@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.
- package/CHANGELOG.md +38 -90
- package/README.md +1 -0
- package/manifests/documentation.yaml +12 -1
- package/manifests/platform.full.yaml +12 -0
- package/package.json +34 -1
- package/src/cli/commands/doctor.js +55 -2
- package/src/cli/commands/indexTools.js +10 -4
- package/src/cli/commands/memory.js +107 -8
- package/src/core/memory/episodes.js +106 -7
- package/src/core/memory/memoryCheck.js +241 -0
- package/src/core/memory/memoryCheckRun.js +27 -0
- package/src/core/memory/memoryHit.js +2 -0
- package/src/core/memory/mutateMemory.js +46 -1
- package/src/core/memory/observations.js +192 -0
- package/src/core/memory/projectIdentity.js +9 -2
- package/src/core/memory/recallEngine.js +204 -9
- package/src/core/memory/records.js +23 -0
- package/src/core/memory/registryPrune.js +230 -0
- package/src/core/memory/retrieval.js +12 -3
- package/src/core/memory/writeGate.js +137 -0
- package/src/core/runtimeConfig.js +12 -2
- package/src/index/buildIndex.js +26 -0
- package/src/index/paths.js +3 -1
- package/src/index/queryIndex.js +372 -26
- package/src/index/resolveContext.js +1 -1
- package/template_project/.claude/hooks/edit-hint.mjs +64 -17
- package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
- package/template_project/.claude/hooks/session-episode.sh +9 -4
- package/template_project/.claude/settings.json +2 -2
- package/template_project/.claude/ukit/index/edit-graph.mjs +141 -11
- package/template_project/.claude/ukit/index/lib/index-core.mjs +400 -27
- package/template_project/.claude/ukit/index/query-index.mjs +14 -3
- package/template_project/.claude/ukit/index/resolve-context.mjs +1 -1
- package/template_project/.claude/ukit/index/route-task.mjs +8 -2
- package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
- package/template_project/.claude/ukit/runtime/memory-lanes.mjs +44 -22
- package/template_project/.claude/ukit/runtime/memory-recall.mjs +204 -9
- package/template_project/.claude/ukit/runtime/memory-validity.mjs +259 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +4 -2
- package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
- package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
- package/template_project/ukit/storage/config.json +4 -2
- package/src/core/agentRuntime/completionGate.js +0 -179
- package/src/core/agentRuntime/context.js +0 -571
- package/src/core/agentRuntime/qualityComparison.js +0 -112
- package/src/core/agentRuntime/resourcePolicy.js +0 -78
- package/src/core/agentRuntime/runtimeSupport.js +0 -255
- package/src/core/codeintel/manifest.js +0 -176
- package/src/core/experiments/deliberation.js +0 -327
- package/src/core/experiments/dynamicWorkflow.js +0 -507
- package/src/core/handoffDocValidator.js +0 -154
- package/src/core/memory/deltaOverlays.js +0 -493
- package/src/core/memory/learningCandidates.js +0 -347
- package/src/core/observability/emit/sessionBoot.js +0 -407
- package/src/core/observability/evaluation/experimentPlan.js +0 -95
- package/src/core/observability/evaluation/perturbation.js +0 -273
- package/src/core/observability/evaluation/replay.js +0 -149
- package/src/core/observability/evaluation/scorecard.js +0 -465
- package/src/core/observability/schema/compatibility.js +0 -180
- package/src/core/observability/support/renderer.js +0 -130
- package/src/core/reviewPanelAggregate.js +0 -204
- package/src/core/taskBudgetValidator.js +0 -251
- package/src/core/taskProgressGuard.js +0 -227
- package/src/decision/reviewVerdict.js +0 -339
- package/src/decision/runtimeFilter.js +0 -150
- package/src/decision/runtimeScheduler.js +0 -239
- package/src/diagnostics/classifyHang.js +0 -246
- package/src/diagnostics/ompStallSnapshot.js +0 -199
- package/src/index/contextPack.js +0 -285
- package/src/index/impactContext.js +0 -360
- package/src/index/reviewPolicy.js +0 -368
- package/src/index/sensitivePath.js +0 -21
- package/src/render/instructionRenderer.js +0 -290
- package/src/skill/auditSkill.js +0 -140
- package/template_project/instructions/overlays/repo.md +0 -9
|
@@ -1,273 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* perturbation.js (TASK-002, SPEC §2 G5-FR06/G5-FR07) — synthetic mutation harness.
|
|
3
|
-
*
|
|
4
|
-
* mutateSummaries(summaries, { seed, plan? }) → { summaries, manifest }
|
|
5
|
-
* detectPerturbations(mutatedSummaries, baselineSummaries, manifest)
|
|
6
|
-
* → { injected, detected, missed[], details[] }
|
|
7
|
-
*
|
|
8
|
-
* Pure module: no fs, no clock, no unseeded randomness (mulberry32, same
|
|
9
|
-
* construction as the bench corpus generator). Mutations edit TraceSummary
|
|
10
|
-
* structures so the downstream pipeline sees a genuinely different trace;
|
|
11
|
-
* detection is measured through the REAL computeFingerprint /
|
|
12
|
-
* detectOpportunities path — never from the manifest alone.
|
|
13
|
-
*
|
|
14
|
-
* Mutation kinds (MUTATION_KINDS):
|
|
15
|
-
* drop_record — removes a span and raises drops.dropped_count>0
|
|
16
|
-
* retry_inflation — adds an attempt_index>1 model span and raises retries
|
|
17
|
-
* cache_miss_spike — adds cache misses (cache.observed, hit_rate recomputed)
|
|
18
|
-
* orphan_span — rewrites parent_span_id to an absent id
|
|
19
|
-
* telemetry_incomplete — flips telemetry_complete=false
|
|
20
|
-
*
|
|
21
|
-
* Detection rule (per manifest entry): the mutated trace is detected when its
|
|
22
|
-
* fingerprint kind/count diverges from its own baseline, OR — once the trace
|
|
23
|
-
* is proven changed (hash divergence) — its opportunity cluster reports
|
|
24
|
-
* `inconclusive` (the honesty path telemetry_incomplete relies on) or a
|
|
25
|
-
* non-clean pattern. An unmutated trace claimed in the manifest cannot be
|
|
26
|
-
* detected: hash-identical traces have nothing to report.
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
import { computeFingerprint } from '../analytics/fingerprints.js';
|
|
30
|
-
import { detectOpportunities } from '../analytics/opportunities.js';
|
|
31
|
-
|
|
32
|
-
export const MUTATION_KINDS = Object.freeze([
|
|
33
|
-
'drop_record',
|
|
34
|
-
'retry_inflation',
|
|
35
|
-
'cache_miss_spike',
|
|
36
|
-
'orphan_span',
|
|
37
|
-
'telemetry_incomplete',
|
|
38
|
-
]);
|
|
39
|
-
|
|
40
|
-
// Deterministic PRNG (mulberry32) — identical construction to the bench corpus.
|
|
41
|
-
function mulberry32(seed) {
|
|
42
|
-
let a = seed >>> 0;
|
|
43
|
-
return function next() {
|
|
44
|
-
a |= 0;
|
|
45
|
-
a = (a + 0x6d2b79f5) | 0;
|
|
46
|
-
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
47
|
-
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
48
|
-
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function isPlainObject(value) {
|
|
53
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function num(value) {
|
|
57
|
-
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Candidate indices for a kind — a mutation must produce a genuinely
|
|
62
|
-
* different trace, so kinds with preconditions filter to eligible traces.
|
|
63
|
-
* Prefers traces not already mutated by this call.
|
|
64
|
-
*/
|
|
65
|
-
function candidateIndices(mutated, kind, used) {
|
|
66
|
-
const eligible = mutated
|
|
67
|
-
.map((s, idx) => ({ s, idx }))
|
|
68
|
-
.filter(({ s }) => {
|
|
69
|
-
if (!isPlainObject(s) || !Array.isArray(s.spans) || s.spans.length === 0) return false;
|
|
70
|
-
if (kind === 'telemetry_incomplete') return s.telemetry_complete === true;
|
|
71
|
-
return true;
|
|
72
|
-
})
|
|
73
|
-
.map(({ idx }) => idx);
|
|
74
|
-
const fresh = eligible.filter((idx) => !used.has(idx));
|
|
75
|
-
return fresh.length > 0 ? fresh : eligible;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function ensureCounters(summary) {
|
|
79
|
-
if (!isPlainObject(summary.retries)) summary.retries = {};
|
|
80
|
-
if (!isPlainObject(summary.drops)) summary.drops = {};
|
|
81
|
-
if (!isPlainObject(summary.drops.by_reason)) summary.drops.by_reason = {};
|
|
82
|
-
if (!isPlainObject(summary.cache)) summary.cache = {};
|
|
83
|
-
if (!isPlainObject(summary.coverage)) summary.coverage = {};
|
|
84
|
-
}
|
|
85
|
-
const MUTATORS = {
|
|
86
|
-
drop_record(summary) {
|
|
87
|
-
const idx = summary.spans.findIndex(
|
|
88
|
-
(s) => typeof s.parent_span_id === 'string' && s.parent_span_id.length > 0,
|
|
89
|
-
);
|
|
90
|
-
const i = idx >= 0 ? idx : 0;
|
|
91
|
-
const removed = summary.spans.splice(i, 1)[0] || null;
|
|
92
|
-
summary.drops.events = num(summary.drops.events) + 1;
|
|
93
|
-
summary.drops.dropped_count = num(summary.drops.dropped_count) + 1;
|
|
94
|
-
summary.drops.by_reason.synthetic_drop = num(summary.drops.by_reason.synthetic_drop) + 1;
|
|
95
|
-
summary.telemetry_complete = false;
|
|
96
|
-
summary.coverage.spans = summary.spans.length;
|
|
97
|
-
return { removed_span_id: removed ? removed.span_id : null };
|
|
98
|
-
},
|
|
99
|
-
|
|
100
|
-
retry_inflation(summary) {
|
|
101
|
-
const model =
|
|
102
|
-
summary.spans.find((s) => s.family === 'model') ||
|
|
103
|
-
summary.spans[summary.spans.length - 1] ||
|
|
104
|
-
null;
|
|
105
|
-
const maxAttempt = summary.spans.reduce(
|
|
106
|
-
(m, s) => (Number.isInteger(s.attempt_index) ? Math.max(m, s.attempt_index) : m),
|
|
107
|
-
0,
|
|
108
|
-
);
|
|
109
|
-
const attemptIndex = Math.max(2, maxAttempt + 1);
|
|
110
|
-
const clone = {
|
|
111
|
-
...(model || {
|
|
112
|
-
parent_span_id: null,
|
|
113
|
-
family: 'model',
|
|
114
|
-
operation: null,
|
|
115
|
-
status: 'completed',
|
|
116
|
-
duration_ms: 0,
|
|
117
|
-
}),
|
|
118
|
-
span_id: `${model ? model.span_id : 'span'}-retry${attemptIndex}`,
|
|
119
|
-
attempt_index: attemptIndex,
|
|
120
|
-
status: 'completed',
|
|
121
|
-
start_record_id: `rec-${summary.trace_id}-retry${attemptIndex}-start`,
|
|
122
|
-
end_record_id: `rec-${summary.trace_id}-retry${attemptIndex}-end`,
|
|
123
|
-
};
|
|
124
|
-
summary.spans.push(clone);
|
|
125
|
-
summary.retries.retries = num(summary.retries.retries) + 1;
|
|
126
|
-
summary.retries.model_attempts = num(summary.retries.model_attempts) + 1;
|
|
127
|
-
summary.coverage.spans = summary.spans.length;
|
|
128
|
-
return { added_attempt_span: clone.span_id, attempt_index: attemptIndex };
|
|
129
|
-
},
|
|
130
|
-
|
|
131
|
-
cache_miss_spike(summary, rand) {
|
|
132
|
-
const added = 2 + Math.floor(rand() * 3); // 2..4 misses
|
|
133
|
-
summary.cache.observed = true;
|
|
134
|
-
summary.cache.hits = num(summary.cache.hits);
|
|
135
|
-
summary.cache.misses = num(summary.cache.misses) + added;
|
|
136
|
-
const lookups = summary.cache.hits + summary.cache.misses;
|
|
137
|
-
summary.cache.hit_rate = lookups > 0 ? summary.cache.hits / lookups : null;
|
|
138
|
-
return { misses_added: added };
|
|
139
|
-
},
|
|
140
|
-
|
|
141
|
-
orphan_span(summary) {
|
|
142
|
-
const idx = summary.spans.findIndex(
|
|
143
|
-
(s) => typeof s.parent_span_id === 'string' && s.parent_span_id.length > 0,
|
|
144
|
-
);
|
|
145
|
-
const i = idx >= 0 ? idx : 0;
|
|
146
|
-
const target = summary.spans[i];
|
|
147
|
-
const previous = target.parent_span_id ?? null;
|
|
148
|
-
target.parent_span_id = `absent-${target.span_id}`;
|
|
149
|
-
summary.coverage.orphan_spans = num(summary.coverage.orphan_spans) + 1;
|
|
150
|
-
return { span_id: target.span_id, previous_parent: previous };
|
|
151
|
-
},
|
|
152
|
-
|
|
153
|
-
telemetry_incomplete(summary) {
|
|
154
|
-
const previous = summary.telemetry_complete;
|
|
155
|
-
summary.telemetry_complete = false;
|
|
156
|
-
return { previous_telemetry_complete: previous };
|
|
157
|
-
},
|
|
158
|
-
};
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* @param {Array<object>} summaries — baseline TraceSummary objects (not mutated).
|
|
162
|
-
* @param {{ seed?: number, plan?: Array<{kind:string}> }} [options]
|
|
163
|
-
* plan defaults to one mutation per MUTATION_KINDS entry.
|
|
164
|
-
* @returns {{ summaries: Array<object>, manifest: Array<object> }}
|
|
165
|
-
* manifest entries: { mutation_id, trace_id, kind, detail }.
|
|
166
|
-
*/
|
|
167
|
-
export function mutateSummaries(summaries, { seed = 42, plan } = {}) {
|
|
168
|
-
if (!Array.isArray(summaries)) {
|
|
169
|
-
throw new TypeError('mutateSummaries: summaries must be an array of TraceSummary');
|
|
170
|
-
}
|
|
171
|
-
const effectivePlan = Array.isArray(plan) ? plan : MUTATION_KINDS.map((kind) => ({ kind }));
|
|
172
|
-
for (const entry of effectivePlan) {
|
|
173
|
-
if (!isPlainObject(entry) || !MUTATION_KINDS.includes(entry.kind)) {
|
|
174
|
-
throw new TypeError(
|
|
175
|
-
`mutateSummaries: plan entries need kind ∈ {${MUTATION_KINDS.join(', ')}}`,
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
const rand = mulberry32(seed);
|
|
181
|
-
const mutated = summaries.map((s) => JSON.parse(JSON.stringify(s)));
|
|
182
|
-
const manifest = [];
|
|
183
|
-
const used = new Set();
|
|
184
|
-
|
|
185
|
-
effectivePlan.forEach((entry, i) => {
|
|
186
|
-
const pickFrom = candidateIndices(mutated, entry.kind, used);
|
|
187
|
-
if (pickFrom.length === 0) return;
|
|
188
|
-
const targetIdx = pickFrom[Math.floor(rand() * pickFrom.length)];
|
|
189
|
-
used.add(targetIdx);
|
|
190
|
-
const summary = mutated[targetIdx];
|
|
191
|
-
ensureCounters(summary);
|
|
192
|
-
const detail = MUTATORS[entry.kind](summary, rand);
|
|
193
|
-
manifest.push({
|
|
194
|
-
mutation_id: `mut-${String(i + 1).padStart(3, '0')}`,
|
|
195
|
-
trace_id: typeof summary.trace_id === 'string' ? summary.trace_id : `idx-${targetIdx}`,
|
|
196
|
-
kind: entry.kind,
|
|
197
|
-
detail,
|
|
198
|
-
});
|
|
199
|
-
});
|
|
200
|
-
|
|
201
|
-
return { summaries: mutated, manifest };
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* Measure detection through the real pipeline: computeFingerprint for
|
|
206
|
-
* per-trace divergence vs baseline and detectOpportunities for cluster
|
|
207
|
-
* status over the mutated set.
|
|
208
|
-
*
|
|
209
|
-
* @param {Array<object>} mutatedSummaries
|
|
210
|
-
* @param {Array<object>} baselineSummaries
|
|
211
|
-
* @param {Array<object>} manifest — entries from mutateSummaries.
|
|
212
|
-
* @returns {{ injected:number, detected:number, missed:Array<object>, details:Array<object> }}
|
|
213
|
-
*/
|
|
214
|
-
export function detectPerturbations(mutatedSummaries, baselineSummaries, manifest) {
|
|
215
|
-
if (!Array.isArray(mutatedSummaries) || !Array.isArray(baselineSummaries) || !Array.isArray(manifest)) {
|
|
216
|
-
throw new TypeError('detectPerturbations: summaries and manifest must be arrays');
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const baselineByTrace = new Map();
|
|
220
|
-
for (const s of baselineSummaries) {
|
|
221
|
-
if (isPlainObject(s) && typeof s.trace_id === 'string') baselineByTrace.set(s.trace_id, s);
|
|
222
|
-
}
|
|
223
|
-
const mutatedByTrace = new Map();
|
|
224
|
-
for (const s of mutatedSummaries) {
|
|
225
|
-
if (isPlainObject(s) && typeof s.trace_id === 'string') mutatedByTrace.set(s.trace_id, s);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// Real pipeline — never read the manifest as evidence.
|
|
229
|
-
const opportunities = detectOpportunities(mutatedSummaries);
|
|
230
|
-
const oppByTrace = new Map();
|
|
231
|
-
for (const opp of opportunities) {
|
|
232
|
-
for (const ref of opp.trace_refs || []) {
|
|
233
|
-
if (!oppByTrace.has(ref)) oppByTrace.set(ref, opp);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
const details = [];
|
|
238
|
-
for (const entry of manifest) {
|
|
239
|
-
const mutated = mutatedByTrace.get(entry.trace_id);
|
|
240
|
-
const baseline = baselineByTrace.get(entry.trace_id);
|
|
241
|
-
const via = [];
|
|
242
|
-
let opportunity = null;
|
|
243
|
-
if (mutated && baseline) {
|
|
244
|
-
const fm = computeFingerprint(mutated);
|
|
245
|
-
const fb = computeFingerprint(baseline);
|
|
246
|
-
const changed = fm.hash !== fb.hash;
|
|
247
|
-
if (fm.kind !== fb.kind || fm.count !== fb.count) via.push('fingerprint');
|
|
248
|
-
opportunity = oppByTrace.get(entry.trace_id) || null;
|
|
249
|
-
if (changed && opportunity) {
|
|
250
|
-
if (opportunity.status === 'inconclusive') via.push('inconclusive');
|
|
251
|
-
else if (opportunity.fingerprint && opportunity.fingerprint.kind !== 'clean') {
|
|
252
|
-
via.push('opportunity');
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
details.push({
|
|
257
|
-
mutation_id: entry.mutation_id,
|
|
258
|
-
trace_id: entry.trace_id,
|
|
259
|
-
kind: entry.kind,
|
|
260
|
-
detected: via.length > 0,
|
|
261
|
-
via,
|
|
262
|
-
opportunity,
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
const missed = details.filter((d) => !d.detected);
|
|
267
|
-
return {
|
|
268
|
-
injected: manifest.length,
|
|
269
|
-
detected: details.length - missed.length,
|
|
270
|
-
missed,
|
|
271
|
-
details,
|
|
272
|
-
};
|
|
273
|
-
}
|
|
@@ -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
|
-
}
|