@ngockhoale/ukit 3.5.2 → 3.5.4

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 (75) hide show
  1. package/CHANGELOG.md +38 -90
  2. package/README.md +1 -0
  3. package/manifests/documentation.yaml +12 -1
  4. package/manifests/platform.full.yaml +12 -0
  5. package/package.json +34 -1
  6. package/src/cli/commands/doctor.js +55 -2
  7. package/src/cli/commands/indexTools.js +10 -4
  8. package/src/cli/commands/memory.js +107 -8
  9. package/src/core/memory/episodes.js +106 -7
  10. package/src/core/memory/memoryCheck.js +241 -0
  11. package/src/core/memory/memoryCheckRun.js +27 -0
  12. package/src/core/memory/memoryHit.js +2 -0
  13. package/src/core/memory/mutateMemory.js +46 -1
  14. package/src/core/memory/observations.js +192 -0
  15. package/src/core/memory/projectIdentity.js +9 -2
  16. package/src/core/memory/recallEngine.js +204 -9
  17. package/src/core/memory/records.js +23 -0
  18. package/src/core/memory/registryPrune.js +230 -0
  19. package/src/core/memory/retrieval.js +12 -3
  20. package/src/core/memory/writeGate.js +137 -0
  21. package/src/core/runtimeConfig.js +12 -2
  22. package/src/index/buildIndex.js +26 -0
  23. package/src/index/paths.js +3 -1
  24. package/src/index/queryIndex.js +372 -26
  25. package/src/index/resolveContext.js +1 -1
  26. package/template_project/.claude/hooks/edit-hint.mjs +64 -17
  27. package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
  28. package/template_project/.claude/hooks/session-episode.sh +9 -4
  29. package/template_project/.claude/settings.json +2 -2
  30. package/template_project/.claude/ukit/index/edit-graph.mjs +141 -11
  31. package/template_project/.claude/ukit/index/lib/index-core.mjs +400 -27
  32. package/template_project/.claude/ukit/index/query-index.mjs +14 -3
  33. package/template_project/.claude/ukit/index/resolve-context.mjs +1 -1
  34. package/template_project/.claude/ukit/index/route-task.mjs +8 -2
  35. package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
  36. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +44 -22
  37. package/template_project/.claude/ukit/runtime/memory-recall.mjs +204 -9
  38. package/template_project/.claude/ukit/runtime/memory-validity.mjs +259 -0
  39. package/template_project/.claude/ukit/runtime/reinject-context.mjs +4 -2
  40. package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
  41. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  42. package/template_project/ukit/storage/config.json +4 -2
  43. package/src/core/agentRuntime/completionGate.js +0 -179
  44. package/src/core/agentRuntime/context.js +0 -571
  45. package/src/core/agentRuntime/qualityComparison.js +0 -112
  46. package/src/core/agentRuntime/resourcePolicy.js +0 -78
  47. package/src/core/agentRuntime/runtimeSupport.js +0 -255
  48. package/src/core/codeintel/manifest.js +0 -176
  49. package/src/core/experiments/deliberation.js +0 -327
  50. package/src/core/experiments/dynamicWorkflow.js +0 -507
  51. package/src/core/handoffDocValidator.js +0 -154
  52. package/src/core/memory/deltaOverlays.js +0 -493
  53. package/src/core/memory/learningCandidates.js +0 -347
  54. package/src/core/observability/emit/sessionBoot.js +0 -407
  55. package/src/core/observability/evaluation/experimentPlan.js +0 -95
  56. package/src/core/observability/evaluation/perturbation.js +0 -273
  57. package/src/core/observability/evaluation/replay.js +0 -149
  58. package/src/core/observability/evaluation/scorecard.js +0 -465
  59. package/src/core/observability/schema/compatibility.js +0 -180
  60. package/src/core/observability/support/renderer.js +0 -130
  61. package/src/core/reviewPanelAggregate.js +0 -204
  62. package/src/core/taskBudgetValidator.js +0 -251
  63. package/src/core/taskProgressGuard.js +0 -227
  64. package/src/decision/reviewVerdict.js +0 -339
  65. package/src/decision/runtimeFilter.js +0 -150
  66. package/src/decision/runtimeScheduler.js +0 -239
  67. package/src/diagnostics/classifyHang.js +0 -246
  68. package/src/diagnostics/ompStallSnapshot.js +0 -199
  69. package/src/index/contextPack.js +0 -285
  70. package/src/index/impactContext.js +0 -360
  71. package/src/index/reviewPolicy.js +0 -368
  72. package/src/index/sensitivePath.js +0 -21
  73. package/src/render/instructionRenderer.js +0 -290
  74. package/src/skill/auditSkill.js +0 -140
  75. package/template_project/instructions/overlays/repo.md +0 -9
