@ngockhoale/ukit 3.5.1 → 3.5.3

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 (39) hide show
  1. package/CHANGELOG.md +35 -297
  2. package/README.md +1 -0
  3. package/manifests/platform.full.yaml +23 -0
  4. package/package.json +8 -1
  5. package/src/cli/commands/doctor.js +14 -2
  6. package/src/cli/commands/memory.js +30 -2
  7. package/src/core/memory/memoryHit.js +2 -0
  8. package/src/core/memory/mutateMemory.js +9 -0
  9. package/src/core/memory/projectIdentity.js +9 -2
  10. package/src/core/memory/recallEngine.js +86 -4
  11. package/src/core/memory/registryPrune.js +230 -0
  12. package/src/core/memory/retrieval.js +12 -3
  13. package/src/core/runtimeConfig.js +1 -0
  14. package/src/index/buildIndex.js +22 -0
  15. package/src/index/impactContext.js +11 -1
  16. package/src/index/queryIndex.js +151 -20
  17. package/template_project/.claude/hooks/edit-hint.mjs +119 -0
  18. package/template_project/.claude/settings.json +2 -2
  19. package/template_project/.claude/ukit/index/edit-graph.mjs +404 -0
  20. package/template_project/.claude/ukit/index/lib/index-core.mjs +185 -20
  21. package/template_project/.claude/ukit/index/post-edit-verify.mjs +8 -5
  22. package/template_project/.claude/ukit/index/resolve-context.mjs +17 -0
  23. package/template_project/.claude/ukit/index/route-task.mjs +4 -1
  24. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +62 -5
  25. package/template_project/.claude/ukit/runtime/memory-lanes.mjs +259 -0
  26. package/template_project/.claude/ukit/runtime/memory-recall.mjs +86 -4
  27. package/template_project/.claude/ukit/runtime/memory-validity.mjs +232 -0
  28. package/template_project/.claude/ukit/runtime/reinject-context.mjs +4 -2
  29. package/template_project/.omp/hooks/pre/ukit-bridge.js +2 -1
  30. package/template_project/AGENTS.md +1 -1
  31. package/template_project/CLAUDE.md +1 -1
  32. package/template_project/instructions/core.md +1 -1
  33. package/src/core/observability/evaluation/experimentPlan.js +0 -95
  34. package/src/core/observability/evaluation/perturbation.js +0 -273
  35. package/src/diagnostics/classifyHang.js +0 -246
  36. package/src/diagnostics/ompStallSnapshot.js +0 -199
  37. package/src/render/instructionRenderer.js +0 -290
  38. package/src/skill/auditSkill.js +0 -140
  39. package/template_project/instructions/overlays/repo.md +0 -9
@@ -4,6 +4,12 @@ import crypto from 'node:crypto';
4
4
  import { execFile, spawnSync } from 'node:child_process';
5
5
  import { withFileLock } from '../../runtime/token-utils.mjs';
6
6
  import { withAsyncLock } from '../../runtime/async-lock.mjs';
7
+ // edit-graph.mjs is optional: a partial install must not lose the whole index core.
8
+ let editGraphModule;
9
+ function loadEditGraphModule() {
10
+ editGraphModule ??= import('../edit-graph.mjs').catch(() => null);
11
+ return editGraphModule;
12
+ }
7
13
 
8
14
  // One wall-clock ceiling for the WHOLE discovery phase: both `git ls-files`
9
15
  // enumerations AND the non-git fallback walk share this single budget. Every
@@ -599,6 +605,7 @@ async function buildCodeIndexInner({ rootDir = process.cwd(), changedFiles = nul
599
605
  [INDEX_ARTIFACTS.relations]: relations.length,
600
606
  },
601
607
  });
608
+ await refreshEditGraph(absoluteRoot, sourceFingerprint.digest, fileRecords, codeFiles, imports, importAliasContext, signal);
602
609
 
