create-principles-disciple 1.89.0 → 1.90.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/console/dist/ui/api.d.ts +2 -1
  2. package/console/dist/ui/api.js +7 -1
  3. package/console/dist/ui/i18n/en.json +18 -1
  4. package/console/dist/ui/i18n/zh-CN.json +18 -1
  5. package/console/dist/ui/pages/focus/FocusPage.js +48 -4
  6. package/console/dist/ui/pages/principles/PrincipleDetailPage.js +70 -2
  7. package/console/dist/web/assets/app.js +1541 -1223
  8. package/console/package.json +1 -1
  9. package/core/dist/prompt-builder/__tests__/routing-guidance.test.d.ts +1 -2
  10. package/core/dist/prompt-builder/__tests__/routing-guidance.test.d.ts.map +1 -1
  11. package/core/dist/prompt-builder/__tests__/routing-guidance.test.js +1 -2
  12. package/core/dist/prompt-builder/__tests__/routing-guidance.test.js.map +1 -1
  13. package/core/dist/prompt-builder/routing-guidance.d.ts +0 -1
  14. package/core/dist/prompt-builder/routing-guidance.d.ts.map +1 -1
  15. package/core/dist/prompt-builder/routing-guidance.js +0 -1
  16. package/core/dist/prompt-builder/routing-guidance.js.map +1 -1
  17. package/core/dist/runtime-v2/__tests__/architecture-regression.test.js +5 -43
  18. package/core/dist/runtime-v2/__tests__/architecture-regression.test.js.map +1 -1
  19. package/core/dist/runtime-v2/adapter/__tests__/pi-ai-runtime-adapter.test.js +205 -2
  20. package/core/dist/runtime-v2/adapter/__tests__/pi-ai-runtime-adapter.test.js.map +1 -1
  21. package/core/dist/runtime-v2/adapter/__tests__/schema-prompt-adapter.test.js +17 -1
  22. package/core/dist/runtime-v2/adapter/__tests__/schema-prompt-adapter.test.js.map +1 -1
  23. package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.d.ts +4 -1
  24. package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  25. package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.js +6 -3
  26. package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.js.map +1 -1
  27. package/core/dist/runtime-v2/adapter/tools/diagnostician-tool.d.ts +20 -7
  28. package/core/dist/runtime-v2/adapter/tools/diagnostician-tool.d.ts.map +1 -1
  29. package/core/dist/runtime-v2/adapter/tools/diagnostician-tool.js +19 -3
  30. package/core/dist/runtime-v2/adapter/tools/diagnostician-tool.js.map +1 -1
  31. package/core/dist/runtime-v2/feature-flags/__tests__/plugin-surface-registry.test.js +3 -3
  32. package/core/dist/runtime-v2/feature-flags/__tests__/plugin-surface-registry.test.js.map +1 -1
  33. package/core/dist/runtime-v2/feature-flags/plugin-surface-registry.d.ts.map +1 -1
  34. package/core/dist/runtime-v2/feature-flags/plugin-surface-registry.js +0 -18
  35. package/core/dist/runtime-v2/feature-flags/plugin-surface-registry.js.map +1 -1
  36. package/package.json +1 -1
  37. package/plugin/dist/hooks/prompt.js +4 -5
  38. package/plugin/dist/index.js +0 -83
  39. package/plugin/package.json +1 -1
  40. package/plugin/dist/core/local-worker-routing.d.ts +0 -124
  41. package/plugin/dist/core/local-worker-routing.js +0 -216
  42. package/plugin/dist/core/model-deployment-registry.d.ts +0 -218
  43. package/plugin/dist/core/model-deployment-registry.js +0 -502
  44. package/plugin/dist/core/model-training-registry.d.ts +0 -295
  45. package/plugin/dist/core/model-training-registry.js +0 -474
  46. package/plugin/dist/core/promotion-gate.d.ts +0 -243
  47. package/plugin/dist/core/promotion-gate.js +0 -554
  48. package/plugin/dist/core/shadow-observation-registry.d.ts +0 -217
  49. package/plugin/dist/core/shadow-observation-registry.js +0 -280
  50. package/plugin/dist/utils/shadow-fingerprint.d.ts +0 -16
  51. package/plugin/dist/utils/shadow-fingerprint.js +0 -34
