@ngockhoale/ukit 3.5.3 → 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 (59) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/manifests/documentation.yaml +12 -1
  3. package/manifests/platform.full.yaml +12 -0
  4. package/package.json +27 -1
  5. package/src/cli/commands/doctor.js +41 -0
  6. package/src/cli/commands/indexTools.js +10 -4
  7. package/src/cli/commands/memory.js +77 -6
  8. package/src/core/memory/episodes.js +106 -7
  9. package/src/core/memory/memoryCheck.js +241 -0
  10. package/src/core/memory/memoryCheckRun.js +27 -0
  11. package/src/core/memory/mutateMemory.js +37 -1
  12. package/src/core/memory/observations.js +192 -0
  13. package/src/core/memory/recallEngine.js +120 -7
  14. package/src/core/memory/records.js +23 -0
  15. package/src/core/memory/writeGate.js +137 -0
  16. package/src/core/runtimeConfig.js +11 -1
  17. package/src/index/buildIndex.js +26 -0
  18. package/src/index/paths.js +3 -1
  19. package/src/index/queryIndex.js +225 -10
  20. package/src/index/resolveContext.js +1 -1
  21. package/template_project/.claude/hooks/edit-hint.mjs +64 -17
  22. package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
  23. package/template_project/.claude/hooks/session-episode.sh +9 -4
  24. package/template_project/.claude/settings.json +2 -2
  25. package/template_project/.claude/ukit/index/lib/index-core.mjs +255 -12
  26. package/template_project/.claude/ukit/index/query-index.mjs +14 -3
  27. package/template_project/.claude/ukit/index/route-task.mjs +4 -1
  28. package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
  29. package/template_project/.claude/ukit/runtime/memory-recall.mjs +120 -7
  30. package/template_project/.claude/ukit/runtime/memory-validity.mjs +28 -1
  31. package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
  32. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  33. package/template_project/ukit/storage/config.json +4 -2
  34. package/src/core/agentRuntime/completionGate.js +0 -179
  35. package/src/core/agentRuntime/context.js +0 -571
  36. package/src/core/agentRuntime/qualityComparison.js +0 -112
  37. package/src/core/agentRuntime/resourcePolicy.js +0 -78
  38. package/src/core/agentRuntime/runtimeSupport.js +0 -255
  39. package/src/core/codeintel/manifest.js +0 -176
  40. package/src/core/experiments/deliberation.js +0 -327
  41. package/src/core/experiments/dynamicWorkflow.js +0 -507
  42. package/src/core/handoffDocValidator.js +0 -154
  43. package/src/core/memory/deltaOverlays.js +0 -493
  44. package/src/core/memory/learningCandidates.js +0 -347
  45. package/src/core/observability/emit/sessionBoot.js +0 -407
  46. package/src/core/observability/evaluation/replay.js +0 -149
  47. package/src/core/observability/evaluation/scorecard.js +0 -465
  48. package/src/core/observability/schema/compatibility.js +0 -180
  49. package/src/core/observability/support/renderer.js +0 -130
  50. package/src/core/reviewPanelAggregate.js +0 -204
  51. package/src/core/taskBudgetValidator.js +0 -251
  52. package/src/core/taskProgressGuard.js +0 -227
  53. package/src/decision/reviewVerdict.js +0 -339
  54. package/src/decision/runtimeFilter.js +0 -150
  55. package/src/decision/runtimeScheduler.js +0 -239
  56. package/src/index/contextPack.js +0 -285
  57. package/src/index/impactContext.js +0 -360
  58. package/src/index/reviewPolicy.js +0 -368
  59. package/src/index/sensitivePath.js +0 -21