603
610
  return {
604
611
  indexDir,
@@ -1192,6 +1199,7 @@ async function tryIncrementalIndexUpdate({ absoluteRoot, indexDir, changedPaths,
1192
1199
  clearIndexArtifactCache(absoluteRoot);
1193
1200
  RELATED_TEST_LOOKUP_CACHE.delete(absoluteRoot);
1194
1201
  }
1202
+ await refreshEditGraph(absoluteRoot, refreshedFingerprint.digest, mergedFileRecords, codeFiles, imports, importAliasContext, signal);
1195
1203
 
1196
1204
  return {
1197
1205
  indexDir,
@@ -1293,7 +1301,7 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
1293
1301
  return QUERY_RESULT_CACHE.get(queryCacheKey);
1294
1302
  }
1295
1303
  const queryPromise = (async () => {
1296
- const { files, searchDescriptorsByFile } = await loadQuerySearchBundle(absoluteRoot);
1304
+ const { files, searchDescriptorsByFile, tokenWeights } = await loadQuerySearchBundle(absoluteRoot);
1297
1305
  const preferredArchetypes = inferPreferredArchetypes(queryDescriptor.tokens);
1298
1306
  const includeLikelyTestFiles = shouldIncludeLikelyTestFiles(queryDescriptor);
1299
1307
 
@@ -1304,8 +1312,10 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
1304
1312
  const searchDescriptor = searchDescriptorsByFile.get(filePath) ?? createFileSearchDescriptor({ filePath, symbols: [] });
1305
1313
  const { score, reasons } = scoreDirectFileMatch({
1306
1314
  queryDescriptor,
1315
+ rawQuery: normalizedQuery,
1307
1316
  filePath,
1308
1317
  searchDescriptor,
1318
+ tokenWeights,
1309
1319
  });
1310
1320
 
1311
1321
  if (score > 0) {
@@ -1347,9 +1357,12 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
1347
1357
  importersByTarget,
1348
1358
  testsMapBySource: testsBySource,
1349
1359
  });
1350
- const boosted = applyHotspotBoosts({ scores: relatedScores, hotspotScores });
1360
+ const boosted = capBoostLift({
1361
+ directScores,
1362
+ scores: applyHotspotBoosts({ scores: relatedScores, hotspotScores }),
1363
+ });
1351
1364
  return freezeQueryResults(
1352
- [...boosted.values()].sort((a, b) => b.score - a.score || a.filePath.localeCompare(b.filePath)).slice(0, limit),
1365
+ [...boosted.values()].map((entry) => ({ ...entry, score: finalizeScore(entry) })).sort((a, b) => b.score - a.score || a.filePath.localeCompare(b.filePath)).slice(0, limit),
1353
1366
  );
1354
1367
  })().catch((error) => {
1355
1368
  QUERY_RESULT_CACHE.delete(queryCacheKey);
@@ -3236,6 +3249,23 @@ function areBugIndexSnapshotsEqual(previousSnapshot, nextSnapshot) {
3236
3249
  && previousSnapshot.size === nextSnapshot.size;
3237
3250
  }
3238
3251
 
3252
+ // Edit graph (mirror/test/import edges): rebuilt only when missing or its digest
3253
+ // differs from the index fingerprint. Never fails the index build.
3254
+ async function refreshEditGraph(rootDir, indexDigest, fileRecords, codeFiles, imports, aliasContext, signal) {
3255
+ const graphModule = await loadEditGraphModule();
3256
+ if (!graphModule) return;
3257
+ await graphModule.ensureEditGraph({
3258
+ rootDir,
3259
+ indexDigest,
3260
+ signal,
3261
+ inputs: () => ({
3262
+ files: fileRecords,
3263
+ imports: buildResolvedImportMap(rootDir, imports, new Set(codeFiles.map((f) => f.filePath)), aliasContext),
3264
+ declaredMirrors: IMPACT_MIRROR_PAIRS,
3265
+ }),
3266
+ });
3267
+ }
3268
+
3239
3269
  async function writeArtifact(rootDir, artifactName, payload) {
3240
3270
  const artifactPath = getArtifactPath(rootDir, artifactName);
3241
3271
  const temporaryPath = `${artifactPath}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -3290,9 +3320,11 @@ async function loadQuerySearchBundle(rootDir) {
3290
3320
  const safeFiles = safeSchemaArtifact(files);
3291
3321
  const safeSymbols = safeSchemaArtifact(symbols);
3292
3322
  const symbolMap = groupBy(safeItems(safeSymbols), (item) => item.filePath);
3323
+ const searchDescriptorsByFile = buildFileSearchDescriptors(safeItems(safeFiles), symbolMap);
3293
3324
  return {
3294
3325
  files: safeFiles,
3295
- searchDescriptorsByFile: buildFileSearchDescriptors(safeItems(safeFiles), symbolMap),
3326
+ searchDescriptorsByFile,
3327
+ tokenWeights: buildTokenWeights(searchDescriptorsByFile),
3296
3328
  };
3297
3329
  })
3298
3330
  .catch((error) => {
@@ -3368,9 +3400,91 @@ function tokenize(query) {
3368
3400
  return tokenizeFoldedText(foldTextForSearch(addCamelBoundaries(query)));
3369
3401
  }
3370
3402
 
3371
- function scoreDirectFileMatch({ queryDescriptor, filePath, searchDescriptor }) {
3403
+ // ── Ranking constants (kept identical in src/index/queryIndex.js) ──
3404
+ const PATH_EXACT_SCORE = 60;
3405
+ const PATH_SUFFIX_SCORE = 48;
3406
+ const PATH_BASENAME_SCORE = 40;
3407
+ const SYMBOL_EXACT_SCORE = 40;
3408
+ const SYMBOL_DECAY = 0.35; // k-th best symbol of a file adds score * SYMBOL_DECAY^k
3409
+ const SYMBOL_REASON_LIMIT = 3;
3410
+ const MIN_SUBSTRING_TOKEN_LENGTH = 3;
3411
+ const BOOST_LIFT_RATIO = 0.2; // import/hotspot/archetype boosts may add at most this share of a direct score (+1)
3412
+ const BOOST_ONLY_RATIO = 0.3; // files with no direct match stay below this share of the best direct score
3413
+
3414
+ // Rarity weight per token in (0,1]: a token present in nearly every file is worth
3415
+ // ~ln2/ln(1+N), a token unique to one file is worth 1. Computed once per bundle.
3416
+ function buildTokenWeights(searchDescriptorsByFile) {
3417
+ const docFrequency = new Map();
3418
+ for (const descriptor of searchDescriptorsByFile.values()) {
3419
+ const seen = new Set(descriptor.path.tokens);
3420
+ for (const symbol of descriptor.symbols) {
3421
+ for (const token of symbol.descriptor.tokens) {
3422
+ seen.add(token);
3423
+ }
3424
+ }
3425
+ for (const token of seen) {
3426
+ docFrequency.set(token, (docFrequency.get(token) ?? 0) + 1);
3427
+ }
3428
+ }
3429
+ const total = searchDescriptorsByFile.size;
3430
+ const denominator = Math.log(1 + total) || 1;
3431
+ const weights = new Map();
3432
+ for (const [token, count] of docFrequency) {
3433
+ weights.set(token, Math.max(0.05, Math.log(1 + total / count) / denominator));
3434
+ }
3435
+ return weights;
3436
+ }
3437
+
3438
+ // Prior applied after scoring so an original beats its mirror copy on ties without
3439
+ // hiding the mirror: root installed copies < template_project < everything else.
3440
+ function mirrorPrior(filePath) {
3441
+ if (/^\.(?:claude|codex|omp)\//.test(filePath)) {
3442
+ return 0.88;
3443
+ }
3444
+ if (filePath.startsWith('template_project/')) {
3445
+ return 0.94;
3446
+ }
3447
+ return 1;
3448
+ }
3449
+
3450
+ function normalizePathQuery(rawQuery) {
3451
+ const value = String(rawQuery ?? '').trim().toLowerCase().replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
3452
+ return value.length >= 3 && !/\s/.test(value) ? value : '';
3453
+ }
3454
+
3455
+ // Exact path / path-suffix (whole segments) / basename match for single-term queries.
3456
+ function scorePathQuery(pathQuery, filePath) {
3457
+ if (!pathQuery) {
3458
+ return null;
3459
+ }
3460
+ const lower = filePath.toLowerCase();
3461
+ const noExt = lower.replace(/\.[a-z0-9]+$/, '');
3462
+ if (pathQuery === lower) {
3463
+ return { score: PATH_EXACT_SCORE, reason: `path_exact:${filePath}` };
3464
+ }
3465
+ if (pathQuery.includes('/')) {
3466
+ if (noExt === pathQuery || lower.endsWith(`/${pathQuery}`) || noExt.endsWith(`/${pathQuery}`)) {
3467
+ return { score: PATH_SUFFIX_SCORE, reason: `path_suffix:${pathQuery}` };
3468
+ }
3469
+ return null;
3470
+ }
3471
+ const base = lower.slice(lower.lastIndexOf('/') + 1);
3472
+ if (pathQuery === base || pathQuery === base.replace(/\.[a-z0-9]+$/, '')) {
3473
+ return { score: PATH_BASENAME_SCORE, reason: `path_basename:${pathQuery}` };
3474
+ }
3475
+ return null;
3476
+ }
3477
+
3478
+ function scoreDirectFileMatch({ queryDescriptor, rawQuery = '', filePath, searchDescriptor, tokenWeights = null }) {
3372
3479
  let score = 0;
3373
3480
  const reasons = [];
3481
+ const weightOf = (token) => tokenWeights?.get(token) ?? 1;
3482
+
3483
+ const pathHit = scorePathQuery(normalizePathQuery(rawQuery), filePath);
3484
+ if (pathHit) {
3485
+ score += pathHit.score;
3486
+ reasons.push(pathHit.reason);
3487
+ }
3374
3488
 
3375
3489
  if (
3376
3490
  queryDescriptor.compact.length >= 6
@@ -3382,43 +3496,45 @@ function scoreDirectFileMatch({ queryDescriptor, filePath, searchDescriptor }) {
3382
3496
 
3383
3497
  for (const token of queryDescriptor.tokens) {
3384
3498
  if (searchDescriptor.path.tokens.has(token)) {
3385
- score += 3;
3499
+ score += 3 * weightOf(token);
3386
3500
  reasons.push(`path_token:${token}`);
3387
- } else if (searchDescriptor.path.rawLower.includes(token)) {
3388
- score += 1;
3501
+ } else if (token.length >= MIN_SUBSTRING_TOKEN_LENGTH && searchDescriptor.path.rawLower.includes(token)) {
3502
+ score += weightOf(token);
3389
3503
  reasons.push(`path_contains:${token}`);
3390
3504
  }
3391
3505
  }
3392
3506
 
3507
+ const symbolHits = [];
3393
3508
  for (const symbolDescriptor of searchDescriptor.symbols) {
3394
3509
  if (
3395
3510
  queryDescriptor.compact.length >= 4
3396
3511
  && symbolDescriptor.descriptor.compact === queryDescriptor.compact
3397
3512
  ) {
3398
- score += 8;
3399
- reasons.push(`symbol_exact:${symbolDescriptor.name}`);
3513
+ symbolHits.push({ score: SYMBOL_EXACT_SCORE, reasons: [`symbol_exact:${symbolDescriptor.name}`] });
3400
3514
  continue;
3401
3515
  }
3402
3516
 
3517
+ let symbolScore = 0;
3518
+ const symbolReasons = [];
3403
3519
  if (
3404
3520
  queryDescriptor.compact.length >= 6
3405
3521
  && symbolDescriptor.descriptor.compact.includes(queryDescriptor.compact)
3406
3522
  ) {
3407
- score += 5;
3408
- reasons.push(`symbol_compact:${symbolDescriptor.name}`);
3523
+ symbolScore += 5;
3524
+ symbolReasons.push(`symbol_compact:${symbolDescriptor.name}`);
3409
3525
  }
3410
3526
 
3411
3527
  let symbolContributed = false;
3412
3528
 
3413
3529
  for (const token of queryDescriptor.tokens) {
3414
3530
  if (symbolDescriptor.descriptor.tokens.has(token)) {
3415
- score += 3;
3531
+ symbolScore += 3 * weightOf(token);
3416
3532
  symbolContributed = true;
3417
- reasons.push(`symbol_token:${symbolDescriptor.name}:${token}`);
3418
- } else if (symbolDescriptor.descriptor.rawLower.includes(token)) {
3419
- score += 1;
3533
+ symbolReasons.push(`symbol_token:${symbolDescriptor.name}:${token}`);
3534
+ } else if (token.length >= MIN_SUBSTRING_TOKEN_LENGTH && symbolDescriptor.descriptor.rawLower.includes(token)) {
3535
+ symbolScore += weightOf(token);
3420
3536
  symbolContributed = true;
3421
- reasons.push(`symbol_contains:${symbolDescriptor.name}`);
3537
+ symbolReasons.push(`symbol_contains:${symbolDescriptor.name}`);
3422
3538
  }
3423
3539
  }
3424
3540
 
@@ -3428,15 +3544,54 @@ function scoreDirectFileMatch({ queryDescriptor, filePath, searchDescriptor }) {
3428
3544
  // from the stronger tiers above.
3429
3545
  if (!symbolContributed && queryDescriptor.compact.length >= 6) {
3430
3546
  if (symbolFuzzyMatches(queryDescriptor.compact, symbolDescriptor.descriptor.compact)) {
3431
- score += 3;
3432
- reasons.push(`symbol_fuzzy:${symbolDescriptor.name}`);
3547
+ symbolScore += 3;
3548
+ symbolReasons.push(`symbol_fuzzy:${symbolDescriptor.name}`);
3433
3549
  }
3434
3550
  }
3551
+
3552
+ if (symbolScore > 0) {
3553
+ symbolHits.push({ score: symbolScore, reasons: symbolReasons });
3554
+ }
3435
3555
  }
3436
3556
 
3557
+ // Best symbol dominates; further symbols add with sharp diminishing returns so
3558
+ // file size (symbol count) cannot outvote match quality.
3559
+ symbolHits.sort((a, b) => b.score - a.score);
3560
+ let decay = 1;
3561
+ symbolHits.forEach((hit, index) => {
3562
+ score += hit.score * decay;
3563
+ decay *= SYMBOL_DECAY;
3564
+ if (index < SYMBOL_REASON_LIMIT) {
3565
+ reasons.push(...hit.reasons);
3566
+ }
3567
+ });
3568
+
3437
3569
  return { score, reasons: [...new Set(reasons)], filePath };
3438
3570
  }
3439
3571
 
3572
+ // Import-graph, hotspot and archetype boosts are context, not evidence: they may
3573
+ // reorder near-equal direct matches but never lift a weak match over a strong one,
3574
+ // and files with no direct match stay below the best direct match.
3575
+ function capBoostLift({ directScores, scores }) {
3576
+ let maxDirect = 0;
3577
+ for (const entry of directScores.values()) {
3578
+ maxDirect = Math.max(maxDirect, entry.score);
3579
+ }
3580
+ for (const [filePath, entry] of scores) {
3581
+ const base = directScores.get(filePath)?.score;
3582
+ if (base === undefined) {
3583
+ entry.score = Math.min(entry.score, BOOST_ONLY_RATIO * maxDirect);
3584
+ } else {
3585
+ entry.score = base + Math.min(Math.max(entry.score - base, 0), BOOST_LIFT_RATIO * base + 1);
3586
+ }
3587
+ }
3588
+ return scores;
3589
+ }
3590
+
3591
+ function finalizeScore(entry) {
3592
+ return Number((entry.score * mirrorPrior(entry.filePath)).toFixed(2));
3593
+ }
3594
+
3440
3595
  // Fuzzy predicate shared by scoreDirectFileMatch and resolveSymbolCandidates:
3441
3596
  // ordered containment (either direction, on tokens or compacts) or a bounded
3442
3597
  // Damerau distance. Cheap length gates run first so the common non-fuzzy case
@@ -5217,7 +5372,17 @@ export async function resolveImpactContext({
5217
5372
  const callItems = safeItems(callsArtifact);
5218
5373
  const importItems = safeItems(importsArtifact);
5219
5374
  const risk = classifyImpactRisk(normalizedChangedFiles);
5220
- const mirrorCounterparts = findMirrorCounterparts(normalizedChangedFiles).slice(0, budget.maxMirrors);
5375
+ const graphModule = await loadEditGraphModule();
5376
+ const editGraph = graphModule ? await graphModule.loadEditGraph(absoluteRoot) : null;
5377
+ const mirrorCounterparts = [...findMirrorCounterparts(normalizedChangedFiles)];
5378
+ for (const changed of normalizedChangedFiles) {
5379
+ for (const mirror of graphModule?.neighboursOf(editGraph, changed).mirrors ?? []) {
5380
+ if (!mirrorCounterparts.some((m) => m.filePath === mirror.path && m.source === changed)) {
5381
+ mirrorCounterparts.push({ filePath: mirror.path, reason: `edit-graph ${mirror.kind} mirror`, source: changed });
5382
+ }
5383
+ }
5384
+ }
5385
+ mirrorCounterparts.splice(budget.maxMirrors);
5221
5386
  const changedFileSet = new Set(normalizedChangedFiles);
5222
5387
  const changedSymbolSet = new Set(normalizedChangedSymbols);
5223
5388
  const changedRecords = callItems.filter((item) => {
@@ -239,14 +239,17 @@ async function main() {
239
239
  }
240
240
  const projectRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
241
241
  const runtimeConfig = await readRuntimeSafePatchConfig(projectRoot);
242
- const result = await verifyPostEdit({
243
- projectRoot,
244
- payload: parseJsonInput(await readStdin(), {}),
245
- });
242
+ const payload = parseJsonInput(await readStdin(), {});
243
+ const result = await verifyPostEdit({ projectRoot, payload });
246
244
  if (json) {
247
245
  process.stdout.write(`${JSON.stringify(result)}\n`);
248
246
  } else if (result.status === 'ok') {
249
- process.stdout.write(`[ukit-safe-patch] ${result.message}\n`);
247
+ // A plain-text line would make the chain's merged stdout invalid JSON and Claude Code
248
+ // would drop a later step's additionalContext (edit-hint). omp's bridge appends step
249
+ // stdout verbatim to the tool result, so omp keeps the plain line.
250
+ const line = `[ukit-safe-patch] ${result.message}`;
251
+ if (payload?.ukit_harness === 'omp' || process.env.UKIT_HARNESS === 'omp') process.stdout.write(`${line}\n`);
252
+ else emitSystemMessage(line);
250
253
  } else if (result.status === 'advisory') {
251
254
  process.stderr.write(`[ukit-safe-patch] ${result.message}\n`);
252
255
  process.stderr.write('[ukit-safe-patch] handoff authoring advisory — change is already written; continue updating docs/AI_HANDOFF/.\n');
@@ -62,6 +62,7 @@ if (!intent && !targetFile) {
62
62
  }
63
63
 
64
64
  await printContextResult(result, { rootDir, showOutline });
65
+ if (targetFile) await printEditHint({ rootDir, targetFile, intent });
65
66
  }
66
67
 
67
68
  catch (error) {
@@ -69,6 +70,22 @@ catch (error) {
69
70
  process.exit(1);
70
71
  }
71
72
 
73
+ // Computed after (never inside) the result cache so memory edits are never stale.
74
+ async function printEditHint({ rootDir, targetFile, intent }) {
75
+ try {
76
+ const { editHintFor } = await import('../runtime/memory-lanes.mjs');
77
+ let target = targetFile;
78
+ if (path.isAbsolute(target)) {
79
+ target = path.relative(path.resolve(rootDir), target).split(path.sep).join('/');
80
+ if (!target || target.startsWith('..') || path.isAbsolute(target)) return; // outside the project: silent
81
+ }
82
+ const hint = await editHintFor({ projectRoot: rootDir, target, query: intent, capture: true });
83
+ if (hint.text) console.log(hint.text);
84
+ } catch {
85
+ // Hints are advisory; never fail the helper.
86
+ }
87
+ }
88
+
72
89
  async function ensureFreshIndex({ rootDir, logPrefix }) {
73
90
  if (typeof indexCore.ensureIndexFresh === 'function') {
74
91
  return indexCore.ensureIndexFresh({ rootDir, logPrefix });
@@ -39,6 +39,7 @@ import {
39
39
  import { resolveRecordFreshness } from '../runtime/memory-freshness.mjs';
40
40
  import { resolveMemoryStage } from '../runtime/memory-flags.mjs';
41
41
  import { recallForHook, renderMarkdownDoc } from '../runtime/memory-recall.mjs';
42
+ import { withValidity, staleSuffix } from '../runtime/memory-validity.mjs';
42
43
  import {
43
44
  ROUTE_VERSION,
44
45
  ROUTE_CONTRACT_VERSION,
@@ -7272,7 +7273,9 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7272
7273
  });
7273
7274
  const recalled = await recallForHook({
7274
7275
  projectRoot: rootDir, query: taskQuery, docs, config: memoryConfig, limit: 2,
7276
+ annotate: (pool) => withValidity(rootDir, pool),
7275
7277
  });
7278
+ const validityById = new Map(recalled.ranked.map((entry) => [entry.doc.id, entry.doc]));
7276
7279
  const rankedItems = recalled.ranked.map((entry) => (entry.doc.type === 'markdown'
7277
7280
  ? { id: entry.doc.id, type: 'markdown', doc: entry.doc }
7278
7281
  : itemById.get(entry.doc.id))).filter(Boolean);
@@ -7294,7 +7297,7 @@ async function buildPreviousContextSnapshot({ rootDir = process.cwd(), routingCo
7294
7297
  return {
7295
7298
  line: rankedItems.map((item) => (item.type === 'markdown'
7296
7299
  ? renderMarkdownDoc(item.doc, 120)
7297
- : buildPreviousContextSnippet(item, freshnessById.get(item.id)))).join(' | '),
7300
+ : `${buildPreviousContextSnippet(item, freshnessById.get(item.id))}${staleSuffix(validityById.get(item.id))}`)).join(' | '),
7298
7301
  selectedIds: rankedItems.map((item) => item.id),
7299
7302
  fingerprint: buildCompactMachineKey('route-memory-v2', {
7300
7303
  taskQuery: normalize(taskQuery),
@@ -170,8 +170,29 @@ function splitTopLevelJsonObjects(text) {
170
170
 
171
171
  function coalesceJsonStdout(text) {
172
172
  if (typeof text !== 'string' || text.length === 0) return text;
173
- const docs = splitTopLevelJsonObjects(text);
174
- if (!docs || docs.length < 2) return text;
173
+ const split = splitTopLevelJsonObjects(text);
174
+ // Mixed stream: single-line JSON documents plus plain text lines. Only when every
175
+ // JSON line is PostToolUse context-only (and at least one exists) is the text folded
176
+ // into the document's additionalContext; anything else (deny + log line) stays byte-exact.
177
+ let plain = [];
178
+ let docs = split;
179
+ if (!split) {
180
+ docs = [];
181
+ for (const line of text.split('\n')) {
182
+ if (!line.trim()) continue;
183
+ let obj = null;
184
+ if (line.trimStart().startsWith('{')) { try { obj = JSON.parse(line); } catch { obj = null; } }
185
+ if (obj && typeof obj === 'object' && !Array.isArray(obj)) docs.push(obj); else plain.push(line.trim());
186
+ }
187
+ // A pretty-printed JSON fragment is not a log line: leave the stream untouched.
188
+ // Bracketed log prefixes such as "[ukit-safe-patch] OK" stay plain text.
189
+ if (plain.some((l) => /^[{}[\]],?$/.test(l) || l.startsWith('{') || /^"[^"]*"\s*(:|,?$)/.test(l))) return text;
190
+ const verdictFree = (d) => !('decision' in d) && d.continue !== false && !('stopReason' in d)
191
+ && (!d.hookSpecificOutput || (d.hookSpecificOutput.hookEventName === 'PostToolUse'
192
+ && !('permissionDecision' in d.hookSpecificOutput) && !('decision' in d.hookSpecificOutput)));
193
+ if (!plain.length || !docs.some((d) => d.hookSpecificOutput) || !docs.every(verdictFree)) return text;
194
+ }
195
+ if (!docs || (docs.length < 2 && !plain.length)) return text;
175
196
  const merged = {};
176
197
  const messages = [];
177
198
  for (const d of docs) {
@@ -180,12 +201,25 @@ function coalesceJsonStdout(text) {
180
201
  if (typeof value === 'string' && value) messages.push(value);
181
202
  continue;
182
203
  }
204
+ if (key === 'hookSpecificOutput' && value && typeof value === 'object' && merged.hookSpecificOutput
205
+ && typeof merged.hookSpecificOutput === 'object') {
206
+ // Two steps may each carry context: join with a newline, never let the later win.
207
+ const prev = merged.hookSpecificOutput;
208
+ const joined = [prev.additionalContext, value.additionalContext].filter((t) => typeof t === 'string' && t);
209
+ merged.hookSpecificOutput = { ...prev, ...value, ...(joined.length ? { additionalContext: joined.join('\n') } : {}) };
210
+ continue;
211
+ }
183
212
  if (key === 'continue' && merged.continue === false) continue;
184
213
  if (key === 'decision' && merged.decision === 'block') continue;
185
214
  if (key === 'reason' && merged.decision === 'block' && d.decision !== 'block') continue;
186
215
  merged[key] = value;
187
216
  }
188
217
  }
218
+ if (plain.length) {
219
+ // Plain lines are trimmed and placed before the documents' context (original order/indentation not preserved).
220
+ const h = merged.hookSpecificOutput;
221
+ h.additionalContext = [...plain, h.additionalContext].filter((t) => typeof t === 'string' && t).join('\n');
222
+ }
189
223
  if (messages.length) merged.systemMessage = messages.join('\n');
190
224
  return `${JSON.stringify(merged)}\n`;
191
225
  }
@@ -195,13 +229,37 @@ function coalesceJsonStdout(text) {
195
229
  // enough — a child killed mid-write can carry the marker in a truncated
196
230
  // capture, and calling that a decision would exempt a genuinely-skipped gate
197
231
  // from the fail-closed verdict. A real decision is a clean exit-0 verdict.
232
+ // WP-C: behaviour is exactly as at HEAD (any clean marker-carrying entry owns
233
+ // stdout) except for ONE shape: stdout whose every document parses and is a
234
+ // PostToolUse context-only `hookSpecificOutput` (additionalContext, no
235
+ // permissionDecision/decision). That is advisory context, not a verdict, and
236
+ // must merge with other steps' output instead of ending the chain.
237
+ function isPostToolUseContextOnly(stdout) {
238
+ const docs = typeof stdout === 'string' ? splitTopLevelJsonObjects(stdout) : null;
239
+ return Boolean(docs) && docs.length > 0 && docs.every((d) => {
240
+ const h = d?.hookSpecificOutput;
241
+ return h && typeof h === 'object' && h.hookEventName === 'PostToolUse'
242
+ && !('permissionDecision' in h) && !('decision' in h)
243
+ && !('decision' in d) && d.continue !== false && !('stopReason' in d);
244
+ });
245
+ }
246
+
198
247
  function emitsPermissionDecision(entry) {
199
248
  return Boolean(entry)
200
249
  && !entry.killed
201
250
  && entry.code === 0
202
251
  && entry.failureKind === 'ok'
203
252
  && typeof entry.stdout === 'string'
204
- && entry.stdout.includes('"hookSpecificOutput"');
253
+ && entry.stdout.includes('"hookSpecificOutput"')
254
+ && !isPostToolUseContextOnly(entry.stdout);
255
+ }
256
+
257
+ // Emit-time owner lookup: HEAD's loose marker lookup, skipping only a CLEAN
258
+ // PostToolUse context-only entry; unclean marker-carrying entries stay candidates.
259
+ function isDecisionOwnerCandidate(r) {
260
+ if (!r || typeof r.stdout !== 'string' || !r.stdout.includes('"hookSpecificOutput"')) return false;
261
+ const clean = !r.killed && r.code === 0 && r.failureKind === 'ok';
262
+ return !(clean && isPostToolUseContextOnly(r.stdout));
205
263
  }
206
264
 
207
265
  function recordTiming(projectRoot, payload, timing) {
@@ -786,8 +844,7 @@ try {
786
844
  // non-zero decision emitter stays routed through the code-2/fail-closed
787
845
  // paths below, per SPEC §FR-001); the strict predicate decides whether that
788
846
  // entry may claim stdout outright.
789
- const decisionResult = chain.results.find((r) =>
790
- typeof r.stdout === 'string' && r.stdout.includes('"hookSpecificOutput"'));
847
+ const decisionResult = chain.results.find(isDecisionOwnerCandidate);
791
848
  const decisionOwnsVerdict = emitsPermissionDecision(decisionResult);
792
849
  const last = decisionResult ?? chain.results[chain.results.length - 1];
793
850