@ngockhoale/ukit 3.5.3 → 3.5.5

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 (70) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/manifests/documentation.yaml +12 -1
  3. package/manifests/platform.full.yaml +12 -0
  4. package/package.json +29 -2
  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 +88 -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 +39 -0
  11. package/src/core/memory/memoryHit.js +31 -15
  12. package/src/core/memory/mutateMemory.js +37 -1
  13. package/src/core/memory/observations.js +192 -0
  14. package/src/core/memory/recallEngine.js +159 -10
  15. package/src/core/memory/recallLanes.js +182 -0
  16. package/src/core/memory/records.js +23 -0
  17. package/src/core/memory/retrieval.js +13 -1
  18. package/src/core/memory/topicCommand.js +75 -0
  19. package/src/core/memory/topicPages.js +545 -0
  20. package/src/core/memory/writeGate.js +137 -0
  21. package/src/core/runtimeConfig.js +56 -1
  22. package/src/decision/registry.js +17 -0
  23. package/src/index/buildIndex.js +312 -5
  24. package/src/index/languageTools.js +100 -0
  25. package/src/index/paths.js +4 -1
  26. package/src/index/queryIndex.js +356 -14
  27. package/src/index/resolveContext.js +1 -1
  28. package/template_project/.claude/hooks/edit-hint.mjs +64 -17
  29. package/template_project/.claude/hooks/session-episode-start.mjs +35 -0
  30. package/template_project/.claude/hooks/session-episode.sh +9 -4
  31. package/template_project/.claude/settings.json +2 -2
  32. package/template_project/.claude/ukit/index/lib/index-core.mjs +769 -18
  33. package/template_project/.claude/ukit/index/query-index.mjs +14 -3
  34. package/template_project/.claude/ukit/index/refresh-index.mjs +11 -0
  35. package/template_project/.claude/ukit/index/route-task.mjs +4 -1
  36. package/template_project/.claude/ukit/runtime/memory-check.mjs +241 -0
  37. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +9 -2
  38. package/template_project/.claude/ukit/runtime/memory-recall.mjs +159 -10
  39. package/template_project/.claude/ukit/runtime/memory-topics.mjs +545 -0
  40. package/template_project/.claude/ukit/runtime/memory-validity.mjs +28 -1
  41. package/template_project/.claude/ukit/runtime/self-improve-trigger.mjs +212 -5
  42. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  43. package/template_project/ukit/storage/config.json +21 -2
  44. package/manifests/instructionRules.yaml +0 -442
  45. package/src/core/agentRuntime/completionGate.js +0 -179
  46. package/src/core/agentRuntime/context.js +0 -571
  47. package/src/core/agentRuntime/qualityComparison.js +0 -112
  48. package/src/core/agentRuntime/resourcePolicy.js +0 -78
  49. package/src/core/agentRuntime/runtimeSupport.js +0 -255
  50. package/src/core/codeintel/manifest.js +0 -176
  51. package/src/core/experiments/deliberation.js +0 -327
  52. package/src/core/experiments/dynamicWorkflow.js +0 -507
  53. package/src/core/handoffDocValidator.js +0 -154
  54. package/src/core/memory/deltaOverlays.js +0 -493
  55. package/src/core/memory/learningCandidates.js +0 -347
  56. package/src/core/observability/emit/sessionBoot.js +0 -407
  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/index/contextPack.js +0 -285
  68. package/src/index/impactContext.js +0 -360
  69. package/src/index/reviewPolicy.js +0 -368
  70. package/src/index/sensitivePath.js +0 -21