@@ -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,149 +0,0 @@
1
- /**
2
- * replay.js (TASK-014, SPEC §5 DF-FR08/DF-FR12, §8) — honest replay fidelity.
3
- *
4
- * replayCase(goldenCase, { policyId }): ReplayResult
5
- *
6
- * Replay is a READ-ONLY, deterministic operation: it materializes the
7
- * recorded run for the requested policy into canonical envelope records and
8
- * returns them for static evaluation. It NEVER executes imported content,
9
- * never calls a model, and never writes to any store — no fs, no clock, no
10
- * randomness. The same (case, policyId) always produces the same records.
11
- *
12
- * Fidelity tags (declared by the case, never inferred):
13
- * POLICY — recorded under the named policy variant; full causal claim
14
- * within the recorded episode.
15
- * CONTEXT — recorded context replay (e.g. bundle-sourced evidence);
16
- * imported content is inert data, evaluated statically only.
17
- * SIMULATED — recorded inputs/versions replayed without a live host;
18
- * user acceptance is not observable → quality stays `unknown`
19
- * and no full causal effect may be claimed.
20
- *
21
- * Compact run encoding (golden fixture format): each record carries the
22
- * canonical field names plus `dt_ms` — the millisecond offset from the
23
- * episode start. replayCase materializes `monotonic_ns`, `wall_time_utc`,
24
- * `record_id`, `trace_id`, `execution_id` and the shared envelope fields
25
- * deterministically; explicit canonical values always win.
26
- */
27
-
28
- import { SEMANTIC_REGISTRY } from '../schema/registry.js';
29
-
30
- export const REPLAY_TAGS = Object.freeze(['POLICY', 'CONTEXT', 'SIMULATED']);
31
-
32
- export const REPLAY_LIMITATIONS = Object.freeze({
33
- POLICY: Object.freeze([]),
34
- CONTEXT: Object.freeze(['imported_content_static_only']),
35
- SIMULATED: Object.freeze([
36
- 'recorded_inputs_only',
37
- 'no_user_acceptance_observable',
38
- 'no_full_causal_claim',
39
- ]),
40
- });
41
-
42
- const REPLAY_EPOCH_MS = Date.UTC(2026, 0, 1, 0, 0, 0);
43
- const REPLAY_WRITER = 'writer-replay';
44
- const REPLAY_BOOT = 'boot-replay';
45
- const REPLAY_SESSION = 'session-replay';
46
- const REPLAY_PROJECT = 'project-replay';
47
-
48
- function isPlainObject(value) {
49
- return value !== null && typeof value === 'object' && !Array.isArray(value);
50
- }
51
-
52
- function asTag(value) {
53
- return REPLAY_TAGS.includes(value) ? value : 'POLICY';
54
- }
55
-
56
- /**
57
- * Resolve the run for `policyId`. `run.same_as` aliases another policy's run
58
- * (one hop) so identical variants do not duplicate record bytes.
59
- */
60
- function resolveRun(runs, policyId) {
61
- if (!isPlainObject(runs)) return null;
62
- let run = runs[policyId];
63
- if (isPlainObject(run) && typeof run.same_as === 'string') {
64
- run = runs[run.same_as];
65
- }
66
- return isPlainObject(run) && Array.isArray(run.records) ? run : null;
67
- }
68
-
69
- /**
70
- * Materialize one compact record into a canonical envelope record.
71
- * Deterministic: ids and clocks derive from (caseId, policyId, index, dt_ms).
72
- */
73
- function materializeRecord(raw, ctx, index) {
74
- const record = isPlainObject(raw) ? { ...raw } : {};
75
- const dtMs = typeof record.dt_ms === 'number' && Number.isFinite(record.dt_ms)
76
- ? record.dt_ms
77
- : index;
78
- delete record.dt_ms;
79
-
80
- if (typeof record.record_type !== 'string') record.record_type = 'fact';
81
- if (typeof record.schema_version !== 'number') record.schema_version = 1;
82
- if (typeof record.record_id !== 'string') {
83
- record.record_id = `rec-${ctx.caseId}-${ctx.policyId}-${String(index + 1).padStart(4, '0')}`;
84
- }
85
- if (typeof record.trace_id !== 'string') record.trace_id = ctx.traceId;
86
- if (typeof record.execution_id !== 'string') record.execution_id = ctx.executionId;
87
- if (typeof record.session_id !== 'string') record.session_id = REPLAY_SESSION;
88
- if (typeof record.project_ref !== 'string') record.project_ref = REPLAY_PROJECT;
89
- if (typeof record.boot_id !== 'string') record.boot_id = REPLAY_BOOT;
90
- if (typeof record.writer_id !== 'string') record.writer_id = REPLAY_WRITER;
91
- if (typeof record.sequence !== 'number') record.sequence = index + 1;
92
- if (typeof record.wall_time_utc !== 'string') {
93
- record.wall_time_utc = new Date(REPLAY_EPOCH_MS + dtMs).toISOString();
94
- }
95
- if (typeof record.monotonic_ns !== 'number') record.monotonic_ns = dtMs * 1e6;
96
- if (typeof record.importance !== 'string') record.importance = 'normal';
97
- if (typeof record.privacy_class !== 'string') {
98
- // Default to the semantic registry's privacy floor so materialized
99
- // records satisfy the contract; unregistered names fall back to public.
100
- record.privacy_class = SEMANTIC_REGISTRY[record.semantic_name]?.privacy_class ?? 'public';
101
- }
102
- if (!isPlainObject(record.payload)) record.payload = {};
103
- return record;
104
- }
105
-
106
- /**
107
- * @param {object} goldenCase — golden case with `runs` and optional
108
- * `fidelity.tag` / `provenance` / `imported_content`.
109
- * @param {{ policyId?: string }} [options]
110
- * @returns {{ ok: true, case_id, tag, limitations, records, provenance }
111
- * | { ok: false, reason, case_id, tag, limitations }}
112
- */
113
- export function replayCase(goldenCase, { policyId } = {}) {
114
- const caseId = isPlainObject(goldenCase) && typeof goldenCase.case_id === 'string'
115
- ? goldenCase.case_id
116
- : 'unknown';
117
- const tag = asTag(isPlainObject(goldenCase) && goldenCase.fidelity && goldenCase.fidelity.tag);
118
- const limitations = [...REPLAY_LIMITATIONS[tag]];
119
- const provenance = isPlainObject(goldenCase) && isPlainObject(goldenCase.provenance)
120
- ? { ...goldenCase.provenance }
121
- : {};
122
- if (provenance.source === 'support_bundle' && !limitations.includes('imported_content_static_only')) {
123
- limitations.push('imported_content_static_only');
124
- }
125
-
126
- const fail = (reason) => ({ ok: false, reason, case_id: caseId, tag, limitations });
127
- if (!isPlainObject(goldenCase)) return fail('invalid_case');
128
- if (typeof policyId !== 'string' || policyId.length === 0) return fail('missing_policy');
129
-
130
- const run = resolveRun(goldenCase.runs, policyId);
131
- if (!run) return fail('missing_run');
132
-
133
- const ctx = {
134
- caseId,
135
- policyId,
136
- traceId: `trace-${caseId}-${policyId}`,
137
- executionId: `exec-${caseId}-${policyId}`,
138
- };
139
- const records = run.records.map((raw, index) => materializeRecord(raw, ctx, index));
140
-
141
- return {
142
- ok: true,
143
- case_id: caseId,
144
- tag,
145
- limitations,
146
- records,
147
- provenance: { ...provenance, policy_id: policyId },
148
- };
149
- }