@@ -1,554 +0,0 @@
1
- /**
2
- * Promotion Gate — Checkpoint Promotion State Machine and Gate Logic
3
- * ==================================================================
4
- *
5
- * PURPOSE: Control when a checkpoint can advance from training → shadow → promotion.
6
- * Training success alone is not enough — a checkpoint must prove it improves
7
- * bounded worker behavior under the existing offline benchmark and does not
8
- * regress runtime safety signals.
9
- *
10
- * PROMOTION STATES:
11
- * - rejected: The checkpoint must not be routed
12
- * - candidate_only: The checkpoint is valid but not yet ready for shadow
13
- * - shadow_ready: The checkpoint may enter controlled shadow rollout
14
- * - promotable: The checkpoint may replace the active checkpoint
15
- *
16
- * STATE TRANSITIONS:
17
- * training_completed
18
- * ↓
19
- * candidate_only ←── (eval attached, lineage complete)
20
- * ↓
21
- * shadow_ready ←── (positive delta, safe constraints)
22
- * ↓
23
- * promotable ←── (shadow window passed, orchestrator review passed)
24
- * ↓
25
- * deployed
26
- *
27
- * PRIMARY OBJECTIVE:
28
- * maximize reduced_prompt_holdout_delta
29
- *
30
- * CONSTRAINT METRICS (must all pass for promotion):
31
- * - arbiterRejectRate <= baseline + allowedMargin
32
- * - executabilityRejectRate <= baseline + allowedMargin
33
- * - reviewedSubsetQuality >= baseline
34
- * - routingScopeNotExpanded == true
35
- *
36
- * DESIGN CONSTRAINTS:
37
- * - No automatic promotion without explicit gate approval
38
- * - Orchestrator review remains mandatory for all promotions
39
- * - Rollback path must be always available
40
- * - First rollout limited to `local-reader` only
41
- */
42
- import * as fs from 'fs';
43
- import * as path from 'path';
44
- import * as crypto from 'crypto';
45
- import { withLock } from '../utils/file-lock.js';
46
- import { atomicWriteFileSync } from '../utils/io.js';
47
- import { getCheckpoint, getEvalSummary, } from './model-training-registry.js';
48
- import { computeShadowStats } from './shadow-observation-registry.js';
49
- // ---------------------------------------------------------------------------
50
- // Constants
51
- // ---------------------------------------------------------------------------
52
- /**
53
- * Candidate delta must exceed this to enter shadow_ready.
54
- */
55
- export const DEFAULT_MIN_DELTA = 0.05;
56
- /**
57
- * Default allowed margin for constraint metrics.
58
- * Constraint metrics can regress by at most this amount.
59
- */
60
- export const DEFAULT_ALLOWED_MARGIN = 0.05;
61
- /**
62
- * Allowed worker profiles for Phase 7 shadow rollout.
63
- * Only bounded local workers eligible. local-reader first, local-editor deferred.
64
- */
65
- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Reason: reserved for Phase 7 shadow rollout profile validation
66
- const ALLOWED_ROLLOUT_PROFILES = ['local-reader'];
67
- /**
68
- * Registry file for promotion records.
69
- */
70
- const PROMOTION_REGISTRY_FILE = 'promotion-registry.json';
71
- /**
72
- * Minimum shadow window duration in milliseconds.
73
- * A checkpoint must remain in shadow_ready for at least this duration
74
- * before it can be promoted to promotable.
75
- *
76
- * Phase 7 default: 1 hour (3600000 ms)
77
- * This gives time for real-world feedback before full promotion.
78
- */
79
- export const MIN_SHADOW_WINDOW_MS = 60 * 60 * 1000; // 1 hour
80
- // ---------------------------------------------------------------------------
81
- // Registry Path
82
- // ---------------------------------------------------------------------------
83
- function getRegistryPath(stateDir) {
84
- return path.join(stateDir, PROMOTION_REGISTRY_FILE);
85
- }
86
- /**
87
- * Ensure the registry directory exists.
88
- */
89
- function ensureRegistryDir(stateDir) {
90
- const registryPath = getRegistryPath(stateDir);
91
- const dir = path.dirname(registryPath);
92
- if (!fs.existsSync(dir)) {
93
- fs.mkdirSync(dir, { recursive: true });
94
- }
95
- }
96
- // ---------------------------------------------------------------------------
97
- // File Operations
98
- // ---------------------------------------------------------------------------
99
- /**
100
- * Read the registry from disk. Returns empty registry if missing.
101
- */
102
- function readRegistry(stateDir) {
103
- const registryPath = getRegistryPath(stateDir);
104
- if (!fs.existsSync(registryPath)) {
105
- return { promotions: [] };
106
- }
107
- try {
108
- const content = fs.readFileSync(registryPath, 'utf-8');
109
- return JSON.parse(content);
110
- }
111
- catch (err) {
112
- console.warn(`[promotion-gate] Registry corrupted at ${registryPath}, recovering with empty state: ${String(err)}`);
113
- return { promotions: [] };
114
- }
115
- }
116
- /**
117
- * Write the registry to disk atomically.
118
- */
119
- function writeRegistry(stateDir, registry) {
120
- ensureRegistryDir(stateDir);
121
- const registryPath = getRegistryPath(stateDir);
122
- atomicWriteFileSync(registryPath, JSON.stringify(registry, null, 2));
123
- }
124
- /**
125
- * Execute a read-modify-write under an exclusive file lock.
126
- */
127
- function withPromotionRegistryLock(stateDir, fn) {
128
- const registryPath = getRegistryPath(stateDir);
129
- return withLock(registryPath, () => {
130
- const registry = readRegistry(stateDir);
131
- return fn(registry);
132
- });
133
- }
134
- /**
135
- * Evaluate whether a checkpoint passes the promotion gate.
136
- *
137
- * @param stateDir - Workspace state directory
138
- * @param params - Evaluation parameters
139
- * @returns PromotionGateResult with pass/fail and details
140
- *
141
- * FAIL-CLOSED: Returns { passes: false } if:
142
- * - No eval attached to checkpoint
143
- * - Delta is negative or below threshold
144
- * - Any constraint metric regresses beyond allowed margin
145
- * - Profile is not in allowed rollout list
146
- */
147
- export function evaluatePromotionGate(stateDir, params) {
148
- const { checkpointId, baselineMetrics, minDelta = DEFAULT_MIN_DELTA, allowedMargin = DEFAULT_ALLOWED_MARGIN, } = params;
149
- const blockers = [];
150
- const constraintChecks = [];
151
- // --- Check 1: Checkpoint exists ---
152
- const checkpoint = getCheckpoint(stateDir, checkpointId);
153
- if (!checkpoint) {
154
- blockers.push(`Checkpoint not found: ${checkpointId}`);
155
- return {
156
- passes: false,
157
- blockers,
158
- constraintChecks: [],
159
- deltaCheck: { actual: 0, threshold: minDelta, passed: false },
160
- evidenceSummary: {
161
- evidenceMode: 'eval-proxy',
162
- shadowSampleCount: 0,
163
- deltaSource: 'eval',
164
- },
165
- };
166
- }
167
- // --- Check 2: Has eval attached ---
168
- if (!checkpoint.lastEvalSummaryRef) {
169
- blockers.push(`Checkpoint ${checkpointId} has no eval summary attached. ` +
170
- `Run benchmark evaluation before promotion gate.`);
171
- return {
172
- passes: false,
173
- blockers,
174
- constraintChecks: [],
175
- deltaCheck: { actual: 0, threshold: minDelta, passed: false },
176
- evidenceSummary: {
177
- evidenceMode: 'eval-proxy',
178
- shadowSampleCount: 0,
179
- deltaSource: 'eval',
180
- },
181
- };
182
- }
183
- // --- Check 3: Get eval summary ---
184
- const evalSummary = getEvalSummary(stateDir, checkpoint.lastEvalSummaryRef);
185
- if (!evalSummary) {
186
- blockers.push(`Eval summary '${checkpoint.lastEvalSummaryRef}' not found. ` +
187
- `Cannot evaluate promotion gate without valid eval.`);
188
- return {
189
- passes: false,
190
- blockers,
191
- constraintChecks: [],
192
- deltaCheck: { actual: 0, threshold: minDelta, passed: false },
193
- evidenceSummary: {
194
- evidenceMode: 'eval-proxy',
195
- shadowSampleCount: 0,
196
- deltaSource: 'eval',
197
- },
198
- };
199
- }
200
- // --- Check 4: Delta must be positive and above threshold ---
201
- const { delta } = evalSummary;
202
- const deltaCheck = {
203
- actual: delta,
204
- threshold: minDelta,
205
- passed: delta >= minDelta,
206
- };
207
- if (!deltaCheck.passed) {
208
- blockers.push(`Reduced-prompt holdout delta (${delta.toFixed(4)}) is below threshold (${minDelta}). ` +
209
- `Checkpoint must show positive improvement to be promoted.`);
210
- }
211
- // --- Check 5: Arbiter reject rate constraint ---
212
- // PREFER real shadow evidence over eval verdict proxy
213
- // Shadow evidence comes from actual runtime routing decisions
214
- const shadowStats = computeShadowStats(stateDir, { checkpointId });
215
- let arbiterRejectRate;
216
- let arbiterRejectSource;
217
- if (shadowStats && shadowStats.isStatisticallySignificant) {
218
- // Use real shadow evidence: reject rate from shadow routing
219
- arbiterRejectRate = shadowStats.rejectRate;
220
- arbiterRejectSource = 'shadow';
221
- }
222
- else {
223
- // Fall back to eval verdict proxy (Phase 7 initial state)
224
- // This is a coarse approximation: 'fail' verdict maps to 100% reject
225
- arbiterRejectRate = evalSummary.verdict === 'fail' ? 1 : 0;
226
- arbiterRejectSource = 'eval-proxy';
227
- }
228
- const arbiterRejectCheck = {
229
- constraint: 'arbiterRejectRate',
230
- actual: arbiterRejectRate,
231
- baseline: baselineMetrics.arbiterRejectRate,
232
- threshold: baselineMetrics.arbiterRejectRate + allowedMargin,
233
- passed: arbiterRejectRate <= baselineMetrics.arbiterRejectRate + allowedMargin,
234
- source: arbiterRejectSource,
235
- };
236
- constraintChecks.push(arbiterRejectCheck);
237
- if (!arbiterRejectCheck.passed) {
238
- blockers.push(`arbiterRejectRate regressed: ${arbiterRejectRate.toFixed(4)} > ${arbiterRejectCheck.threshold.toFixed(4)} ` +
239
- `(baseline: ${baselineMetrics.arbiterRejectRate.toFixed(4)}, margin: ${allowedMargin}) ` +
240
- `[source: ${arbiterRejectSource}${shadowStats ? `, n=${shadowStats.totalCount}` : ''}]`);
241
- }
242
- // --- Check 6: Executability reject rate constraint ---
243
- // PREFER real shadow evidence: escalation rate + profile rejection rate
244
- let executabilityRejectRate;
245
- let executabilityRejectSource;
246
- if (shadowStats && shadowStats.isStatisticallySignificant) {
247
- // Use real shadow evidence: escalation + profile rejection from routing
248
- executabilityRejectRate = shadowStats.escalationRate + shadowStats.profileRejectedRate;
249
- executabilityRejectSource = 'shadow';
250
- }
251
- else {
252
- // Fall back to eval verdict proxy
253
- // This is a coarse approximation
254
- executabilityRejectRate = evalSummary.verdict === 'fail' ? 0.1 : 0;
255
- executabilityRejectSource = 'eval-proxy';
256
- }
257
- const executabilityRejectCheck = {
258
- constraint: 'executabilityRejectRate',
259
- actual: executabilityRejectRate,
260
- baseline: baselineMetrics.executabilityRejectRate,
261
- threshold: baselineMetrics.executabilityRejectRate + allowedMargin,
262
- passed: executabilityRejectRate <= baselineMetrics.executabilityRejectRate + allowedMargin,
263
- source: executabilityRejectSource,
264
- };
265
- constraintChecks.push(executabilityRejectCheck);
266
- if (!executabilityRejectCheck.passed) {
267
- blockers.push(`executabilityRejectRate regressed: ${executabilityRejectRate.toFixed(4)} > ${executabilityRejectCheck.threshold.toFixed(4)} ` +
268
- `(baseline: ${baselineMetrics.executabilityRejectRate.toFixed(4)}, margin: ${allowedMargin}) ` +
269
- `[source: ${executabilityRejectSource}${shadowStats ? `, n=${shadowStats.totalCount}` : ''}]`);
270
- }
271
- // --- Check 7: Reviewed subset quality constraint ---
272
- // Use eval score as proxy for quality
273
- const reviewedSubsetQuality = evalSummary.candidateScore;
274
- const qualityCheck = {
275
- constraint: 'reviewedSubsetQuality',
276
- actual: reviewedSubsetQuality,
277
- baseline: baselineMetrics.reviewedSubsetQuality,
278
- threshold: baselineMetrics.reviewedSubsetQuality - allowedMargin,
279
- passed: reviewedSubsetQuality >= baselineMetrics.reviewedSubsetQuality - allowedMargin,
280
- };
281
- constraintChecks.push(qualityCheck);
282
- if (!qualityCheck.passed) {
283
- blockers.push(`reviewedSubsetQuality regressed: ${reviewedSubsetQuality.toFixed(4)} < ${qualityCheck.threshold.toFixed(4)} ` +
284
- `(baseline: ${baselineMetrics.reviewedSubsetQuality.toFixed(4)})`);
285
- }
286
- // --- Determine if passes ---
287
- const allPassed = deltaCheck.passed &&
288
- arbiterRejectCheck.passed &&
289
- executabilityRejectCheck.passed &&
290
- qualityCheck.passed;
291
- // --- Suggest state based on checks ---
292
- let suggestedState;
293
- if (allPassed) {
294
- suggestedState = 'candidate_only';
295
- // If delta is strong enough, could be shadow_ready directly
296
- if (delta >= minDelta * 2) {
297
- suggestedState = 'shadow_ready';
298
- }
299
- }
300
- else {
301
- suggestedState = 'rejected';
302
- }
303
- const evidenceMode = arbiterRejectSource === 'shadow' && executabilityRejectSource === 'shadow'
304
- ? 'shadow'
305
- : arbiterRejectSource === 'eval-proxy' && executabilityRejectSource === 'eval-proxy'
306
- ? 'eval-proxy'
307
- : 'mixed';
308
- return {
309
- passes: allPassed,
310
- suggestedState,
311
- blockers,
312
- constraintChecks,
313
- deltaCheck,
314
- evidenceSummary: {
315
- evidenceMode,
316
- shadowSampleCount: shadowStats?.totalCount ?? 0,
317
- deltaSource: 'eval',
318
- },
319
- };
320
- }
321
- /**
322
- * Advance a checkpoint's promotion state.
323
- *
324
- * @param stateDir - Workspace state directory
325
- * @param params - Advancement parameters
326
- * @returns The updated PromotionRecord
327
- *
328
- * @throws Error if gate evaluation fails
329
- * @throws Error if state transition is not allowed
330
- */
331
- export function advancePromotion(stateDir, params) {
332
- const { checkpointId, targetProfile, baselineMetrics, orchestratorReviewPassed = false, reviewNote, minDelta = DEFAULT_MIN_DELTA, allowedMargin = DEFAULT_ALLOWED_MARGIN, } = params;
333
- // First, evaluate the gate
334
- const gateResult = evaluatePromotionGate(stateDir, {
335
- checkpointId,
336
- targetProfile,
337
- baselineMetrics,
338
- minDelta,
339
- allowedMargin,
340
- });
341
- // Find existing promotion record (if any) - need this to know current state
342
- return withPromotionRegistryLock(stateDir, (registry) => {
343
- const now = new Date().toISOString();
344
- const existingIdx = registry.promotions.findIndex((p) => p.checkpointId === checkpointId);
345
- const currentState = existingIdx >= 0 ? registry.promotions[existingIdx].state : 'candidate_only';
346
- // Determine the target state based on current state, gate result, and review
347
- //
348
- // STATE TRANSITION RULES:
349
- // - Any state → rejected: if gate fails
350
- // - rejected/candidate_only → candidate_only: if gate passes but no review yet
351
- // - shadow_ready → promotable: if gate passes + review + shadow window elapsed
352
- // - rejected → candidate_only/shadow_ready: allowed via re-evaluation
353
- // (new eval data may reverse a previous rejection)
354
- //
355
- let targetState;
356
- if (!gateResult.passes) {
357
- targetState = 'rejected';
358
- }
359
- else if (!orchestratorReviewPassed) {
360
- // Gate passed but need orchestrator review before shadow_ready
361
- // Review is ALWAYS required to reach shadow_ready, regardless of delta strength
362
- targetState = 'candidate_only';
363
- }
364
- else {
365
- // Gate passed and orchestrator review passed: advance one level
366
- // Only go to promotable if already at shadow_ready; otherwise advance to shadow_ready
367
- if (currentState === 'shadow_ready') {
368
- // Check shadow window duration before allowing promotion
369
- const existing = existingIdx >= 0 ? registry.promotions[existingIdx] : null;
370
- const shadowStartedAt = existing?.shadowStartedAt;
371
- if (shadowStartedAt) {
372
- const shadowElapsed = Date.now() - new Date(shadowStartedAt).getTime();
373
- if (shadowElapsed < MIN_SHADOW_WINDOW_MS) {
374
- // Shadow window not elapsed yet — stay at shadow_ready
375
- targetState = 'shadow_ready';
376
- }
377
- else {
378
- // Shadow window elapsed — allow promotion to promotable
379
- targetState = 'promotable';
380
- }
381
- }
382
- else {
383
- // No shadowStartedAt, allow promotion (backward compat)
384
- targetState = 'promotable';
385
- }
386
- }
387
- else {
388
- // At candidate_only (or new), advance to shadow_ready
389
- targetState = 'shadow_ready';
390
- }
391
- }
392
- // Get previous promotion ID for chain
393
- const previousPromotionId = existingIdx >= 0
394
- ? registry.promotions[existingIdx].promotionId
395
- : undefined;
396
- // Get checkpoint info for lineage
397
- const checkpoint = getCheckpoint(stateDir, checkpointId);
398
- const evalSummary = checkpoint?.lastEvalSummaryRef
399
- ? getEvalSummary(stateDir, checkpoint.lastEvalSummaryRef)
400
- : null;
401
- // Get current delta
402
- const reducedPromptDelta = evalSummary?.delta ?? 0;
403
- // Create/update promotion record
404
- const promotion = {
405
- promotionId: existingIdx >= 0
406
- ? registry.promotions[existingIdx].promotionId
407
- : crypto.randomUUID(),
408
- checkpointId,
409
- state: targetState,
410
- targetProfile,
411
- targetModelFamily: checkpoint?.targetModelFamily ?? 'unknown',
412
- reducedPromptDelta,
413
- constraintMetrics: {
414
- arbiterRejectRate: evalSummary?.verdict === 'fail' ? 1 : 0,
415
- executabilityRejectRate: evalSummary?.verdict === 'fail' ? 0.1 : 0,
416
- reviewedSubsetQuality: evalSummary?.candidateScore ?? 0,
417
- routingScopeNotExpanded: true, // Always true in Phase 7
418
- },
419
- baselineMetrics,
420
- orchestratorReviewPassed,
421
- reviewNote,
422
- stateChangedAt: now,
423
- createdAt: existingIdx >= 0
424
- ? registry.promotions[existingIdx].createdAt
425
- : now,
426
- shadowStartedAt: (targetState === 'shadow_ready' || targetState === 'promotable')
427
- ? (() => {
428
- const existing = existingIdx >= 0 ? registry.promotions[existingIdx] : null;
429
- // Only preserve shadowStartedAt if the checkpoint was already on the
430
- // shadow path (shadow_ready or promotable). A demotion to candidate_only
431
- // or rejected means the next shadow entry is a fresh start — use now.
432
- if (existing?.shadowStartedAt &&
433
- (existing.state === 'shadow_ready' || existing.state === 'promotable')) {
434
- return existing.shadowStartedAt;
435
- }
436
- return now;
437
- })()
438
- : existingIdx >= 0
439
- ? registry.promotions[existingIdx].shadowStartedAt
440
- : undefined,
441
- promotableAt: targetState === 'promotable'
442
- ? now
443
- : existingIdx >= 0
444
- ? registry.promotions[existingIdx].promotableAt
445
- : undefined,
446
- previousPromotionId,
447
- };
448
- if (existingIdx >= 0) {
449
- registry.promotions[existingIdx] = promotion;
450
- }
451
- else {
452
- registry.promotions.push(promotion);
453
- }
454
- writeRegistry(stateDir, registry);
455
- return promotion;
456
- });
457
- }
458
- // ---------------------------------------------------------------------------
459
- // Promotion Queries
460
- // ---------------------------------------------------------------------------
461
- /**
462
- * Get the current promotion state for a checkpoint.
463
- */
464
- export function getPromotionState(stateDir, checkpointId) {
465
- const registry = readRegistry(stateDir);
466
- const promotion = registry.promotions.find((p) => p.checkpointId === checkpointId);
467
- return promotion?.state ?? null;
468
- }
469
- /**
470
- * Get the promotion record for a checkpoint.
471
- */
472
- export function getPromotionRecord(stateDir, checkpointId) {
473
- const registry = readRegistry(stateDir);
474
- return registry.promotions.find((p) => p.checkpointId === checkpointId) ?? null;
475
- }
476
- /**
477
- * List promotions by state.
478
- */
479
- export function listPromotionsByState(stateDir, state) {
480
- const registry = readRegistry(stateDir);
481
- return registry.promotions.filter((p) => p.state === state);
482
- }
483
- /**
484
- * List all promotions for a profile.
485
- */
486
- export function listPromotionsForProfile(stateDir, targetProfile) {
487
- const registry = readRegistry(stateDir);
488
- return registry.promotions.filter((p) => p.targetProfile === targetProfile);
489
- }
490
- // ---------------------------------------------------------------------------
491
- // Rollback Support
492
- // ---------------------------------------------------------------------------
493
- /**
494
- * Reject a checkpoint, preventing it from being promoted.
495
- *
496
- * @param stateDir - Workspace state directory
497
- * @param checkpointId - Checkpoint to reject
498
- * @param reason - Reason for rejection
499
- * @returns The updated PromotionRecord
500
- */
501
- export function rejectCheckpoint(stateDir, checkpointId, reason) {
502
- return withPromotionRegistryLock(stateDir, (registry) => {
503
- const now = new Date().toISOString();
504
- const existingIdx = registry.promotions.findIndex((p) => p.checkpointId === checkpointId);
505
- const checkpoint = getCheckpoint(stateDir, checkpointId);
506
- const promotion = {
507
- promotionId: existingIdx >= 0
508
- ? registry.promotions[existingIdx].promotionId
509
- : crypto.randomUUID(),
510
- checkpointId,
511
- state: 'rejected',
512
- targetProfile: 'local-reader', // Default, should be overridden
513
- targetModelFamily: checkpoint?.targetModelFamily ?? 'unknown',
514
- reducedPromptDelta: 0,
515
- constraintMetrics: {
516
- arbiterRejectRate: 1,
517
- executabilityRejectRate: 1,
518
- reviewedSubsetQuality: 0,
519
- routingScopeNotExpanded: true,
520
- },
521
- baselineMetrics: {
522
- arbiterRejectRate: 0,
523
- executabilityRejectRate: 0,
524
- reviewedSubsetQuality: 0,
525
- },
526
- orchestratorReviewPassed: false,
527
- reviewNote: reason,
528
- stateChangedAt: now,
529
- createdAt: existingIdx >= 0
530
- ? registry.promotions[existingIdx].createdAt
531
- : now,
532
- };
533
- if (existingIdx >= 0) {
534
- registry.promotions[existingIdx] = promotion;
535
- }
536
- else {
537
- registry.promotions.push(promotion);
538
- }
539
- writeRegistry(stateDir, registry);
540
- return promotion;
541
- });
542
- }
543
- // ---------------------------------------------------------------------------
544
- // Default Baseline Metrics
545
- // ---------------------------------------------------------------------------
546
- /**
547
- * Default baseline metrics for Phase 7.
548
- * These represent the "acceptable" thresholds that new checkpoints must meet.
549
- */
550
- export const DEFAULT_BASELINE_METRICS = {
551
- arbiterRejectRate: 0.15, // 15% max arbiter rejection
552
- executabilityRejectRate: 0.10, // 10% max executability rejection
553
- reviewedSubsetQuality: 0.70, // 70% minimum quality score
554
- };