@principles/pd-cli 1.138.0 → 1.140.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/dist/commands/__tests__/runtime-activation-nextaction.test.js +3 -3
- package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +1 -1
- package/dist/commands/runtime-activation.d.ts +15 -3
- package/dist/commands/runtime-activation.d.ts.map +1 -1
- package/dist/commands/runtime-activation.js +160 -49
- package/dist/commands/runtime-activation.js.map +1 -1
- package/dist/commands/runtime-artifact-repair.d.ts +58 -0
- package/dist/commands/runtime-artifact-repair.d.ts.map +1 -0
- package/dist/commands/runtime-artifact-repair.js +415 -0
- package/dist/commands/runtime-artifact-repair.js.map +1 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/commands/__tests__/runtime-activation-nextaction.test.ts +5 -3
- package/src/commands/runtime-activation.ts +161 -59
- package/src/commands/runtime-artifact-repair.ts +524 -0
- package/src/index.ts +21 -0
- package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +26 -0
- package/tests/commands/runtime-activation.test.ts +68 -7
- package/tests/commands/runtime-artifact-repair-registration.test.ts +74 -0
- package/tests/commands/runtime-artifact-repair.test.ts +404 -0
- package/tests/e2e/cross-package-acceptance.test.ts +3 -5
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-555 phase 1 — artifact identity drift repair planner (DRY-RUN ONLY).
|
|
3
|
+
*
|
|
4
|
+
* Historical scribe artifacts were written under an older task-id naming
|
|
5
|
+
* scheme (`artificer-scribe-…-<chan>×4`); re-seeded chains reference scribe
|
|
6
|
+
* tasks under the current scheme (`scribe-…-<chan>×3`). The artificer-family
|
|
7
|
+
* resolvers do exact source_task_id lookups, so those artifacts are
|
|
8
|
+
* unreachable and 63 tasks failed permanently with input_invalid.
|
|
9
|
+
*
|
|
10
|
+
* This command ONLY builds a repair plan (migration-plan.json). It never
|
|
11
|
+
* mutates state.db: the connection is opened readonly with
|
|
12
|
+
* bootstrapIfMissing=false (ERR-023 — dry-run must not open writable DBs,
|
|
13
|
+
* and must not create an empty state.db as a side effect).
|
|
14
|
+
*
|
|
15
|
+
* Repair rules (deliberately conservative — no fuzzy matching):
|
|
16
|
+
* - Rule 1 (remap): a `principle` artifact exists whose source_task_id carries
|
|
17
|
+
* the SAME normalized role chain, the SAME full UUID token, AND the SAME
|
|
18
|
+
* trailing channel token as the dependency task id (e.g. a legacy channel
|
|
19
|
+
* repetition-count variant of the dependency's own key). Full-token equality
|
|
20
|
+
* on all three, not substring/prefix guessing. Exactly one match →
|
|
21
|
+
* high-confidence re-key proposal. Downstream-stage artifacts of the same
|
|
22
|
+
* chain (extra role prefixes like `artificer-…`/`evaluator-…`) do NOT match —
|
|
23
|
+
* re-keying them would feed a later stage's output into an earlier slot.
|
|
24
|
+
* - Rule 2 (reconstruct): no artifact found, but the dependency task has a
|
|
25
|
+
* succeeded run with non-empty output_payload → medium-confidence artifact
|
|
26
|
+
* reconstruction proposal.
|
|
27
|
+
* - Anything ambiguous or unconfirmable → needs_human_review. We never guess.
|
|
28
|
+
*
|
|
29
|
+
* CLI gates: cli-1 (strict JSON), cli-2 (exit + return), cli-4 (dry-run
|
|
30
|
+
* default, --confirm refused in this phase), cli-5 (failure path writes
|
|
31
|
+
* nothing to the DB), cli-6 (structured reason + nextAction).
|
|
32
|
+
*/
|
|
33
|
+
import * as fs from 'fs';
|
|
34
|
+
import * as path from 'path';
|
|
35
|
+
import type { Database } from 'better-sqlite3';
|
|
36
|
+
import { SqliteConnection } from '@principles/core/runtime-v2';
|
|
37
|
+
import { resolveWorkspaceDir } from '../resolve-workspace.js';
|
|
38
|
+
import { emitResult, emitError, emitFlagConflict } from '../services/cli-output.js';
|
|
39
|
+
|
|
40
|
+
interface ArtifactRepairOptions {
|
|
41
|
+
workspace?: string;
|
|
42
|
+
dryRun?: boolean;
|
|
43
|
+
confirm?: boolean;
|
|
44
|
+
out?: string;
|
|
45
|
+
json?: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ── Plan types (migration-plan.json contract) ────────────────────────────────
|
|
49
|
+
|
|
50
|
+
export type ArtifactRepairAction =
|
|
51
|
+
| 'remap_source_task_id'
|
|
52
|
+
| 'reconstruct_from_run_payload'
|
|
53
|
+
| 'needs_human_review';
|
|
54
|
+
|
|
55
|
+
export type ArtifactRepairSource =
|
|
56
|
+
| 'old_key_uuid_match'
|
|
57
|
+
| 'run_output_payload'
|
|
58
|
+
| 'direct_key'
|
|
59
|
+
| 'none';
|
|
60
|
+
|
|
61
|
+
export interface ArtifactRepairPlanEntry {
|
|
62
|
+
failed_task_id: string;
|
|
63
|
+
failed_task_kind: string;
|
|
64
|
+
dependency_task_id: string;
|
|
65
|
+
existing_artifact: {
|
|
66
|
+
artifact_id: string;
|
|
67
|
+
artifact_kind: string;
|
|
68
|
+
source_task_id: string;
|
|
69
|
+
} | null;
|
|
70
|
+
artifact_source: ArtifactRepairSource;
|
|
71
|
+
repair_action: ArtifactRepairAction;
|
|
72
|
+
confidence: 'high' | 'medium' | null;
|
|
73
|
+
reason: string;
|
|
74
|
+
proposal: {
|
|
75
|
+
action: 'remap_source_task_id' | 'reconstruct_from_run_payload';
|
|
76
|
+
artifact_id?: string;
|
|
77
|
+
old_source_task_id?: string;
|
|
78
|
+
new_source_task_id?: string;
|
|
79
|
+
run_id?: string;
|
|
80
|
+
artifact_kind?: string;
|
|
81
|
+
validation_status?: string;
|
|
82
|
+
} | null;
|
|
83
|
+
unresolved_dep_count: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface ArtifactRepairPlanSummary {
|
|
87
|
+
scanned_failed_tasks: number;
|
|
88
|
+
rule1_remap: number;
|
|
89
|
+
rule2_reconstruct: number;
|
|
90
|
+
needs_human_review: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface ArtifactRepairPlan {
|
|
94
|
+
generatedAt: string;
|
|
95
|
+
workspace: string;
|
|
96
|
+
dryRun: true;
|
|
97
|
+
summary: ArtifactRepairPlanSummary;
|
|
98
|
+
entries: ArtifactRepairPlanEntry[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── Untrusted-row helpers (rc-1/rc-4/rc-5) ───────────────────────────────────
|
|
102
|
+
|
|
103
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
104
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function readString(row: unknown, key: string): string | null {
|
|
108
|
+
if (!isRecord(row)) return null;
|
|
109
|
+
if (!Object.hasOwn(row, key)) return null;
|
|
110
|
+
const value = row[key];
|
|
111
|
+
return typeof value === 'string' ? value : null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const BOUNDED_FIELD_MAX = 200;
|
|
115
|
+
|
|
116
|
+
function bounded(value: string | null): string | null {
|
|
117
|
+
if (value === null) return null;
|
|
118
|
+
return value.length <= BOUNDED_FIELD_MAX ? value : value.substring(0, BOUNDED_FIELD_MAX);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const FULL_UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;
|
|
122
|
+
|
|
123
|
+
/** Extract the FIRST full canonical UUID token; null when the id has none. */
|
|
124
|
+
function extractFullUuid(id: string): string | null {
|
|
125
|
+
for (const match of id.toLowerCase().matchAll(FULL_UUID_RE)) {
|
|
126
|
+
return match[0];
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Extract the trailing repeated channel token (e.g. `prompt` from
|
|
133
|
+
* `…-prompt-prompt-prompt`). Task ids end with the channel token repeated;
|
|
134
|
+
* requiring equality on UUID and channel disambiguates same-chain tasks
|
|
135
|
+
* across channels without any fuzzy matching.
|
|
136
|
+
*/
|
|
137
|
+
function extractTrailingChannelToken(id: string): string | null {
|
|
138
|
+
const segments = id.split('-');
|
|
139
|
+
const last = segments[segments.length - 1];
|
|
140
|
+
return last ? last : null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Normalize an id to its role chain: strip the UUID token and the trailing
|
|
145
|
+
* repeated channel tokens. `scribe-philosopher-dreamer-<uuid>-prompt×3` →
|
|
146
|
+
* `scribe-philosopher-dreamer`; `artificer-scribe-philosopher-dreamer-<uuid>-
|
|
147
|
+
* prompt×4` → `artificer-scribe-philosopher-dreamer` (a DIFFERENT stage).
|
|
148
|
+
* Rule 1 requires this to be equal so downstream-stage artifacts of the same
|
|
149
|
+
* chain are never re-keyed into an earlier stage's slot.
|
|
150
|
+
*/
|
|
151
|
+
function normalizeRoleChain(id: string): string {
|
|
152
|
+
const withoutUuid = id.replace(FULL_UUID_RE, '');
|
|
153
|
+
const segments = withoutUuid.split('-').filter((t) => t.length > 0);
|
|
154
|
+
if (segments.length > 1) {
|
|
155
|
+
const last = segments[segments.length - 1];
|
|
156
|
+
let i = segments.length;
|
|
157
|
+
while (i > 1 && segments[i - 1] === last) i -= 1;
|
|
158
|
+
segments.length = i;
|
|
159
|
+
}
|
|
160
|
+
return segments.join('-');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Dependency kinds whose pi_artifacts feed downstream runners. */
|
|
164
|
+
const PRODUCER_DEP_KINDS: ReadonlySet<string> = new Set(['dreamer', 'philosopher', 'scribe', 'artificer']);
|
|
165
|
+
|
|
166
|
+
function extractDependencyTaskIds(diagnosticJson: string | null): { ok: true; ids: string[] } | { ok: false; reason: string } {
|
|
167
|
+
if (!diagnosticJson) return { ok: false, reason: 'tasks.diagnostic_json is null' };
|
|
168
|
+
let parsed: unknown;
|
|
169
|
+
try {
|
|
170
|
+
parsed = JSON.parse(diagnosticJson);
|
|
171
|
+
} catch (err) {
|
|
172
|
+
return { ok: false, reason: `diagnostic_json is not valid JSON: ${err instanceof Error ? err.message : String(err)}` };
|
|
173
|
+
}
|
|
174
|
+
if (!isRecord(parsed)) return { ok: false, reason: 'diagnostic_json is not an object' };
|
|
175
|
+
if (!Object.hasOwn(parsed, 'pi_metadata')) return { ok: false, reason: 'diagnostic_json missing pi_metadata' };
|
|
176
|
+
const meta: unknown = parsed.pi_metadata;
|
|
177
|
+
if (!isRecord(meta)) return { ok: false, reason: 'pi_metadata is not an object' };
|
|
178
|
+
if (!Object.hasOwn(meta, 'dependencyTaskIds')) return { ok: false, reason: 'pi_metadata missing dependencyTaskIds' };
|
|
179
|
+
const deps: unknown = meta.dependencyTaskIds;
|
|
180
|
+
if (!Array.isArray(deps)) return { ok: false, reason: 'dependencyTaskIds is not an array' };
|
|
181
|
+
const ids = deps.filter((d): d is string => typeof d === 'string');
|
|
182
|
+
if (ids.length === 0) return { ok: false, reason: 'dependencyTaskIds is empty or contains no string elements' };
|
|
183
|
+
return { ok: true, ids };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── Plan builder ──────────────────────────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
interface DepTaskRow {
|
|
189
|
+
taskId: string;
|
|
190
|
+
taskKind: string | null;
|
|
191
|
+
status: string | null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function loadDepTask(db: Database, taskId: string): DepTaskRow | null {
|
|
195
|
+
const row: unknown = db
|
|
196
|
+
.prepare('SELECT task_id, task_kind, status FROM tasks WHERE task_id = ?')
|
|
197
|
+
.get(taskId);
|
|
198
|
+
if (!isRecord(row)) return null;
|
|
199
|
+
const id = readString(row, 'task_id');
|
|
200
|
+
if (!id) return null;
|
|
201
|
+
return { taskId: id, taskKind: readString(row, 'task_kind'), status: readString(row, 'status') };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function countDirectArtifacts(db: Database, depTaskId: string): number {
|
|
205
|
+
const row: unknown = db
|
|
206
|
+
.prepare("SELECT COUNT(*) AS c FROM pi_artifacts WHERE source_task_id = ? AND artifact_kind = 'principle'")
|
|
207
|
+
.get(depTaskId);
|
|
208
|
+
if (!isRecord(row) || !Object.hasOwn(row, 'c')) return 0;
|
|
209
|
+
const { c } = row;
|
|
210
|
+
return typeof c === 'number' ? c : 0;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
interface CandidateArtifact {
|
|
214
|
+
artifactId: string;
|
|
215
|
+
sourceTaskId: string;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function findOldKeyCandidates(
|
|
219
|
+
db: Database,
|
|
220
|
+
depTaskId: string,
|
|
221
|
+
): CandidateArtifact[] {
|
|
222
|
+
const depUuid = extractFullUuid(depTaskId);
|
|
223
|
+
const depChannel = extractTrailingChannelToken(depTaskId);
|
|
224
|
+
const depRoleChain = normalizeRoleChain(depTaskId);
|
|
225
|
+
if (!depUuid || !depChannel) return [];
|
|
226
|
+
|
|
227
|
+
const rows: unknown[] = db
|
|
228
|
+
.prepare("SELECT artifact_id, source_task_id FROM pi_artifacts WHERE artifact_kind = 'principle'")
|
|
229
|
+
.all();
|
|
230
|
+
const candidates: CandidateArtifact[] = [];
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
if (!isRecord(row)) continue;
|
|
233
|
+
const artifactId = readString(row, 'artifact_id');
|
|
234
|
+
const sourceTaskId = readString(row, 'source_task_id');
|
|
235
|
+
if (!artifactId || !sourceTaskId) continue;
|
|
236
|
+
if (sourceTaskId === depTaskId) continue; // direct key handled separately
|
|
237
|
+
if (extractFullUuid(sourceTaskId) !== depUuid) continue; // exact full-UUID equality
|
|
238
|
+
if (extractTrailingChannelToken(sourceTaskId) !== depChannel) continue;
|
|
239
|
+
if (normalizeRoleChain(sourceTaskId) !== depRoleChain) continue; // same producer stage only
|
|
240
|
+
candidates.push({ artifactId, sourceTaskId });
|
|
241
|
+
}
|
|
242
|
+
return candidates;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function findSucceededRunPayload(
|
|
246
|
+
db: Database,
|
|
247
|
+
depTaskId: string,
|
|
248
|
+
): { runId: string } | null {
|
|
249
|
+
const row: unknown = db
|
|
250
|
+
.prepare(
|
|
251
|
+
`SELECT run_id FROM runs
|
|
252
|
+
WHERE task_id = ? AND execution_status = 'succeeded'
|
|
253
|
+
AND output_payload IS NOT NULL AND TRIM(output_payload) != ''
|
|
254
|
+
ORDER BY started_at DESC, attempt_number DESC
|
|
255
|
+
LIMIT 1`,
|
|
256
|
+
)
|
|
257
|
+
.get(depTaskId);
|
|
258
|
+
if (!isRecord(row)) return null;
|
|
259
|
+
const runId = readString(row, 'run_id');
|
|
260
|
+
return runId ? { runId } : null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function humanReviewEntry(input: {
|
|
264
|
+
failedTaskId: string;
|
|
265
|
+
failedTaskKind: string;
|
|
266
|
+
dependencyTaskId: string;
|
|
267
|
+
reason: string;
|
|
268
|
+
unresolvedDepCount: number;
|
|
269
|
+
}): ArtifactRepairPlanEntry {
|
|
270
|
+
return {
|
|
271
|
+
failed_task_id: input.failedTaskId,
|
|
272
|
+
failed_task_kind: input.failedTaskKind,
|
|
273
|
+
dependency_task_id: input.dependencyTaskId,
|
|
274
|
+
existing_artifact: null,
|
|
275
|
+
artifact_source: 'none',
|
|
276
|
+
repair_action: 'needs_human_review',
|
|
277
|
+
confidence: null,
|
|
278
|
+
reason: bounded(input.reason) ?? input.reason,
|
|
279
|
+
proposal: null,
|
|
280
|
+
unresolved_dep_count: input.unresolvedDepCount,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Build the dry-run repair plan. `db` must come from a readonly connection —
|
|
286
|
+
* this function executes SELECTs only and never mutates state.
|
|
287
|
+
*/
|
|
288
|
+
export function buildArtifactRepairPlan(
|
|
289
|
+
db: Database,
|
|
290
|
+
opts: { workspaceDir: string; generatedAt: string },
|
|
291
|
+
): ArtifactRepairPlan {
|
|
292
|
+
const failedTasks: unknown[] = db
|
|
293
|
+
.prepare(
|
|
294
|
+
`SELECT task_id, task_kind, last_error, diagnostic_json FROM tasks
|
|
295
|
+
WHERE task_kind IN ('dreamer', 'philosopher', 'scribe', 'artificer', 'evaluator')
|
|
296
|
+
AND status = 'failed' AND last_error = 'input_invalid'`,
|
|
297
|
+
)
|
|
298
|
+
.all();
|
|
299
|
+
|
|
300
|
+
const entries: ArtifactRepairPlanEntry[] = [];
|
|
301
|
+
|
|
302
|
+
for (const failedRow of failedTasks) {
|
|
303
|
+
if (!isRecord(failedRow)) continue;
|
|
304
|
+
const failedTaskId = readString(failedRow, 'task_id');
|
|
305
|
+
const failedTaskKind = readString(failedRow, 'task_kind') ?? 'unknown';
|
|
306
|
+
if (!failedTaskId) continue;
|
|
307
|
+
|
|
308
|
+
const deps = extractDependencyTaskIds(readString(failedRow, 'diagnostic_json'));
|
|
309
|
+
if (!deps.ok) {
|
|
310
|
+
entries.push(humanReviewEntry({
|
|
311
|
+
failedTaskId,
|
|
312
|
+
failedTaskKind,
|
|
313
|
+
dependencyTaskId: '',
|
|
314
|
+
reason: deps.reason,
|
|
315
|
+
unresolvedDepCount: 0,
|
|
316
|
+
}));
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// First producer dependency whose artifact cannot be resolved by the
|
|
321
|
+
// exact-key lookup is the repair target; count the rest.
|
|
322
|
+
let blocker: {
|
|
323
|
+
depTaskId: string;
|
|
324
|
+
depTask: DepTaskRow | null;
|
|
325
|
+
directArtifacts: number;
|
|
326
|
+
} | null = null;
|
|
327
|
+
let unresolvedDepCount = 0;
|
|
328
|
+
|
|
329
|
+
for (const depTaskId of deps.ids) {
|
|
330
|
+
const depTask = loadDepTask(db, depTaskId);
|
|
331
|
+
const depKind = depTask?.taskKind;
|
|
332
|
+
if (!depTask || !depKind || !PRODUCER_DEP_KINDS.has(depKind)) continue; // resolver ignores non-producer deps
|
|
333
|
+
const directArtifacts = countDirectArtifacts(db, depTaskId);
|
|
334
|
+
if (directArtifacts > 0) continue; // resolvable — not a blocker
|
|
335
|
+
unresolvedDepCount++;
|
|
336
|
+
if (!blocker) blocker = { depTaskId, depTask, directArtifacts };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (!blocker) {
|
|
340
|
+
entries.push(humanReviewEntry({
|
|
341
|
+
failedTaskId,
|
|
342
|
+
failedTaskKind,
|
|
343
|
+
dependencyTaskId: '',
|
|
344
|
+
reason: 'no unresolved producer dependency found — input_invalid has another cause; inspect the task runs',
|
|
345
|
+
unresolvedDepCount: 0,
|
|
346
|
+
}));
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const { depTaskId, depTask } = blocker;
|
|
351
|
+
|
|
352
|
+
if (!depTask || depTask.status !== 'succeeded') {
|
|
353
|
+
const status = depTask?.status ?? 'missing';
|
|
354
|
+
entries.push(humanReviewEntry({
|
|
355
|
+
failedTaskId,
|
|
356
|
+
failedTaskKind,
|
|
357
|
+
dependencyTaskId: depTaskId,
|
|
358
|
+
reason: `producer dependency task is ${status} — repair requires re-running the dependency, not artifact migration`,
|
|
359
|
+
unresolvedDepCount,
|
|
360
|
+
}));
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Rule 1: unique old-key artifact with identical full UUID + channel token.
|
|
365
|
+
const candidates = findOldKeyCandidates(db, depTaskId);
|
|
366
|
+
const [candidate] = candidates;
|
|
367
|
+
if (candidates.length === 1 && candidate) {
|
|
368
|
+
entries.push({
|
|
369
|
+
failed_task_id: failedTaskId,
|
|
370
|
+
failed_task_kind: failedTaskKind,
|
|
371
|
+
dependency_task_id: depTaskId,
|
|
372
|
+
existing_artifact: {
|
|
373
|
+
artifact_id: candidate.artifactId,
|
|
374
|
+
artifact_kind: 'principle',
|
|
375
|
+
source_task_id: candidate.sourceTaskId,
|
|
376
|
+
},
|
|
377
|
+
artifact_source: 'old_key_uuid_match',
|
|
378
|
+
repair_action: 'remap_source_task_id',
|
|
379
|
+
confidence: 'high',
|
|
380
|
+
reason: `principle artifact exists under a legacy key with identical role-chain+UUID+channel tokens; propose re-keying source_task_id ${candidate.sourceTaskId} → ${depTaskId}`,
|
|
381
|
+
proposal: {
|
|
382
|
+
action: 'remap_source_task_id',
|
|
383
|
+
artifact_id: candidate.artifactId,
|
|
384
|
+
old_source_task_id: candidate.sourceTaskId,
|
|
385
|
+
new_source_task_id: depTaskId,
|
|
386
|
+
},
|
|
387
|
+
unresolved_dep_count: unresolvedDepCount,
|
|
388
|
+
});
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (candidates.length > 1) {
|
|
392
|
+
entries.push(humanReviewEntry({
|
|
393
|
+
failedTaskId,
|
|
394
|
+
failedTaskKind,
|
|
395
|
+
dependencyTaskId: depTaskId,
|
|
396
|
+
reason: `ambiguous legacy artifacts: ${candidates.length} principle rows share the dependency's role-chain+UUID+channel tokens (${candidates.map((c) => c.artifactId).join(', ')})`,
|
|
397
|
+
unresolvedDepCount,
|
|
398
|
+
}));
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Rule 2: reconstruct from the dependency's succeeded run payload.
|
|
403
|
+
const run = findSucceededRunPayload(db, depTaskId);
|
|
404
|
+
if (run) {
|
|
405
|
+
entries.push({
|
|
406
|
+
failed_task_id: failedTaskId,
|
|
407
|
+
failed_task_kind: failedTaskKind,
|
|
408
|
+
dependency_task_id: depTaskId,
|
|
409
|
+
existing_artifact: null,
|
|
410
|
+
artifact_source: 'run_output_payload',
|
|
411
|
+
repair_action: 'reconstruct_from_run_payload',
|
|
412
|
+
confidence: 'medium',
|
|
413
|
+
reason: `no principle artifact under any key, but succeeded run ${run.runId} has output_payload; propose reconstructing a principle artifact for ${depTaskId}`,
|
|
414
|
+
proposal: {
|
|
415
|
+
action: 'reconstruct_from_run_payload',
|
|
416
|
+
run_id: run.runId,
|
|
417
|
+
new_source_task_id: depTaskId,
|
|
418
|
+
artifact_kind: 'principle',
|
|
419
|
+
validation_status: 'pending',
|
|
420
|
+
},
|
|
421
|
+
unresolved_dep_count: unresolvedDepCount,
|
|
422
|
+
});
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
entries.push(humanReviewEntry({
|
|
427
|
+
failedTaskId,
|
|
428
|
+
failedTaskKind,
|
|
429
|
+
dependencyTaskId: depTaskId,
|
|
430
|
+
reason: 'no principle artifact under any resolvable key and no succeeded run output_payload to reconstruct from',
|
|
431
|
+
unresolvedDepCount,
|
|
432
|
+
}));
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const summary: ArtifactRepairPlanSummary = {
|
|
436
|
+
scanned_failed_tasks: entries.length,
|
|
437
|
+
rule1_remap: entries.filter((e) => e.repair_action === 'remap_source_task_id').length,
|
|
438
|
+
rule2_reconstruct: entries.filter((e) => e.repair_action === 'reconstruct_from_run_payload').length,
|
|
439
|
+
needs_human_review: entries.filter((e) => e.repair_action === 'needs_human_review').length,
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
return {
|
|
443
|
+
generatedAt: opts.generatedAt,
|
|
444
|
+
workspace: opts.workspaceDir,
|
|
445
|
+
dryRun: true,
|
|
446
|
+
summary,
|
|
447
|
+
entries,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// ── CLI handler ───────────────────────────────────────────────────────────────
|
|
452
|
+
|
|
453
|
+
interface ArtifactRepairCliResult {
|
|
454
|
+
ok: true;
|
|
455
|
+
dryRun: true;
|
|
456
|
+
planFile: string;
|
|
457
|
+
summary: ArtifactRepairPlanSummary;
|
|
458
|
+
nextAction: string;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function formatTextOutput(output: ArtifactRepairCliResult): string {
|
|
462
|
+
const lines: string[] = [];
|
|
463
|
+
lines.push(`Artifact Repair (dry-run, PRI-555 phase 1)`);
|
|
464
|
+
lines.push(` plan file: ${output.planFile}`);
|
|
465
|
+
lines.push(` scanned failed: ${output.summary.scanned_failed_tasks}`);
|
|
466
|
+
lines.push(` Rule-1 remap: ${output.summary.rule1_remap}`);
|
|
467
|
+
lines.push(` Rule-2 reconstruct: ${output.summary.rule2_reconstruct}`);
|
|
468
|
+
lines.push(` needs human review: ${output.summary.needs_human_review}`);
|
|
469
|
+
lines.push(` next action: ${output.nextAction}`);
|
|
470
|
+
return lines.join('\n');
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export async function handleRuntimeArtifactRepair(opts: ArtifactRepairOptions): Promise<void> {
|
|
474
|
+
if (opts.dryRun && opts.confirm) {
|
|
475
|
+
const exitCode = emitFlagConflict({ json: opts.json ?? false });
|
|
476
|
+
process.exit(exitCode);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (opts.confirm) {
|
|
480
|
+
// PRI-555 phase 1 is dry-run only: applying a plan mutates production
|
|
481
|
+
// state.db and must stay a deliberate, owner-approved follow-up.
|
|
482
|
+
const reason = '--confirm is not implemented: artifact repair ships dry-run only in PRI-555 phase 1';
|
|
483
|
+
const nextAction = 'Review migration-plan.json with the owner; apply confirmed entries via the runbook in docs/fix/pri-554-556-555-fix-report.md.';
|
|
484
|
+
if (opts.json ?? false) {
|
|
485
|
+
console.log(JSON.stringify({ ok: false, reason, nextAction }, null, 2));
|
|
486
|
+
} else {
|
|
487
|
+
console.error(`Error: ${reason}`);
|
|
488
|
+
console.error(`Next action: ${nextAction}`);
|
|
489
|
+
}
|
|
490
|
+
process.exit(1);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
|
|
495
|
+
const planPath = opts.out ? path.resolve(opts.out) : path.join(process.cwd(), 'migration-plan.json');
|
|
496
|
+
|
|
497
|
+
// ERR-023: dry-run opens the DB readonly, and must not bootstrap an empty
|
|
498
|
+
// state.db either — a missing state.db is an error, not a fresh workspace.
|
|
499
|
+
let conn: SqliteConnection | null = null;
|
|
500
|
+
try {
|
|
501
|
+
conn = new SqliteConnection({ workspaceDir, readonly: true, bootstrapIfMissing: false });
|
|
502
|
+
const plan = buildArtifactRepairPlan(conn.getDb(), {
|
|
503
|
+
workspaceDir,
|
|
504
|
+
generatedAt: new Date().toISOString(),
|
|
505
|
+
});
|
|
506
|
+
fs.writeFileSync(planPath, JSON.stringify(plan, null, 2), 'utf8');
|
|
507
|
+
|
|
508
|
+
const result: ArtifactRepairCliResult = {
|
|
509
|
+
ok: true,
|
|
510
|
+
dryRun: true,
|
|
511
|
+
planFile: planPath,
|
|
512
|
+
summary: plan.summary,
|
|
513
|
+
nextAction: 'Review migration-plan.json (Rule-1 remap proposals first). Nothing has been modified; wait for owner confirmation before applying.',
|
|
514
|
+
};
|
|
515
|
+
emitResult(result, { json: opts.json ?? false, formatText: formatTextOutput });
|
|
516
|
+
} catch (err) {
|
|
517
|
+
process.exitCode = emitError(err, {
|
|
518
|
+
json: opts.json ?? false,
|
|
519
|
+
nextAction: 'Verify --workspace points to a workspace with an initialized .pd/state.db (pd runtime init), then retry.',
|
|
520
|
+
});
|
|
521
|
+
} finally {
|
|
522
|
+
try { conn?.close(); } catch { /* best-effort */ }
|
|
523
|
+
}
|
|
524
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -48,6 +48,7 @@ import { handleRuntimeDiagnosticsExport } from './commands/runtime-diagnostics-e
|
|
|
48
48
|
import { registerRuntimeCompatibilityScanCommand } from './commands/runtime-compatibility-scan.js';
|
|
49
49
|
import { handleRuntimeRecoverySweep } from './commands/runtime-recovery.js';
|
|
50
50
|
import { handleRuntimeRecoveryFailedTasks } from './commands/runtime-recovery-failed-tasks.js';
|
|
51
|
+
import { handleRuntimeArtifactRepair } from './commands/runtime-artifact-repair.js';
|
|
51
52
|
import {
|
|
52
53
|
handleRuntimeActivationDeactivate,
|
|
53
54
|
handleRuntimeActivationList,
|
|
@@ -699,6 +700,26 @@ const recoveryCmd = runtimeCmd
|
|
|
699
700
|
.command('recovery', { hidden: true })
|
|
700
701
|
.description('Runtime V2 lease recovery operations');
|
|
701
702
|
|
|
703
|
+
// PRI-555 phase 1: dry-run-only artifact identity drift repair planner.
|
|
704
|
+
runtimeCmd
|
|
705
|
+
.command('artifact-repair')
|
|
706
|
+
.description('Plan repairs for unreachable scribe artifacts (dry-run only; writes migration-plan.json, never modifies state.db)')
|
|
707
|
+
.option('-w, --workspace <path>', 'Workspace directory')
|
|
708
|
+
.option('--dry-run', 'Build migration-plan.json only (default)')
|
|
709
|
+
.option('--confirm', 'Not implemented in this phase — refused')
|
|
710
|
+
.option('--out <path>', 'Output path for migration-plan.json (default: ./migration-plan.json)')
|
|
711
|
+
.option('--json', 'Output raw JSON')
|
|
712
|
+
.action(async (opts) => {
|
|
713
|
+
await handleRuntimeArtifactRepair({
|
|
714
|
+
workspace: opts.workspace,
|
|
715
|
+
dryRun: opts.dryRun,
|
|
716
|
+
confirm: opts.confirm,
|
|
717
|
+
out: opts.out,
|
|
718
|
+
json: opts.json,
|
|
719
|
+
});
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
|
|
702
723
|
recoveryCmd
|
|
703
724
|
.command('sweep')
|
|
704
725
|
.description('Detect and optionally recover expired leases')
|
|
@@ -85,6 +85,14 @@ describe('pd activation promote — flag wiring (CLI gate rule 7)', () => {
|
|
|
85
85
|
expect(opt?.long).toBe('--json');
|
|
86
86
|
});
|
|
87
87
|
|
|
88
|
+
it.each(['--artifact-id', '--artifact-digest', '--control-version', '--idempotency-key', '--reason', '--note'])(
|
|
89
|
+
'registers Owner authority binding option %s', (flag) => {
|
|
90
|
+
const program = freshProgram();
|
|
91
|
+
const promoteCmd = registerRuntimeActivationPromoteCommand(program.command('activation'));
|
|
92
|
+
expect(promoteCmd.options.find(option => option.long === flag)).toBeDefined();
|
|
93
|
+
},
|
|
94
|
+
);
|
|
95
|
+
|
|
88
96
|
it('registers --activation-id as required option', () => {
|
|
89
97
|
const program = freshProgram();
|
|
90
98
|
const activationCmd = program.command('activation');
|
|
@@ -209,6 +217,24 @@ describe('pd activation promote — flag wiring (CLI gate rule 7)', () => {
|
|
|
209
217
|
expect(captured.opts?.workspace).toBe('/tmp/test');
|
|
210
218
|
});
|
|
211
219
|
|
|
220
|
+
it('parses all Owner authority binding values through the real command', async () => {
|
|
221
|
+
const program = freshProgram();
|
|
222
|
+
const promoteCmd = registerRuntimeActivationPromoteCommand(program.command('activation'));
|
|
223
|
+
const captured: CapturedAction = { opts: null };
|
|
224
|
+
attachCapture(promoteCmd, captured);
|
|
225
|
+
|
|
226
|
+
await program.parseAsync([
|
|
227
|
+
'node', 'pd', 'activation', 'promote', '--activation-id', 'act-1',
|
|
228
|
+
'--artifact-id', 'art-1', '--artifact-digest', 'sha256:one', '--control-version', '7',
|
|
229
|
+
'--idempotency-key', 'idem-1', '--reason', 'owner_review', '--note', 'reviewed', '--confirm',
|
|
230
|
+
]);
|
|
231
|
+
|
|
232
|
+
expect(captured.opts).toMatchObject({
|
|
233
|
+
artifactId: 'art-1', artifactDigest: 'sha256:one', controlVersion: 7,
|
|
234
|
+
idempotencyKey: 'idem-1', reason: 'owner_review', note: 'reviewed', confirm: true,
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
212
238
|
it('rejects missing --activation-id (required option)', async () => {
|
|
213
239
|
const program = freshProgram();
|
|
214
240
|
const activationCmd = program.command('activation');
|