create-principles-disciple 1.89.0 → 1.91.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 (53) 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 +2 -2
  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/core/package.json +1 -1
  37. package/package.json +2 -2
  38. package/pd-cli/package.json +1 -1
  39. package/plugin/dist/hooks/prompt.js +4 -5
  40. package/plugin/dist/index.js +0 -83
  41. package/plugin/package.json +2 -2
  42. package/plugin/dist/core/local-worker-routing.d.ts +0 -124
  43. package/plugin/dist/core/local-worker-routing.js +0 -216
  44. package/plugin/dist/core/model-deployment-registry.d.ts +0 -218
  45. package/plugin/dist/core/model-deployment-registry.js +0 -502
  46. package/plugin/dist/core/model-training-registry.d.ts +0 -295
  47. package/plugin/dist/core/model-training-registry.js +0 -474
  48. package/plugin/dist/core/promotion-gate.d.ts +0 -243
  49. package/plugin/dist/core/promotion-gate.js +0 -554
  50. package/plugin/dist/core/shadow-observation-registry.d.ts +0 -217
  51. package/plugin/dist/core/shadow-observation-registry.js +0 -280
  52. package/plugin/dist/utils/shadow-fingerprint.d.ts +0 -16
  53. package/plugin/dist/utils/shadow-fingerprint.js +0 -34