@@ -1,407 +0,0 @@
1
- /**
2
- * sessionBoot.js (TASK-003, SPEC §5 FR-003, §6, §14) — the live session-boot
3
- * emit surface: the production caller the recorder layer never had.
4
- *
5
- * emitSessionBoot({ projectRoot, engine, sessionId, config?, deps? })
6
- * → { status: 'written', written, elapsed_ms }
7
- * | { status: 'dropped'|'partial'|'error', reason }
8
- * emitOutcomeObserved({ projectRoot, record, config?, deps? }) → same result
9
- * resolveEmitStage(config) → 'off' | 'shadow' | 'canary' | 'default'
10
- * loadEmitConfig(projectRoot) → merged emit config (async, never throws)
11
- *
12
- * A hook child process lives for milliseconds — `startLifecycle`'s interval
13
- * timers and beforeExit flush cannot survive it (SPEC §14 chose the bounded
14
- * one-shot emit). One call = one recorder = one record = one flush, each
15
- * step racing a deadline, so the emit can never delay session start: it is
16
- * fire-and-forget, bounded, and never throws.
17
- *
18
- * Stage contract: this surface emits by default — the shipped
19
- * `.ukit/storage/config.json` sets observability.stage='default' and the
20
- * runtime default config agrees — so 'off' is an explicit kill switch the
21
- * owner sets; a missing config file or missing stage emits (the same
22
- * "default" the rest of the runtime resolves to). A caller-supplied
23
- * `config` object is used as the complete merged config, so callers that
24
- * want the live stage pass the runtime config themselves; absent config
25
- * resolves the 'default' effective stage.
26
- *
27
- * The parity-locked mirror
28
- * template_project/.claude/ukit/runtime/observability-emit.mjs cannot
29
- * import package source — it replicates this pipeline (envelope fill →
30
- * validate → sanitize → bounded append) with identical semantics. Keep the
31
- * record shape changes coordinated with `tests/consistency/
32
- * sessionBootEmitParity.test.js`.
33
- */
34
-
35
- import crypto from 'node:crypto';
36
- import fs from 'node:fs';
37
- import path from 'node:path';
38
-
39
- import { createRecorder } from './recorder.js';
40
- import {
41
- buildSessionBootRecord,
42
- segmentsRoot,
43
- sessionBootRequestKey,
44
- SEMANTIC_OUTCOME_OBSERVED,
45
- } from './lifecycle.js';
46
- import { resolveStage } from './config.js';
47
-
48
- /** Hard upper bound for the whole one-shot emit (ms). */
49
- export const SESSION_BOOT_EMIT_DEADLINE_MS = 250;
50
-
51
- const VALID_STAGES = new Set(['off', 'shadow', 'canary', 'default']);
52
-
53
- function isPlainObject(value) {
54
- return value !== null && typeof value === 'object' && !Array.isArray(value);
55
- }
56
-
57
- function isNonEmptyString(value) {
58
- return typeof value === 'string' && value.length > 0;
59
- }
60
-
61
- /**
62
- * The emit surface's effective stage: the explicit literal 'off' is the
63
- * kill switch; any other explicit stage value resolves through
64
- * resolveStage verbatim; absent/malformed resolves 'default' (the shipped
65
- * + code default), never the recorder's fail-safe 'off'.
66
- */
67
- export function resolveEmitStage(config = null) {
68
- const node = isPlainObject(config) ? config.observability : undefined;
69
- if (isPlainObject(node) && node.stage === 'off') return 'off';
70
- const stage = resolveStage(config);
71
- return stage === 'off' ? 'default' : stage;
72
- }
73
-
74
- /**
75
- * `.ukit/storage/config.json` on disk → emit config. A missing/corrupt
76
- * file means a pre-install or bare project: effective stage 'default'
77
- * (the shipped value), mirroring the runtime's own code default.
78
- */
79
- export async function loadEmitConfig(projectRoot) {
80
- if (!isNonEmptyString(projectRoot)) return null;
81
- try {
82
- const raw = await fs.promises.readFile(
83
- path.join(projectRoot, '.ukit', 'storage', 'config.json'),
84
- 'utf8',
85
- );
86
- const parsed = JSON.parse(raw);
87
- return isPlainObject(parsed) ? parsed : null;
88
- } catch {
89
- return null;
90
- }
91
- }
92
-
93
- /**
94
- * Race a promise against a deadline; the loser keeps running detached
95
- * (bounded telemetry accepts a late write over blocking the caller).
96
- * Returns { value } | { timedOut: true }. The timer is unref'd so it can
97
- * never pin a dying hook process.
98
- */
99
- async function bounded(promise, deadlineMs) {
100
- if (!Number.isFinite(deadlineMs) || deadlineMs <= 0) {
101
- return { timedOut: true };
102
- }
103
- let timer;
104
- try {
105
- const result = await Promise.race([
106
- Promise.resolve(promise).then((value) => ({ value })),
107
- new Promise((resolve) => {
108
- timer = setTimeout(() => resolve({ timedOut: true }), deadlineMs);
109
- if (timer.unref) timer.unref();
110
- }),
111
- ]);
112
- return result;
113
- } finally {
114
- clearTimeout(timer);
115
- }
116
- }
117
-
118
- function toEmitResult(result, elapsed_ms) {
119
- const out = { ...result };
120
- out.elapsed_ms = Math.max(0, elapsed_ms);
121
- return out;
122
- }
123
-
124
- /**
125
- * The shared one-shot emit pipeline. `record` is a semantic-record
126
- * candidate; the recorder fills envelope fields, validates, sanitizes,
127
- * applies the sampling decider, and flush() drains through the segment
128
- * writer — the twin never reimplements any of those stages.
129
- */
130
- async function emitOne({ projectRoot, config, record, deps, deadlineMs }) {
131
- const started = Date.now();
132
- const fail = (reason) => toEmitResult({ status: 'dropped', reason }, Date.now() - started);
133
-
134
- if (!isNonEmptyString(projectRoot)) return fail('missing-project-root');
135
- if (!isPlainObject(record)) return fail('invalid-record');
136
- if (resolveEmitStage(config) === 'off') return fail('stage-off');
137
-
138
- const injected = isPlainObject(deps) ? deps : {};
139
- const clock = {
140
- nowMs: typeof injected.nowMs === 'function' ? injected.nowMs : () => injected.nowMs ?? Date.now(),
141
- nowNs:
142
- typeof injected.nowNs === 'function'
143
- ? injected.nowNs
144
- : () => injected.nowNs ?? process.hrtime.bigint(),
145
- iso:
146
- typeof injected.iso === 'function'
147
- ? injected.iso
148
- : () => injected.iso ?? new Date().toISOString(),
149
- };
150
- const writer =
151
- typeof injected.writer === 'function' ? injected.writer : undefined;
152
- const samplingSeed = Number.isFinite(injected.samplingSeed) ? injected.samplingSeed : undefined;
153
-
154
- // resolveEmitStage owns the 'default'-absent asymmetry: the effective
155
- // stage written back here is 'off' only when the owner set the literal
156
- // 'off' (that case already returned above); an absent or malformed stage
157
- // resolves 'default' — the shipped + code default — while a supplied
158
- // 'shadow'/'canary' passes through verbatim. Other observability keys
159
- // (sampling, seams) ride along untouched for the recorder's own gates.
160
- const effectiveConfig = isPlainObject(config)
161
- ? {
162
- ...config,
163
- observability: {
164
- ...(isPlainObject(config.observability) ? config.observability : {}),
165
- stage: resolveEmitStage(config),
166
- },
167
- }
168
- : { observability: { stage: 'default' } };
169
-
170
- const budget = Number.isFinite(deadlineMs) && deadlineMs > 0
171
- ? Math.min(deadlineMs, SESSION_BOOT_EMIT_DEADLINE_MS)
172
- : SESSION_BOOT_EMIT_DEADLINE_MS;
173
-
174
- // appendRecord's resolveRoot requires the segments root's PARENT to
175
- // already exist (realpath containment), so a fresh project needs the
176
- // .ukit/storage/observability tree created here — bounded by the same
177
- // deadline so a stalled mount can never pin the hook.
178
- const targetRoot = segmentsRoot(path.resolve(projectRoot));
179
- const seeded = await bounded(
180
- fs.promises.mkdir(targetRoot, { recursive: true }).catch((err) => err),
181
- budget,
182
- );
183
- if (seeded.timedOut) {
184
- return toEmitResult({ status: 'partial', reason: 'deadline' }, Date.now() - started);
185
- }
186
- try {
187
- if (seeded.value instanceof Error) throw seeded.value;
188
- } catch {
189
- // mkdir raced with another process or failed — fall through and let
190
- // the write path report the typed io reason.
191
- }
192
- try {
193
- const recorder = createRecorder({
194
- root: segmentsRoot(path.resolve(projectRoot)),
195
- config: effectiveConfig,
196
- clock,
197
- ...(writer ? { writer } : {}),
198
- ...(samplingSeed !== undefined ? { samplingSeed } : {}),
199
- });
200
- const emitted = recorder.emit(record);
201
- if (emitted.status !== 'accepted') {
202
- return fail(emitted.reason || 'dropped');
203
- }
204
- const flushed = await bounded(recorder.flush({ deadlineMs: budget }), budget);
205
- if (flushed.timedOut) {
206
- return toEmitResult({ status: 'partial', reason: 'deadline' }, Date.now() - started);
207
- }
208
- const result = flushed.value;
209
- if (result.status === 'ok' && result.written > 0) {
210
- return toEmitResult(
211
- { status: 'written', written: result.written },
212
- Date.now() - started,
213
- );
214
- }
215
- return toEmitResult(
216
- { status: result.status === 'partial' ? 'partial' : 'dropped', reason: result.reason || 'write-failed' },
217
- Date.now() - started,
218
- );
219
- } catch {
220
- return fail('emit-error');
221
- }
222
- }
223
-
224
- /**
225
- * `emitSessionBoot({ projectRoot, engine, sessionId, config?, deps? })` —
226
- * append ONE `execution.started` record to the project's active segment.
227
- * `deps` is the test-injection seam: { nowMs?, nowNs?, iso?, writer?,
228
- * samplingSeed? } (values or zero-arg functions; the recorder's clock
229
- * contract). Never throws, never exceeds the deadline.
230
- */
231
- export async function emitSessionBoot({
232
- projectRoot,
233
- engine,
234
- sessionId,
235
- config,
236
- deps,
237
- deadlineMs,
238
- } = {}) {
239
- const injected = isPlainObject(deps) ? deps : {};
240
- const nowMs = typeof injected.nowMs === 'function' ? injected.nowMs() : injected.nowMs;
241
- const record = buildSessionBootRecord({
242
- projectRoot,
243
- engine: isNonEmptyString(engine) ? engine : 'unknown',
244
- sessionId,
245
- nowMs: Number.isFinite(nowMs) ? nowMs : Date.now(),
246
- });
247
- return emitOne({ projectRoot, config, record, deps: injected, deadlineMs });
248
- }
249
-
250
- /**
251
- * `emitOutcomeObserved({ projectRoot, record, config?, deps? })` — the
252
- * generic terminal-record seam TASK-005's emitters consume. `record` is a
253
- * full semantic-record candidate; a missing `semantic_name` defaults to
254
- * 'outcome.observed' (the seam's own event).
255
- */
256
- export async function emitOutcomeObserved({
257
- projectRoot,
258
- record,
259
- config,
260
- deps,
261
- deadlineMs,
262
- } = {}) {
263
- const candidate = isPlainObject(record) ? { ...record } : record;
264
- if (isPlainObject(candidate) && candidate.semantic_name === undefined) {
265
- candidate.semantic_name = SEMANTIC_OUTCOME_OBSERVED;
266
- }
267
- return emitOne({
268
- projectRoot,
269
- config,
270
- record: candidate,
271
- deps: isPlainObject(deps) ? deps : {},
272
- deadlineMs,
273
- });
274
- }
275
-
276
-
277
- // --- TASK-005 (FR-005, BL-007): terminal OutcomeRecord construction ---------
278
- // The three terminal emitters (record-execution.mjs receipts,
279
- // stop-coordinator.mjs verdicts, execution-ledger.mjs finalizers) share ONE
280
- // record builder so every `outcome.observed` record carries the ARCH
281
- // §Data Contracts OutcomeRecord fields plus the TASK-003 session-boot
282
- // `request_key` join id — the missing 1-of-3934 emitter surface (TM §2).
283
-
284
- export const OUTCOME_VERDICTS = Object.freeze([
285
- 'VERIFIED', 'FAILED', 'BLOCKED', 'INCONCLUSIVE', 'INTERRUPTED',
286
- ]);
287
-
288
- const OUTCOME_ENFORCEMENTS = new Set(['enforced', 'advisory']);
289
-
290
- // FR-005/FR-006: `advisory` is the Codex marker — the engine stamp may arrive
291
- // as an explicit `engine` argument or as `env.UKIT_HARNESS` (the stamp the
292
- // .sh wrappers and the omp bridge export). Anything else is `enforced`.
293
- export function deriveEnforcement({ engine = null, env = null } = {}) {
294
- const fromArg = isNonEmptyString(engine) ? engine : null;
295
- const fromEnv = isPlainObject(env) && isNonEmptyString(env.UKIT_HARNESS) ? env.UKIT_HARNESS : null;
296
- return (fromArg === 'codex' || fromEnv === 'codex') ? 'advisory' : 'enforced';
297
- }
298
-
299
- // The run id is the ledger's session identity: `run-<safe session id>` when a
300
- // session is known, `run-transcript-<sha256[:12]>` for transcript-only
301
- // payloads (never the raw path — it would be path-redacted anyway), else null.
302
- export function outcomeRunId(payload = {}) {
303
- const sessionId = isNonEmptyString(payload.session_id)
304
- ? payload.session_id
305
- : (isNonEmptyString(payload.sessionId) ? payload.sessionId : null);
306
- if (sessionId) {
307
- const safe = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96);
308
- return `run-${safe}`;
309
- }
310
- const transcript = isNonEmptyString(payload.transcript_path)
311
- ? payload.transcript_path
312
- : (isNonEmptyString(payload.transcriptPath) ? payload.transcriptPath : null);
313
- if (transcript) {
314
- const digest = crypto.createHash('sha256').update(String(transcript)).digest('hex').slice(0, 12);
315
- return `run-transcript-${digest}`;
316
- }
317
- return null;
318
- }
319
-
320
- function outcomeStringList(value, cap) {
321
- if (!Array.isArray(value)) return [];
322
- return value
323
- .filter((item) => typeof item === 'string' && item.length > 0)
324
- .map((item) => item.slice(0, 160))
325
- .slice(0, cap);
326
- }
327
-
328
- function outcomeCost(value) {
329
- if (!isPlainObject(value)) return { latencyMs: null, rounds: null };
330
- const cost = value;
331
- return {
332
- latencyMs: Number.isFinite(cost.latencyMs) && cost.latencyMs >= 0 ? cost.latencyMs : null,
333
- rounds: Number.isFinite(cost.rounds) && cost.rounds >= 0 ? cost.rounds : null,
334
- };
335
- }
336
-
337
- // A3 (C100 O8): agent/model/provider linkage. Nullable and additive: a value the hook payload
338
- // or emitter did not supply stays null (UNKNOWN) — never a guess, never 0, never inferred from a model name.
339
- function linkageField(...candidates) {
340
- for (const value of candidates) {
341
- if (typeof value === 'string' && value.trim().length > 0) return value.trim().slice(0, 96);
342
- }
343
- return null;
344
- }
345
-
346
- /**
347
- * buildOutcomeObservedRecord({ outcome, projectRoot, payload, sessionId,
348
- * engine, env }) → semantic-record candidate for `outcome.observed`.
349
- *
350
- * `outcome` is the ARCH §Data Contracts OutcomeRecord subset the emitter knows:
351
- * { outcomeId?, runId?, routeId?, routeFingerprint?, ledgerKey?, verdict,
352
- * evidenceIds?, cost?, reviewActions?, enforcement?, engine?, source?, ts? }
353
- * Every field defaults sanely — a terminal event without runId/route data
354
- * still emits with nulls (task case 4) and never blocks the caller's path.
355
- * `payload` is the hook payload: it supplies session identity for runId
356
- * derivation, the session-boot request_key join, and the envelope session_id.
357
- * `enforcement` derives per FR-006 unless the emitter overrode it.
358
- */
359
- export function buildOutcomeObservedRecord({
360
- outcome = null,
361
- projectRoot = null,
362
- payload = {},
363
- sessionId = null,
364
- engine = null,
365
- env = null,
366
- } = {}) {
367
- const safe = isPlainObject(outcome) ? outcome : {};
368
- const resolvedSessionId = isNonEmptyString(sessionId)
369
- ? sessionId
370
- : (isNonEmptyString(payload?.session_id)
371
- ? payload.session_id
372
- : (isNonEmptyString(payload?.sessionId) ? payload.sessionId : null));
373
- const engineName = isNonEmptyString(engine)
374
- ? engine
375
- : (isNonEmptyString(safe.engine) ? safe.engine : null);
376
- const verdict = OUTCOME_VERDICTS.includes(safe.verdict) ? safe.verdict : 'INCONCLUSIVE';
377
- const recordPayload = {
378
- outcomeId: isNonEmptyString(safe.outcomeId) ? safe.outcomeId : `oc-${crypto.randomUUID()}`,
379
- runId: safe.runId !== undefined ? safe.runId : outcomeRunId(payload),
380
- routeId: safe.routeId !== undefined ? safe.routeId : null,
381
- routeFingerprint: safe.routeFingerprint !== undefined ? safe.routeFingerprint : null,
382
- ledgerKey: safe.ledgerKey !== undefined ? safe.ledgerKey : null,
383
- verdict,
384
- evidenceIds: outcomeStringList(safe.evidenceIds, 32),
385
- cost: outcomeCost(safe.cost),
386
- reviewActions: outcomeStringList(safe.reviewActions, 32),
387
- agentId: linkageField(safe.agentId, payload?.agent_id),
388
- parentAgentId: linkageField(safe.parentAgentId, payload?.parent_agent_id),
389
- agentType: linkageField(safe.agentType, payload?.agent_type),
390
- model: linkageField(safe.model, payload?.model),
391
- provider: linkageField(safe.provider),
392
- enforcement: OUTCOME_ENFORCEMENTS.has(safe.enforcement)
393
- ? safe.enforcement
394
- : deriveEnforcement({ engine: engineName, env }),
395
- engine: engineName,
396
- source: isNonEmptyString(safe.source) ? safe.source.slice(0, 96) : null,
397
- request_key: sessionBootRequestKey({ projectRoot, sessionId: resolvedSessionId }),
398
- ts: isNonEmptyString(safe.ts) ? safe.ts : new Date().toISOString(),
399
- };
400
- return {
401
- semantic_name: SEMANTIC_OUTCOME_OBSERVED,
402
- session_id: resolvedSessionId ?? undefined,
403
- payload: recordPayload,
404
- };
405
- }
406
-
407
- export { sessionBootRequestKey };
@@ -1,95 +0,0 @@
1
- /**
2
- * experimentPlan — pure staged controlled-experiment planner (GAP-c).
3
- *
4
- * Maps a KB optimization entry + a `computeGateComparison` GateComparison to
5
- * staged rollout ACTIONS over the seam ladder. The planner EMITS intent only:
6
- * it never mutates config, never calls killSwitch/resolveSeamConfig, and never
7
- * touches fs. Execution (if any) is a separate operator-owned act.
8
- *
9
- * Rules:
10
- * - gate must be a real GateComparison (verdict in pass|non-inferior|unknown);
11
- * anything else → TypeError (a fabricated gate can never plan a promotion).
12
- * - abort flag (operator rollback_criterion met) → kill 'abort-requested'.
13
- * - gate.forbiddenFailures > 0 → kill 'forbidden-failures' prepended.
14
- * - verdict !== 'pass' → hold (reason = verdict). 'non-inferior' means the
15
- * variant FAILED the pre-registered gate.
16
- * - verdict 'pass' + non-empty controlled_rollout.evidence_refs → one promote
17
- * action per seam in stage-rank order (shadow → canary → default), each
18
- * carrying requires_evidence_refs:true. Missing refs → hold
19
- * 'missing-controlled-rollout-evidence': promotion never fires on the
20
- * quality signal alone.
21
- */
22
-
23
- import { SEAM_MIN_STAGE } from '../rollout.js';
24
-
25
- export const ROLLOUT_ACTIONS = Object.freeze(['promote', 'hold', 'kill']);
26
-
27
- const GATE_VERDICTS = new Set(['pass', 'non-inferior', 'unknown']);
28
-
29
- const STAGE_RANK = { shadow: 1, canary: 2, default: 3 };
30
-
31
- function isPlainObject(value) {
32
- return value !== null && typeof value === 'object' && !Array.isArray(value);
33
- }
34
-
35
- function isNonEmptyStringList(value) {
36
- return (
37
- Array.isArray(value) &&
38
- value.length > 0 &&
39
- value.every((v) => typeof v === 'string' && v.length > 0)
40
- );
41
- }
42
-
43
- /**
44
- * @param {{optimization?: object, gate?: object, abort?: boolean}} input
45
- * @returns {{actions: object[]}} frozen action list
46
- */
47
- export function planControlledRollout(input = {}) {
48
- const { optimization, gate, abort } = isPlainObject(input) ? input : {};
49
-
50
- if (!isPlainObject(gate) || !GATE_VERDICTS.has(gate.verdict)) {
51
- throw new TypeError(
52
- 'experimentPlan: gate must be a GateComparison with verdict in pass|non-inferior|unknown',
53
- );
54
- }
55
-
56
- const actions = [];
57
-
58
- if (abort === true) {
59
- actions.push({ type: 'kill', reason: 'abort-requested' });
60
- }
61
- if (gate.forbiddenFailures > 0) {
62
- actions.push({ type: 'kill', reason: 'forbidden-failures' });
63
- }
64
-
65
- if (gate.verdict !== 'pass') {
66
- actions.push({ type: 'hold', reason: gate.verdict });
67
- return { actions: Object.freeze(actions) };
68
- }
69
-
70
- if (actions.length > 0) {
71
- // pass + forbiddenFailures is unreachable from real computeGateComparison
72
- // output (forbidden → non-inferior hard gate); defend the shape anyway.
73
- return { actions: Object.freeze(actions) };
74
- }
75
-
76
- const rollout = isPlainObject(optimization) ? optimization.controlled_rollout : undefined;
77
- const evidenceRefs = isPlainObject(rollout) ? rollout.evidence_refs : undefined;
78
- if (!isNonEmptyStringList(evidenceRefs)) {
79
- return {
80
- actions: Object.freeze([{ type: 'hold', reason: 'missing-controlled-rollout-evidence' }]),
81
- };
82
- }
83
-
84
- // Order from the shared seam contract (read-only): each seam promotes at the
85
- // stage it unlocks, lowest stage rank first.
86
- const seams = Object.entries(SEAM_MIN_STAGE)
87
- .map(([seam, stage]) => ({ seam, stage }))
88
- .sort((a, b) => STAGE_RANK[a.stage] - STAGE_RANK[b.stage] || a.seam.localeCompare(b.seam));
89
-
90
- for (const { seam, stage } of seams) {
91
- actions.push({ type: 'promote', seam, stage, requires_evidence_refs: true });
92
- }
93
-
94
- return { actions: Object.freeze(actions) };
95
- }