@@ -1,571 +0,0 @@
1
- // Bounded runtime-context compiler (G5 / TASK-002) + subagent context
2
- // manifest builder (C89-006 / SPEC §7).
3
- // Pure module: no I/O, no runtimeConfig reads, no adapter/gate imports.
4
- // Compiles goal / verified state / evidence / memory records into a frozen
5
- // BoundedContext under a hard byte budget that includes framing and
6
- // provenance labels. Every included item carries {source, ref, bytes, age?};
7
- // every dropped item is listed in omitted[] with {source, ref, reason} —
8
- // omission is always visible, never silent.
9
- //
10
- // Memory records pass through src/core/memory/policy.js eligible();
11
- // ineligible records are excluded (omitted with the policy reason), and
12
- // eligible-but-unverified records are labeled 'unverified' and quoted —
13
- // never injected as instruction.
14
- import crypto from 'node:crypto';
15
-
16
- import { validateTaskContract } from './contract.js';
17
- import { eligible } from '../memory/policy.js';
18
- import { isSensitivePath } from '../../index/sensitivePath.js';
19
-
20
- const STALE_MS = 15 * 60 * 1000; // default freshness window for evidence
21
-
22
- const HEADER = '# UKit runtime context';
23
- const FOOTER = '# end context';
24
-
25
- function byteLen(s) {
26
- return Buffer.byteLength(s, 'utf8');
27
- }
28
-
29
- function oneLine(text) {
30
- return String(text).split('\n').join(' ');
31
- }
32
-
33
- // Each candidate: { source, ref, label|null, age?, line, required }
34
- function renderLine(c) {
35
- const label = c.label ? ` ${c.label}` : '';
36
- const age = c.age != null ? ` age=${c.age}ms` : '';
37
- const prefix = c.label === 'unverified' ? '> ' : '';
38
- return `${prefix}[${c.source}${label} ref=${c.ref}${age}] ${oneLine(c.text)}`;
39
- }
40
-
41
- export function compileRuntimeContext({
42
- task,
43
- verifiedState,
44
- evidence,
45
- memoryRecords,
46
- budget,
47
- now,
48
- } = {}) {
49
- const nowMs = typeof now === 'number' ? now : Date.now();
50
-
51
- if (typeof budget !== 'number' || !Number.isFinite(budget) || budget <= 0) {
52
- return { ok: false, code: 'malformed_input' };
53
- }
54
- if (task == null || typeof task !== 'object' || typeof task.goal !== 'string' || task.goal.length === 0) {
55
- return { ok: false, code: 'malformed_input' };
56
- }
57
- if (evidence != null && !Array.isArray(evidence)) {
58
- return { ok: false, code: 'malformed_input' };
59
- }
60
- if (memoryRecords != null && !Array.isArray(memoryRecords)) {
61
- return { ok: false, code: 'malformed_input' };
62
- }
63
-
64
- const candidates = [];
65
- const omitted = [];
66
- const push = (c, required = false) => candidates.push({ ...c, required });
67
- const omit = (source, ref, reason) =>
68
- omitted.push(Object.freeze({ source, ref, reason }));
69
-
70
- // Goal is always required — a context with no goal is not a context.
71
- push({ source: 'task', ref: task.id != null ? String(task.id) : 'task', text: `goal: ${task.goal}` }, true);
72
-
73
- if (verifiedState != null) {
74
- const text = typeof verifiedState === 'string' ? verifiedState : verifiedState.summary;
75
- if (typeof text === 'string' && text.length > 0) {
76
- push({ source: 'verified-state', ref: verifiedState.ref != null ? String(verifiedState.ref) : 'state', text }, true);
77
- }
78
- }
79
-
80
- for (const ev of evidence || []) {
81
- if (ev == null || typeof ev !== 'object' || typeof ev.content !== 'string') {
82
- omit('evidence', ev && ev.ref != null ? String(ev.ref) : 'unknown', 'malformed_input');
83
- continue;
84
- }
85
- const source = typeof ev.source === 'string' ? ev.source : 'evidence';
86
- const ref = ev.ref != null ? String(ev.ref) : 'unknown';
87
- const ttl = typeof ev.ttlMs === 'number' ? ev.ttlMs : STALE_MS;
88
- const age = typeof ev.observedAt === 'number' ? nowMs - ev.observedAt : null;
89
- if (age != null && age > ttl) {
90
- omit(source, ref, 'stale');
91
- continue;
92
- }
93
- push({ source, ref, text: ev.content, age });
94
- }
95
-
96
- const memContext = {
97
- projectId:
98
- (verifiedState && typeof verifiedState.projectId === 'string' ? verifiedState.projectId : null)
99
- ?? (typeof task.projectId === 'string' ? task.projectId : null),
100
- now: nowMs,
101
- };
102
-
103
- for (const rec of memoryRecords || []) {
104
- const ref = rec && rec.id != null ? String(rec.id) : 'memory';
105
- const verdict = eligible(rec, memContext);
106
- if (!verdict.ok) {
107
- omit('memory', ref, verdict.reason);
108
- continue;
109
- }
110
- const text = typeof rec.content === 'string' ? rec.content
111
- : typeof rec.text === 'string' ? rec.text
112
- : null;
113
- if (text == null) {
114
- omit('memory', ref, 'malformed_input');
115
- continue;
116
- }
117
- const unverified = rec.verified !== true && rec.trust_tier !== 'verified';
118
- push({ source: 'memory', ref, text, label: unverified ? 'unverified' : null });
119
- }
120
-
121
- const framingBytes = byteLen(`${HEADER}\n\n${FOOTER}\n`);
122
- let used = framingBytes;
123
- const includedLines = [];
124
- const included = [];
125
-
126
- for (const c of candidates) {
127
- const line = renderLine(c);
128
- const lineBytes = byteLen(line) + 1; // trailing newline
129
- if (used + lineBytes <= budget) {
130
- used += lineBytes;
131
- includedLines.push(line);
132
- const item = { source: c.source, ref: c.ref, bytes: lineBytes };
133
- if (c.age != null) item.age = c.age;
134
- if (c.label) item.label = c.label;
135
- included.push(Object.freeze(item));
136
- } else if (c.required) {
137
- // A required element cannot fit: nothing useful can be emitted.
138
- return { ok: false, code: 'over_budget' };
139
- } else {
140
- omit(c.source, c.ref, 'over_budget');
141
- }
142
- }
143
-
144
- const packet = `${HEADER}\n${includedLines.join('\n')}\n${FOOTER}\n`;
145
- return {
146
- ok: true,
147
- context: Object.freeze({
148
- packet,
149
- included: Object.freeze(included),
150
- omitted: Object.freeze(omitted),
151
- }),
152
- };
153
- }
154
-
155
- // --- C89-006: subagent ContextManifest (SPEC §7, FR-05) ---------------------
156
- // `buildSubagentContext` selects isolated/curated context for a delegated
157
- // role from caller-supplied candidates and emits a traceable manifest:
158
- // every include/exclude carries reason + provenance + a deterministic token
159
- // estimate, required contract fields are never dropped by size pressure,
160
- // sensitive/secret refs are redacted before any retrieval runs, exact
161
- // duplicates collapse while keeping lineage (sourceRefs), and a requested
162
- // `fork` is honestly labeled `fork_unavailable` until a host probe proves
163
- // real state inheritance — a summary copy is never a fork.
164
- //
165
- // The builder stays pure: it performs no fs/config/adapter access itself.
166
- // Optional original verification is injected through `resolveOriginal`
167
- // (wired to eventStore.resolveRunArtifact by callers that need it);
168
- // persistence is eventStore.persistContextManifestRef, not this module.
169
-
170
- const MANIFEST_VERSION = 1;
171
- export const CONTEXT_MANIFEST_POLICY_VERSION = 'context-selection.v1';
172
-
173
- // Deterministic local estimator (chars/4, min 1) — matches the codebase
174
- // convention without importing the I/O-bearing token module.
175
- function estimateTokens(value) {
176
- const text = String(value ?? '');
177
- if (!text) return 0;
178
- return Math.max(1, Math.ceil(text.length / 4));
179
- }
180
-
181
- const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
182
- const isPlainRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
183
-
184
- // Fingerprint an item's content exactly (SPEC §7: exact dedupe only first —
185
- // semantic pruning is deferred). Items with no content fall back to the ref.
186
- function fingerprintOf(ref, text) {
187
- const payload = text != null && text !== '' ? text : `<no-content:${ref}>`;
188
- return crypto.createHash('sha256').update(payload).digest('hex');
189
- }
190
-
191
- const KNOWN_MODES = Object.freeze(['isolated', 'curated', 'fork']);
192
-
193
- function forkCellStatus(hostCapabilities) {
194
- return hostCapabilities?.capabilities?.fork?.status ?? null;
195
- }
196
-
197
- /**
198
- * Assemble a subagent ContextManifest (SPEC §7).
199
- *
200
- * @param {object} args
201
- * @param {object} args.taskContract TaskContract v1 (validateTaskContract
202
- * enforced at this boundary — a malformed contract gets no context).
203
- * @param {string} args.role child role; defaults to taskContract.role.
204
- * @param {string} [args.mode] 'isolated'|'curated'|'fork'; defaults to
205
- * taskContract.contextMode then 'curated'. 'fork' resolves
206
- * 'fork_unavailable' unless hostCapabilities proves real inheritance.
207
- * @param {Array<object>} [args.candidates] parent state/evidence/memory
208
- * candidates. Fields: ref, content|text, required, kind, audience,
209
- * sensitivity ('sensitive' → redacted), provenance, observedAt, ttlMs,
210
- * memoryRecord (routed through memory/policy eligible()), artifactRef
211
- * (resolved via resolveOriginal when supplied).
212
- * @param {object} [args.hostCapabilities] probeSubagentCapabilities result.
213
- * @param {object} [args.policyContext] {projectId, projectAliases,
214
- * includeUser} for memory eligible().
215
- * @param {Function} [args.resolveOriginal] async (artifactRef) →
216
- * {ok:true,sha256?}|{status:'unavailable',reason} — injected resolver;
217
- * availability checks run AFTER sensitivity eligibility so secrets are
218
- * never fetched.
219
- * @param {number} [args.budgetTokens] advisory cap: optional items that do
220
- * not fit are excluded 'over_budget'; required items are never dropped —
221
- * an exceedance flips manifest.overBudget instead (quality > budget).
222
- * @param {string} [args.runId] parent run id; defaults taskContract.id.
223
- * @param {number} [args.now] clock for staleness checks.
224
- * @returns {Promise<{ok:true, mode:'isolated'|'curated'|'fork_unavailable'|'fork',
225
- * manifest:object, contextRefs:string[]}|{ok:false, code:string, errors?:string[]}>}
226
- */
227
- export async function buildSubagentContext({
228
- taskContract,
229
- role,
230
- mode,
231
- candidates,
232
- hostCapabilities,
233
- policyContext = {},
234
- resolveOriginal = null,
235
- budgetTokens = null,
236
- runId,
237
- now,
238
- } = {}) {
239
- if (taskContract === undefined || taskContract === null) {
240
- return { ok: false, code: 'malformed_input' };
241
- }
242
- const contractVerdict = validateTaskContract(taskContract);
243
- if (!contractVerdict.valid) {
244
- return { ok: false, code: 'invalid_contract', errors: contractVerdict.errors };
245
- }
246
- if (candidates != null && !Array.isArray(candidates)) {
247
- return { ok: false, code: 'malformed_input' };
248
- }
249
-
250
- const effectiveRole = isNonEmptyStr(role) ? role : taskContract.role;
251
- const requestedMode = mode ?? taskContract.contextMode ?? 'curated';
252
- if (!KNOWN_MODES.includes(requestedMode)) {
253
- return { ok: false, code: 'malformed_input' };
254
- }
255
-
256
- // Fork honesty (SPEC §7): a real fork exists only where a host probe proves
257
- // state inheritance; everything else is the curated fallback labeled
258
- // 'fork_unavailable' — copying a short summary is never labeled fork.
259
- const effectiveMode = requestedMode === 'fork'
260
- ? (forkCellStatus(hostCapabilities) === 'supported' ? 'fork' : 'fork_unavailable')
261
- : requestedMode;
262
-
263
- const effectiveRunId = isNonEmptyStr(runId) ? runId : taskContract.id;
264
- const nowMs = typeof now === 'number' ? now : Date.now();
265
- const budget = Number.isInteger(budgetTokens) && budgetTokens >= 0
266
- ? budgetTokens
267
- : null;
268
-
269
- const items = [];
270
- const pushItem = (entry) => {
271
- items.push(Object.freeze(entry));
272
- return entry;
273
- };
274
- const exclude = (ref, reason, extra = {}) =>
275
- pushItem({
276
- ref,
277
- included: false,
278
- reason,
279
- tokenEstimate: estimateTokens(extra.text ?? ref),
280
- provenance: extra.provenance ?? 'unknown',
281
- ...(extra.detail != null ? { detail: extra.detail } : {}),
282
- });
283
-
284
- // Required contract-derived items first: objective / scope / constraints /
285
- // expectedOutput / stopConditions / evidenceRequirement / knownFacts are
286
- // the acceptance boundary and are never droppable by size pressure.
287
- const contractItem = (ref, text, provenance = 'task-contract') =>
288
- pushItem({
289
- ref,
290
- included: true,
291
- reason: 'required_contract',
292
- tokenEstimate: estimateTokens(text),
293
- provenance,
294
- fingerprint: fingerprintOf(ref, text),
295
- });
296
-
297
- contractItem('contract:objective', taskContract.objective);
298
- for (const [i, p] of (taskContract.scope?.include ?? []).entries()) {
299
- contractItem(`contract:scope-include:${i}`, `scope include: ${p}`);
300
- }
301
- for (const [i, p] of (taskContract.scope?.exclude ?? []).entries()) {
302
- contractItem(`contract:scope-exclude:${i}`, `scope exclude: ${p}`);
303
- }
304
- (taskContract.constraints ?? []).forEach((c, i) => {
305
- contractItem(`contract:constraint:${i}`, `constraint: ${c}`);
306
- });
307
- contractItem('contract:expected-output', taskContract.expectedOutput);
308
- if (taskContract.evidenceRequirement != null) {
309
- contractItem('contract:evidence-requirement', taskContract.evidenceRequirement);
310
- }
311
- (taskContract.stopConditions ?? []).forEach((s, i) => {
312
- contractItem(`contract:stop-condition:${i}`, `stop: ${s}`);
313
- });
314
- (taskContract.knownFacts ?? []).forEach((f, i) => {
315
- contractItem(`contract:known-fact:${i}`, f.statement, f.source);
316
- });
317
-
318
- const memContext = {
319
- projectId: isNonEmptyStr(policyContext.projectId) ? policyContext.projectId : null,
320
- projectAliases: Array.isArray(policyContext.projectAliases)
321
- ? policyContext.projectAliases
322
- : undefined,
323
- includeUser: policyContext.includeUser === true,
324
- now: nowMs,
325
- };
326
-
327
- const seenFingerprints = new Map(); // fingerprint → first ref (lineage)
328
- let tokensUsed = items.reduce((n, i) => n + i.tokenEstimate, 0);
329
- let overBudget = budget != null && tokensUsed > budget;
330
-
331
- for (const [idx, cand] of (candidates ?? []).entries()) {
332
- const ref = isNonEmptyStr(cand?.ref) ? cand.ref : `candidate:${idx}`;
333
- const provenance = isNonEmptyStr(cand?.provenance)
334
- ? cand.provenance
335
- : isNonEmptyStr(cand?.source) ? cand.source : 'unknown';
336
- const text = typeof cand?.content === 'string' ? cand.content
337
- : typeof cand?.text === 'string' ? cand.text : null;
338
- const tokenEstimate = estimateTokens(text ?? ref);
339
-
340
- if (!isPlainRec(cand) || !isNonEmptyStr(cand.ref)) {
341
- exclude(ref, 'malformed_candidate', { text, provenance });
342
- continue;
343
- }
344
- // Secrets never reach the child — redact before any original resolution
345
- // so the resolver never fetches bytes it must not see.
346
- if (cand.sensitivity === 'sensitive' || cand.artifactRef?.sensitivity === 'sensitive') {
347
- exclude(ref, 'redacted', { text, provenance });
348
- continue;
349
- }
350
- if (cand.memoryRecord != null) {
351
- const verdict = eligible(cand.memoryRecord, memContext);
352
- if (!verdict.ok) {
353
- exclude(ref, verdict.reason, { text, provenance });
354
- continue;
355
- }
356
- }
357
- // Cross-run refs are out of scope for this child — deny before resolve.
358
- if (isNonEmptyStr(cand.artifactRef?.runId) && cand.artifactRef.runId !== effectiveRunId) {
359
- exclude(ref, 'cross_run', { text, provenance });
360
- continue;
361
- }
362
- // Verify the original when a resolver is wired: a missing or
363
- // checksum-changed original is marked invalid, never presented as
364
- // current, and never silently omitted.
365
- if (typeof resolveOriginal === 'function' && isPlainRec(cand.artifactRef)) {
366
- let resolved = null;
367
- try {
368
- resolved = await resolveOriginal(cand.artifactRef);
369
- } catch {
370
- resolved = null;
371
- }
372
- if (resolved == null || resolved.status === 'unavailable') {
373
- const reason = resolved?.reason;
374
- const marked = reason === 'checksum_mismatch' || reason === 'bytes_mismatch'
375
- ? 'stale_original'
376
- : 'original_unavailable';
377
- exclude(ref, marked, { text, provenance, detail: reason ?? 'unresolved' });
378
- continue;
379
- }
380
- }
381
- if (typeof cand.observedAt === 'number') {
382
- const ttl = typeof cand.ttlMs === 'number' ? cand.ttlMs : STALE_MS;
383
- if (nowMs - cand.observedAt > ttl) {
384
- exclude(ref, 'stale', { text, provenance });
385
- continue;
386
- }
387
- }
388
- if (cand.audience != null) {
389
- const aud = Array.isArray(cand.audience) ? cand.audience : [cand.audience];
390
- if (!aud.includes(effectiveRole)) {
391
- exclude(ref, 'audience_mismatch', { text, provenance });
392
- continue;
393
- }
394
- }
395
- // Isolated lanes (SPEC §6 reviewer default) receive requirements / diffs /
396
- // tests / evidence — implementer narrative is out by construction.
397
- if (effectiveMode === 'isolated' && cand.kind === 'narrative' && cand.required !== true) {
398
- exclude(ref, 'isolated_excludes_narrative', { text, provenance });
399
- continue;
400
- }
401
-
402
- const fingerprint = fingerprintOf(ref, text);
403
-
404
- if (cand.required === true) {
405
- pushItem({
406
- ref,
407
- included: true,
408
- reason: 'required',
409
- tokenEstimate,
410
- provenance,
411
- fingerprint,
412
- });
413
- tokensUsed += tokenEstimate;
414
- if (budget != null && tokensUsed > budget) overBudget = true;
415
- seenFingerprints.set(fingerprint, ref);
416
- continue;
417
- }
418
-
419
- // Unknown relevance preserves the item (SPEC §7): the default action is
420
- // include, so ambiguous candidates are carried with provenance intact.
421
- const prior = seenFingerprints.get(fingerprint);
422
- if (prior != null) {
423
- // Exact-duplicate collapse — lineage kept on both sides.
424
- const kept = items.find((i) => i.ref === prior);
425
- const merged = {
426
- ...kept,
427
- sourceRefs: Object.freeze([...(kept.sourceRefs ?? []), ref]),
428
- };
429
- items[items.indexOf(kept)] = Object.freeze(merged);
430
- exclude(ref, 'duplicate', { text, provenance, detail: `of:${prior}` });
431
- continue;
432
- }
433
- if (budget != null && tokensUsed + tokenEstimate > budget) {
434
- exclude(ref, 'over_budget', { text, provenance });
435
- continue;
436
- }
437
- const entry = {
438
- ref,
439
- included: true,
440
- reason: 'relevant',
441
- tokenEstimate,
442
- provenance,
443
- fingerprint,
444
- };
445
- if (cand.memoryRecord != null
446
- && cand.memoryRecord.verified !== true
447
- && cand.memoryRecord.trust_tier !== 'verified') {
448
- entry.label = 'unverified';
449
- }
450
- pushItem(entry);
451
- seenFingerprints.set(fingerprint, ref);
452
- tokensUsed += tokenEstimate;
453
- }
454
-
455
- const contextRefs = Object.freeze(
456
- items.filter((i) => i.included).map((i) => i.ref),
457
- );
458
- const excludedCandidates = Object.freeze(
459
- items.filter((i) => !i.included).map((i) => i.ref),
460
- );
461
-
462
- // Source fingerprint: deterministic over what was fed in — requested mode,
463
- // run binding, and the candidate ref set — so manifests can be compared
464
- // across identical inputs without trusting a regenerated build.
465
- const sourceFingerprint = crypto.createHash('sha256').update(JSON.stringify({
466
- runId: effectiveRunId,
467
- requestedMode,
468
- refs: (candidates ?? []).map((c, i) =>
469
- isNonEmptyStr(c?.ref) ? c.ref : `candidate:${i}`),
470
- })).digest('hex');
471
-
472
- const manifest = {
473
- version: MANIFEST_VERSION,
474
- runId: effectiveRunId,
475
- mode: effectiveMode,
476
- policyVersion: CONTEXT_MANIFEST_POLICY_VERSION,
477
- // No shipped host exposes prompt-assembly control — the manifest is an
478
- // advisory selection, never a claim about the child's actual prompt.
479
- enforcement: 'advisory',
480
- items: Object.freeze(items),
481
- excludedCandidates,
482
- tokensUsed,
483
- overBudget,
484
- sourceFingerprint,
485
- };
486
- if (effectiveMode !== requestedMode) manifest.requestedMode = requestedMode;
487
-
488
- return {
489
- ok: true,
490
- mode: effectiveMode,
491
- manifest: Object.freeze(manifest),
492
- contextRefs,
493
- };
494
- }
495
-
496
- // --- TASK-B3 (PLAN-ENDUR-B §B3): context pack → delegation candidates -------
497
- // Pure mapping from a buildContextPack result (TASK-B2, plain data) into
498
- // candidates for buildSubagentContext. No fs/config/network/LLM access here —
499
- // the pack is supplied by the caller; this module stays I/O-free.
500
- //
501
- // Freshness honesty (documented choice, TASK-B3 Discussion): the pack carries
502
- // no generation timestamp (B2 is clock-free), so "not fresh" is expressed via
503
- // the EXISTING observedAt/ttlMs staleness path of buildSubagentContext —
504
- // no new exclusion machinery, no change to its output shape:
505
- // - fresh pack (stale:false, fallback:null): observedAt = mapping `now`,
506
- // ttlMs = STALE_MS → included while within the default evidence window.
507
- // - degraded pack (stale:true OR fallback set): observedAt = 0, ttlMs = 0 →
508
- // excluded 'stale' by any real downstream clock (nowMs > 0). Candidates are
509
- // still mapped (visible as excluded manifest items), never fresh-labeled.
510
- // Sensitive paths use the shared pure predicate src/index/sensitivePath.js
511
- // (same one contextPack.js uses — no mirrored copy) and map with
512
- // sensitivity:'sensitive' so the existing redaction path excludes them.
513
-
514
- // Deterministic content text over path/reason/outline only. Outline order is
515
- // authoritative from the pack (B2 emits line-sorted outlines).
516
- function packEntryText(entry) {
517
- const lines = [
518
- `path: ${entry.path}`,
519
- `reason: ${isNonEmptyStr(entry.reason) ? entry.reason : 'unknown'}`,
520
- ];
521
- for (const symbol of Array.isArray(entry.outline) ? entry.outline : []) {
522
- if (symbol == null || typeof symbol !== 'object' || !isNonEmptyStr(symbol.name)) {
523
- continue;
524
- }
525
- const type = isNonEmptyStr(symbol.type) ? symbol.type : 'symbol';
526
- const signature = isNonEmptyStr(symbol.signature) ? ` ${symbol.signature}` : '';
527
- lines.push(`symbol: ${symbol.name} (${type})${signature}`);
528
- }
529
- return lines.join('\n');
530
- }
531
-
532
- /**
533
- * Map a buildContextPack result to buildSubagentContext candidates (pure).
534
- *
535
- * @param {object|null} pack buildContextPack result; malformed input maps to [].
536
- * @param {object} [options]
537
- * @param {number} [options.now] Mapping clock; anchors fresh candidates'
538
- * observedAt (default Date.now(), matching module convention).
539
- * @returns {Array<object>} One candidate per pack file: ref `pack:<path>`,
540
- * kind 'evidence', provenance 'context-pack', required:false, deterministic
541
- * content; degraded packs (stale/fallback) carry observedAt:0/ttlMs:0 so the
542
- * existing staleness path excludes them; sensitive paths carry
543
- * sensitivity:'sensitive' for the existing redaction path.
544
- */
545
- export function contextPackToCandidates(pack, { now } = {}) {
546
- const nowMs = typeof now === 'number' && Number.isFinite(now) ? now : Date.now();
547
- const files = pack != null && typeof pack === 'object' && Array.isArray(pack.files)
548
- ? pack.files
549
- : [];
550
- const degraded = pack?.stale === true || pack?.fallback != null;
551
- const observedAt = degraded ? 0 : nowMs;
552
- const ttlMs = degraded ? 0 : STALE_MS;
553
-
554
- const candidates = [];
555
- for (const entry of files) {
556
- if (entry == null || typeof entry !== 'object' || !isNonEmptyStr(entry.path)) {
557
- continue;
558
- }
559
- candidates.push({
560
- ref: `pack:${entry.path}`,
561
- content: packEntryText(entry),
562
- required: false,
563
- kind: 'evidence',
564
- provenance: 'context-pack',
565
- observedAt,
566
- ttlMs,
567
- ...(isSensitivePath(entry.path) ? { sensitivity: 'sensitive' } : {}),
568
- });
569
- }
570
- return candidates;
571
- }
@@ -1,112 +0,0 @@
1
- // Shadow quality-comparison harness (G5 / TASK-004, G5-FR06).
2
- // Pure replay: re-runs recorded evidence inputs through the completion-evidence
3
- // gate and compares against the recorded ledger evaluateCompletion() result.
4
- // No ledger writes, no VM spawns, no model calls — the gate evaluator is
5
- // injected (defaults to a dynamic import of ./completionGate.js so this module
6
- // lands safely when TASK-003 ships in the same wave).
7
- //
8
- // Ledger verdict semantics (template_project/.claude/ukit/runtime/execution-ledger.mjs):
9
- // complete:true → released (all evidence satisfied)
10
- // continue:true → blocked (unfinished work keeps recovering)
11
- // continue:false (loud release, no complete flag) → released
12
- // Gate verdict semantics (SPEC §4):
13
- // PASS → released; MORE_EVIDENCE | FIX_REQUIRED | FAILED → blocked.
14
- // Comparison kinds:
15
- // agree — both released or both blocked
16
- // stricter — ledger released where the gate blocks (counted as
17
- // falsePassBlocks: a ledger release the gate would have held)
18
- // looser — gate released where the ledger blocked
19
- // unverifiable — recorded data insufficient; never guessed.
20
-
21
- export const VERDICT_KINDS = Object.freeze(['agree', 'stricter', 'looser', 'unverifiable']);
22
-
23
- const BLOCKING_VERDICTS = new Set(['MORE_EVIDENCE', 'FIX_REQUIRED', 'FAILED']);
24
-
25
- function gateReleased(verdict) {
26
- return verdict === 'PASS';
27
- }
28
-
29
- // Ledger released = explicit completion OR a loud release without continuation.
30
- // `continue` must be a boolean; `complete` is optional.
31
- function ledgerVerdict(ledger) {
32
- if (ledger == null || typeof ledger !== 'object') return null;
33
- if (typeof ledger.continue !== 'boolean') return null;
34
- const released = ledger.complete === true || ledger.continue === false;
35
- return { complete: ledger.complete === true, continue: ledger.continue, released };
36
- }
37
-
38
- async function defaultEvaluator(evidence) {
39
- const mod = await import('./completionGate.js');
40
- return mod.evaluateCompletionEvidence(evidence);
41
- }
42
-
43
- function freezeRow(row) {
44
- return Object.freeze({ ...row, ledger: Object.freeze({ ...row.ledger }) });
45
- }
46
-
47
- export async function runQualityShadow({ fixtures, evaluator } = {}) {
48
- const evaluate = typeof evaluator === 'function' ? evaluator : defaultEvaluator;
49
- const list = Array.isArray(fixtures) ? fixtures : [];
50
-
51
- const rows = [];
52
- const summary = { total: 0, agreements: 0, disagreements: 0, falsePassBlocks: 0, unverifiable: 0 };
53
-
54
- for (const fx of list) {
55
- const id = fx && fx.id != null ? String(fx.id) : `fixture-${rows.length}`;
56
- const ledgerV = ledgerVerdict(fx && fx.ledger);
57
- const evidence = fx && fx.evidence;
58
-
59
- let verdict = null;
60
- let evalOk = evidence != null;
61
- if (evalOk) {
62
- try {
63
- const result = await evaluate(evidence);
64
- verdict = result && typeof result.verdict === 'string' ? result.verdict : null;
65
- evalOk = verdict === 'PASS' || BLOCKING_VERDICTS.has(verdict);
66
- } catch {
67
- evalOk = false;
68
- }
69
- }
70
-
71
- let row;
72
- if (!evalOk || ledgerV === null) {
73
- row = freezeRow({
74
- id,
75
- gate: 'unverifiable',
76
- ledger: { complete: ledgerV ? ledgerV.complete : false, continue: ledgerV ? ledgerV.continue : false },
77
- agreement: false,
78
- kind: 'unverifiable',
79
- });
80
- summary.unverifiable += 1;
81
- } else {
82
- const released = gateReleased(verdict);
83
- let kind;
84
- let agreement;
85
- if (released === ledgerV.released) {
86
- kind = 'agree';
87
- agreement = true;
88
- } else {
89
- kind = ledgerV.released ? 'stricter' : 'looser';
90
- agreement = false;
91
- }
92
- row = freezeRow({
93
- id,
94
- gate: verdict,
95
- ledger: { complete: ledgerV.complete, continue: ledgerV.continue },
96
- agreement,
97
- kind,
98
- });
99
- if (agreement) {
100
- summary.agreements += 1;
101
- } else {
102
- summary.disagreements += 1;
103
- if (kind === 'stricter') summary.falsePassBlocks += 1;
104
- }
105
- }
106
-
107
- rows.push(row);
108
- summary.total += 1;
109
- }
110
-
111
- return { rows: Object.freeze(rows), summary: Object.freeze(summary) };
112
- }