@@ -1,502 +0,0 @@
1
- /**
2
- * Model Deployment Registry — Worker Profile → Checkpoint Binding & Routing Control
3
- * ===============================================================================
4
- *
5
- * PURPOSE: Establish auditable, reversible bindings between worker profiles and
6
- * trained model checkpoints so that routing decisions are code-governed and
7
- * rollback-safe.
8
- *
9
- * ARCHITECTURE:
10
- * - Registry file: {stateDir}/.state/nocturnal/deployment-registry.json
11
- * - File locking on all write operations
12
- * - Immutable deployment records — rollback uses previousCheckpointId
13
- * - Tight integration with model-training-registry for checkpoint validation
14
- *
15
- * PROFILE CONSTRAINTS (Phase 5 only):
16
- * - local-reader → must bind a checkpoint whose targetModelFamily is a "reader" family
17
- * - local-editor → must bind a checkpoint whose targetModelFamily is an "editor" family
18
- * - No other profiles are accepted
19
- *
20
- * BINDING RULES:
21
- * - Only a deployable checkpoint can be bound
22
- * - The checkpoint's targetModelFamily must satisfy the profile's family constraint
23
- * - binding sets routingEnabled = false; enableRoutingForProfile() must be called explicitly
24
- * - rollbackDeployment() returns to previousCheckpointId (if any)
25
- *
26
- * DESIGN CONSTRAINTS:
27
- * - No actual task routing execution (Phase 5 only)
28
- * - No automatic promotion or failover
29
- * - Registry is append-only for deployments; rollback creates a new binding
30
- */
31
- import * as fs from 'fs';
32
- import * as path from 'path';
33
- import * as crypto from 'crypto';
34
- import { withLock } from '../utils/file-lock.js';
35
- import { atomicWriteFileSync } from '../utils/io.js';
36
- import { getCheckpoint, isCheckpointDeployable, } from './model-training-registry.js';
37
- import { getPromotionState } from './promotion-gate.js';
38
- // ---------------------------------------------------------------------------
39
- // Constants
40
- // ---------------------------------------------------------------------------
41
- const REGISTRY_FILE = '.state/nocturnal/deployment-registry.json';
42
- /**
43
- * The set of valid Phase 5 worker profile names.
44
- */
45
- export const SUPPORTED_PROFILES = ['local-reader', 'local-editor'];
46
- // ---------------------------------------------------------------------------
47
- // Profile–Family Constraint System
48
- // ---------------------------------------------------------------------------
49
- /**
50
- * Known model family name prefixes/suffixes recognized as "reader" families.
51
- * Any targetModelFamily string containing one of these tokens is considered a reader family.
52
- *
53
- * This is a first-iteration heuristic. Real systems may use explicit tag registries.
54
- */
55
- const READER_FAMILY_KEYWORDS = ['reader', 'read', 'claude-haiku', 'qwen-lite', 'phi-mini'];
56
- /**
57
- * Known model family name prefixes/suffixes recognized as "editor" families.
58
- * Any targetModelFamily string containing one of these tokens is considered an editor family.
59
- */
60
- const EDITOR_FAMILY_KEYWORDS = ['editor', 'edit', 'code', 'claude-sonnet', 'gpt-4o-mini'];
61
- /**
62
- * Determine whether a target model family name qualifies as a "reader" family.
63
- * Returns true if any known reader keyword appears in the family name (case-insensitive).
64
- */
65
- function isReaderFamily(targetModelFamily) {
66
- const lower = targetModelFamily.toLowerCase();
67
- return READER_FAMILY_KEYWORDS.some((kw) => lower.includes(kw));
68
- }
69
- /**
70
- * Determine whether a target model family name qualifies as an "editor" family.
71
- * Returns true if any known editor keyword appears in the family name (case-insensitive).
72
- */
73
- function isEditorFamily(targetModelFamily) {
74
- const lower = targetModelFamily.toLowerCase();
75
- return EDITOR_FAMILY_KEYWORDS.some((kw) => lower.includes(kw));
76
- }
77
- /**
78
- * Validate that a given targetModelFamily satisfies a worker's family constraint.
79
- *
80
- * @param profile - The worker profile requesting the binding
81
- * @param targetModelFamily - The checkpoint's target model family
82
- * @throws Error if the family is incompatible with the profile
83
- */
84
- function validateProfileFamilyConstraint(profile, targetModelFamily) {
85
- if (profile === 'local-reader') {
86
- if (!isReaderFamily(targetModelFamily)) {
87
- throw new Error(`Family constraint violated: profile "${profile}" requires a reader-family checkpoint ` +
88
- `but checkpoint targets "${targetModelFamily}". ` +
89
- `Reader families must contain one of: ${READER_FAMILY_KEYWORDS.join(', ')}. ` +
90
- `If you are deploying a new model family, update the READER_FAMILY_KEYWORDS or ` +
91
- `EDITOR_FAMILY_KEYWORDS constants in model-deployment-registry.ts.`);
92
- }
93
- }
94
- else if (profile === 'local-editor') {
95
- if (!isEditorFamily(targetModelFamily)) {
96
- throw new Error(`Family constraint violated: profile "${profile}" requires an editor-family checkpoint ` +
97
- `but checkpoint targets "${targetModelFamily}". ` +
98
- `Editor families must contain one of: ${EDITOR_FAMILY_KEYWORDS.join(', ')}. ` +
99
- `If you are deploying a new model family, update the EDITOR_FAMILY_KEYWORDS constant ` +
100
- `in model-deployment-registry.ts.`);
101
- }
102
- }
103
- }
104
- // ---------------------------------------------------------------------------
105
- // Registry Path
106
- // ---------------------------------------------------------------------------
107
- function getRegistryPath(stateDir) {
108
- return path.join(stateDir, REGISTRY_FILE);
109
- }
110
- /**
111
- * Ensure the registry directory exists.
112
- */
113
- function ensureRegistryDir(stateDir) {
114
- const registryPath = getRegistryPath(stateDir);
115
- const dir = path.dirname(registryPath);
116
- if (!fs.existsSync(dir)) {
117
- fs.mkdirSync(dir, { recursive: true });
118
- }
119
- }
120
- // ---------------------------------------------------------------------------
121
- // File Operations
122
- // ---------------------------------------------------------------------------
123
- /**
124
- * Read the registry from disk. Returns empty registry if missing.
125
- * Throws if the file exists but contains invalid JSON — fail-closed
126
- * to prevent silent data loss when a corrupt registry would otherwise
127
- * be overwritten on the next write.
128
- */
129
- function readRegistry(stateDir) {
130
- const registryPath = getRegistryPath(stateDir);
131
- if (!fs.existsSync(registryPath)) {
132
- return { deployments: [] };
133
- }
134
- try {
135
- const content = fs.readFileSync(registryPath, 'utf-8');
136
- const registry = JSON.parse(content);
137
- // Validate required structure — fail closed on malformed registry
138
- if (!Array.isArray(registry.deployments)) {
139
- throw new Error(`Corrupt deployment registry at "${registryPath}": missing or invalid "deployments" field`);
140
- }
141
- return registry;
142
- }
143
- catch (err) {
144
- if (err instanceof SyntaxError || err instanceof Error) {
145
- throw new Error(`Failed to read deployment registry from "${registryPath}": ${err.message}`, { cause: err });
146
- }
147
- throw err;
148
- }
149
- }
150
- /**
151
- * Write the registry to disk atomically.
152
- * Caller must hold the registry lock.
153
- */
154
- function writeRegistry(stateDir, registry) {
155
- ensureRegistryDir(stateDir);
156
- const registryPath = getRegistryPath(stateDir);
157
- atomicWriteFileSync(registryPath, JSON.stringify(registry, null, 2));
158
- }
159
- /**
160
- * Execute a read-modify-write under an exclusive file lock.
161
- */
162
- function withDeploymentRegistryLock(stateDir, fn) {
163
- const registryPath = getRegistryPath(stateDir);
164
- return withLock(registryPath, () => {
165
- const registry = readRegistry(stateDir);
166
- return fn(registry);
167
- });
168
- }
169
- // ---------------------------------------------------------------------------
170
- // Profile Validation
171
- // ---------------------------------------------------------------------------
172
- /**
173
- * Validate that a worker profile name is supported in Phase 5.
174
- *
175
- * @throws Error if the profile is not in SUPPORTED_PROFILES
176
- */
177
- export function assertSupportedProfile(profile) {
178
- if (!SUPPORTED_PROFILES.includes(profile)) {
179
- throw new Error(`Unsupported worker profile: "${profile}". ` +
180
- `Phase 5 only supports: ${SUPPORTED_PROFILES.join(', ')}. ` +
181
- `Do not add new profiles in Phase 5.`);
182
- }
183
- }
184
- // ---------------------------------------------------------------------------
185
- // Promotion Gate Integration (Phase 7)
186
- // ---------------------------------------------------------------------------
187
- /**
188
- * Check if a checkpoint has passed the promotion gate and can be deployed.
189
- *
190
- * This function checks:
191
- * 1. The checkpoint has an eval summary attached (lineage complete)
192
- * 2. The promotion state is 'shadow_ready' or 'promotable' (gate passed)
193
- *
194
- * @param stateDir - Workspace state directory
195
- * @param checkpointId - Checkpoint to verify
196
- * @returns true if the checkpoint can be deployed, false otherwise
197
- */
198
- export function hasPassedPromotionGate(stateDir, checkpointId) {
199
- const checkpoint = getCheckpoint(stateDir, checkpointId);
200
- if (!checkpoint)
201
- return false;
202
- // Must have eval summary attached
203
- if (!checkpoint.lastEvalSummaryRef)
204
- return false;
205
- // Check promotion state
206
- const state = getPromotionState(stateDir, checkpointId);
207
- return state === 'shadow_ready' || state === 'promotable';
208
- }
209
- /**
210
- * Assert that a checkpoint has passed the promotion gate.
211
- * Throws if the checkpoint cannot be deployed.
212
- *
213
- * @param stateDir - Workspace state directory
214
- * @param checkpointId - Checkpoint to verify
215
- * @throws Error if the checkpoint has not passed the promotion gate
216
- */
217
- export function assertPromotionGatePassed(stateDir, checkpointId) {
218
- if (!hasPassedPromotionGate(stateDir, checkpointId)) {
219
- throw new Error(`Checkpoint "${checkpointId}" has not passed the promotion gate. ` +
220
- `A checkpoint must pass the promotion gate (state: shadow_ready or promotable) ` +
221
- `before it can be bound to a worker profile. ` +
222
- `Ensure the promotion gate has been evaluated and approved.`);
223
- }
224
- }
225
- // ---------------------------------------------------------------------------
226
- // Core Operations
227
- // ---------------------------------------------------------------------------
228
- /**
229
- * Bind a checkpoint to a worker profile, creating or updating the deployment record.
230
- *
231
- * BINDING RULE (fail-closed):
232
- * Only a checkpoint that is marked deployable in the training registry may be bound.
233
- *
234
- * PROFILE-FAMILY CONSTRAINT:
235
- * The checkpoint's targetModelFamily must satisfy the profile's family keyword constraint.
236
- * See: validateProfileFamilyConstraint()
237
- *
238
- * @param stateDir - Workspace state directory
239
- * @param workerProfile - Target worker profile (local-reader | local-editor)
240
- * @param checkpointId - Checkpoint to bind (must be deployable)
241
- * @param note - Optional human-readable note
242
- * @returns The new or updated Deployment record
243
- *
244
- * @throws Error if checkpoint is not found or not deployable
245
- * @throws Error if checkpoint's targetModelFamily violates profile constraints
246
- */
247
- export function bindCheckpointToWorkerProfile(stateDir, workerProfile, checkpointId, note) {
248
- assertSupportedProfile(workerProfile);
249
- return withDeploymentRegistryLock(stateDir, (registry) => {
250
- const now = new Date().toISOString();
251
- // --- Validate checkpoint exists and is deployable ---
252
- const checkpoint = getCheckpoint(stateDir, checkpointId);
253
- if (!checkpoint) {
254
- throw new Error(`bindCheckpointToWorkerProfile failed: checkpoint "${checkpointId}" not found ` +
255
- `in training registry. Ensure the checkpoint has been registered via ` +
256
- `registerCheckpoint() in model-training-registry.ts first.`);
257
- }
258
- if (!isCheckpointDeployable(stateDir, checkpointId)) {
259
- throw new Error(`bindCheckpointToWorkerProfile failed: checkpoint "${checkpointId}" is not deployable. ` +
260
- `Only checkpoints that have passed evaluation may be bound to a worker profile. ` +
261
- `Use markCheckpointDeployable() in model-training-registry.ts after a successful eval.`);
262
- }
263
- // --- Phase 7: Validate promotion gate has passed ---
264
- assertPromotionGatePassed(stateDir, checkpointId);
265
- // --- Validate profile-family constraint ---
266
- validateProfileFamilyConstraint(workerProfile, checkpoint.targetModelFamily);
267
- // --- Find existing deployment for this profile (if any) ---
268
- const existingIdx = registry.deployments.findIndex((d) => d.workerProfile === workerProfile);
269
- const deploymentId = existingIdx >= 0
270
- ? registry.deployments[existingIdx].deploymentId
271
- : crypto.randomUUID();
272
- const previousCheckpointId = existingIdx >= 0
273
- ? registry.deployments[existingIdx].activeCheckpointId ?? null
274
- : null;
275
- const newDeployment = {
276
- deploymentId,
277
- workerProfile,
278
- targetModelFamily: checkpoint.targetModelFamily,
279
- activeCheckpointId: checkpointId,
280
- // When re-binding (updating checkpoint), the old active becomes previous
281
- previousCheckpointId,
282
- // routingEnabled starts false — must be explicitly enabled
283
- routingEnabled: false,
284
- deployedAt: existingIdx >= 0
285
- ? registry.deployments[existingIdx].deployedAt
286
- : now,
287
- updatedAt: now,
288
- note: note ?? (existingIdx >= 0 ? registry.deployments[existingIdx].note : undefined),
289
- };
290
- if (existingIdx >= 0) {
291
- registry.deployments[existingIdx] = newDeployment;
292
- }
293
- else {
294
- registry.deployments.push(newDeployment);
295
- }
296
- writeRegistry(stateDir, registry);
297
- return newDeployment;
298
- });
299
- }
300
- /**
301
- * Retrieve the deployment record for a worker profile.
302
- *
303
- * @returns Deployment if found, null otherwise
304
- */
305
- export function getDeployment(stateDir, workerProfile) {
306
- assertSupportedProfile(workerProfile);
307
- const registry = readRegistry(stateDir);
308
- return registry.deployments.find((d) => d.workerProfile === workerProfile) ?? null;
309
- }
310
- /**
311
- * List all deployments, optionally filtered.
312
- *
313
- * @param stateDir - Workspace state directory
314
- * @param filter - Optional filter criteria
315
- */
316
- export function listDeployments(stateDir, filter) {
317
- const registry = readRegistry(stateDir);
318
- let { deployments } = registry;
319
- if (filter?.workerProfile) {
320
- deployments = deployments.filter((d) => d.workerProfile === filter.workerProfile);
321
- }
322
- if (filter?.routingEnabled !== undefined) {
323
- deployments = deployments.filter((d) => d.routingEnabled === filter.routingEnabled);
324
- }
325
- return deployments.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
326
- }
327
- /**
328
- * Enable routing for a worker profile.
329
- *
330
- * PRECONDITIONS (fail-closed):
331
- * 1. A deployment record must exist for this profile
332
- * 2. activeCheckpointId must not be null
333
- *
334
- * @throws Error if no deployment exists
335
- * @throws Error if activeCheckpointId is null (nothing to route to)
336
- */
337
- export function enableRoutingForProfile(stateDir, workerProfile) {
338
- assertSupportedProfile(workerProfile);
339
- return withDeploymentRegistryLock(stateDir, (registry) => {
340
- const idx = registry.deployments.findIndex((d) => d.workerProfile === workerProfile);
341
- if (idx === -1) {
342
- throw new Error(`enableRoutingForProfile failed: no deployment found for profile "${workerProfile}". ` +
343
- `Bind a checkpoint first using bindCheckpointToWorkerProfile().`);
344
- }
345
- const deployment = registry.deployments[idx];
346
- if (!deployment.activeCheckpointId) {
347
- throw new Error(`enableRoutingForProfile failed: deployment for "${workerProfile}" has no ` +
348
- `active checkpoint (activeCheckpointId is null). ` +
349
- `Bind a checkpoint before enabling routing.`);
350
- }
351
- // Double-check the active checkpoint is still deployable
352
- if (!isCheckpointDeployable(stateDir, deployment.activeCheckpointId)) {
353
- throw new Error(`enableRoutingForProfile failed: active checkpoint "${deployment.activeCheckpointId}" ` +
354
- `for profile "${workerProfile}" is no longer marked deployable. ` +
355
- `Revoke deployment or bind a new checkpoint before enabling routing.`);
356
- }
357
- registry.deployments[idx] = {
358
- ...deployment,
359
- routingEnabled: true,
360
- updatedAt: new Date().toISOString(),
361
- };
362
- writeRegistry(stateDir, registry);
363
- return registry.deployments[idx];
364
- });
365
- }
366
- /**
367
- * Disable routing for a worker profile.
368
- * This is always safe — it does not unbind the checkpoint.
369
- *
370
- * @throws Error if no deployment exists for the profile
371
- */
372
- export function disableRoutingForProfile(stateDir, workerProfile) {
373
- assertSupportedProfile(workerProfile);
374
- return withDeploymentRegistryLock(stateDir, (registry) => {
375
- const idx = registry.deployments.findIndex((d) => d.workerProfile === workerProfile);
376
- if (idx === -1) {
377
- throw new Error(`disableRoutingForProfile failed: no deployment found for profile "${workerProfile}".`);
378
- }
379
- registry.deployments[idx] = {
380
- ...registry.deployments[idx],
381
- routingEnabled: false,
382
- updatedAt: new Date().toISOString(),
383
- };
384
- writeRegistry(stateDir, registry);
385
- return registry.deployments[idx];
386
- });
387
- }
388
- /**
389
- * Roll back the deployment for a worker profile to its previous checkpoint.
390
- *
391
- * ROLLBACK RULE:
392
- * - Can only roll back if previousCheckpointId is not null
393
- * - Sets activeCheckpointId = previousCheckpointId
394
- * - The old activeCheckpointId becomes the new previousCheckpointId
395
- * - routingEnabled is set to false (must be re-enabled explicitly)
396
- *
397
- * @throws Error if no deployment exists
398
- * @throws Error if no previous checkpoint is available
399
- */
400
- export function rollbackDeployment(stateDir, workerProfile, note) {
401
- assertSupportedProfile(workerProfile);
402
- return withDeploymentRegistryLock(stateDir, (registry) => {
403
- const idx = registry.deployments.findIndex((d) => d.workerProfile === workerProfile);
404
- if (idx === -1) {
405
- throw new Error(`rollbackDeployment failed: no deployment found for profile "${workerProfile}".`);
406
- }
407
- const deployment = registry.deployments[idx];
408
- if (!deployment.previousCheckpointId) {
409
- throw new Error(`rollbackDeployment failed: no previous checkpoint available for profile ` +
410
- `"${workerProfile}". The current deployment has no rollback target. ` +
411
- `(activeCheckpointId="${deployment.activeCheckpointId}", ` +
412
- `previousCheckpointId=null)`);
413
- }
414
- // Verify the rollback target checkpoint still exists and is deployable
415
- const rollbackTarget = getCheckpoint(stateDir, deployment.previousCheckpointId);
416
- if (!rollbackTarget) {
417
- throw new Error(`rollbackDeployment failed: previous checkpoint "${deployment.previousCheckpointId}" ` +
418
- `no longer exists in the training registry. Cannot roll back to a deleted checkpoint.`);
419
- }
420
- if (!isCheckpointDeployable(stateDir, deployment.previousCheckpointId)) {
421
- throw new Error(`rollbackDeployment failed: previous checkpoint "${deployment.previousCheckpointId}" ` +
422
- `is no longer deployable. Roll back to a passing checkpoint or re-bind a new one.`);
423
- }
424
- const now = new Date().toISOString();
425
- // Chain the rollback: the old active becomes the new previous
426
- const newPreviousCheckpointId = deployment.activeCheckpointId;
427
- const rolledBack = {
428
- ...deployment,
429
- activeCheckpointId: deployment.previousCheckpointId,
430
- previousCheckpointId: newPreviousCheckpointId,
431
- routingEnabled: false, // Always disable routing after rollback — must re-enable
432
- updatedAt: now,
433
- note: note ?? `Rollback to ${deployment.previousCheckpointId}`,
434
- };
435
- registry.deployments[idx] = rolledBack;
436
- writeRegistry(stateDir, registry);
437
- return rolledBack;
438
- });
439
- }
440
- // ---------------------------------------------------------------------------
441
- // Read-Only Query Helpers
442
- // ---------------------------------------------------------------------------
443
- /**
444
- * Check whether a worker profile currently has an enabled deployment
445
- * with an active checkpoint that is still deployable.
446
- *
447
- * GOVERNANCE: Even if routing was previously enabled, a checkpoint that
448
- * has been revoked (marked non-deployable via markCheckpointDeployable(false))
449
- * must not be used for routing. This prevents routing traffic to a
450
- * checkpoint that has been superseded or failed re-evaluation.
451
- */
452
- export function isRoutingEnabledForProfile(stateDir, workerProfile) {
453
- const deployment = getDeployment(stateDir, workerProfile);
454
- if (!deployment?.routingEnabled)
455
- return false;
456
- if (!deployment.activeCheckpointId)
457
- return false;
458
- // Re-check deployability on every routing decision — checkpoint may have been revoked
459
- return isCheckpointDeployable(stateDir, deployment.activeCheckpointId);
460
- }
461
- /**
462
- * Get the active checkpoint ID for a worker profile.
463
- * Returns null if no deployment or no active checkpoint.
464
- */
465
- export function getActiveCheckpointForProfile(stateDir, workerProfile) {
466
- const deployment = getDeployment(stateDir, workerProfile);
467
- return deployment?.activeCheckpointId ?? null;
468
- }
469
- /**
470
- * Get the full deployment record with lineage context.
471
- * Returns null if no deployment exists.
472
- *
473
- * Lineage includes: deployment record, active checkpoint, parent training run, eval summary.
474
- */
475
- export function getDeploymentLineage(stateDir, workerProfile) {
476
- const deployment = getDeployment(stateDir, workerProfile);
477
- if (!deployment)
478
- return null;
479
- const activeCheckpoint = deployment.activeCheckpointId
480
- ? getCheckpoint(stateDir, deployment.activeCheckpointId)
481
- : null;
482
- return { deployment, activeCheckpoint };
483
- }
484
- /**
485
- * Get the complete deployment registry (for debugging/admin purposes).
486
- */
487
- export function getFullDeploymentRegistry(stateDir) {
488
- return readRegistry(stateDir);
489
- }
490
- /**
491
- * Compute stats for the deployment registry.
492
- */
493
- export function getDeploymentRegistryStats(stateDir) {
494
- const registry = readRegistry(stateDir);
495
- const { deployments } = registry;
496
- return {
497
- totalDeployments: deployments.length,
498
- activeDeployments: deployments.filter((d) => d.routingEnabled).length,
499
- profilesWithBindings: new Set(deployments.map((d) => d.workerProfile)).size,
500
- profilesWithRoutingEnabled: deployments.filter((d) => d.routingEnabled).length,
501
- };
502
- }