@ngockhoale/ukit 3.5.5 → 3.5.6

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 (53) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/manifests/engineConformance.yaml +0 -13
  3. package/manifests/platform.full.yaml +25 -0
  4. package/package.json +1 -8
  5. package/src/cli/commands/indexTools.js +1 -0
  6. package/src/cli/commands/memory.js +33 -4
  7. package/src/core/applyPlan.js +25 -72
  8. package/src/core/diffPlan.js +38 -9
  9. package/src/core/managedTemplateMerge.js +146 -0
  10. package/src/core/memory/memoryFlags.js +5 -6
  11. package/src/core/memory/policy.js +5 -0
  12. package/src/core/memory/store.js +17 -0
  13. package/src/core/metadata.js +12 -8
  14. package/src/core/runInstallPipeline.js +16 -10
  15. package/src/core/runtimeConfig.js +14 -83
  16. package/src/core/uninstall.js +8 -1
  17. package/src/decision/registry.js +17 -17
  18. package/src/decision/runtimeDecide.js +5 -5
  19. package/src/index/queryIndex.js +41 -4
  20. package/src/index/routeResolver.js +2 -2
  21. package/src/index/semanticLane.js +269 -0
  22. package/src/learning/lessonClass.js +110 -0
  23. package/src/learning/patternProposals.js +111 -7
  24. package/src/learning/reeditMiner.js +104 -0
  25. package/src/learning/selfImprove.js +9 -1
  26. package/template_project/.claude/skills/canvas-design/SKILL.md +2 -2
  27. package/template_project/.claude/skills/canvas-design/canvas-fonts/{InstrumentSans-OFL.txt → InstrumentSerif-OFL.txt} +3 -3
  28. package/template_project/.claude/skills/canvas-design/scripts/fetch-fonts.mjs +148 -0
  29. package/template_project/.claude/ukit/index/embed-index.mjs +26 -0
  30. package/template_project/.claude/ukit/index/lib/index-core.mjs +43 -4
  31. package/template_project/.claude/ukit/index/lib/semantic-lane.mjs +269 -0
  32. package/template_project/.claude/ukit/index/query-index.mjs +9 -1
  33. package/template_project/.claude/ukit/index/route-resolver.mjs +2 -2
  34. package/template_project/.claude/ukit/runtime/memory-policy.mjs +5 -0
  35. package/template_project/ukit/storage/config.json +0 -32
  36. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf +0 -0
  37. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt +0 -93
  38. package/template_project/.claude/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf +0 -0
  39. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf +0 -0
  40. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf +0 -0
  41. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf +0 -0
  42. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf +0 -0
  43. package/template_project/.claude/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf +0 -0
  44. package/template_project/.claude/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf +0 -0
  45. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Bold.ttf +0 -0
  46. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf +0 -0
  47. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Italic.ttf +0 -0
  48. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-OFL.txt +0 -93
  49. package/template_project/.claude/skills/canvas-design/canvas-fonts/Lora-Regular.ttf +0 -0
  50. package/template_project/.claude/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf +0 -0
  51. package/template_project/.claude/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf +0 -0
  52. package/template_project/.claude/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt +0 -93
  53. package/template_project/.claude/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf +0 -0
@@ -608,6 +608,8 @@ function patternCandidateFromRecord(record) {
608
608
  };
609
609
  }
610
610
 
611
+ const DAY_MS = 24 * 60 * 60 * 1000;
612
+
611
613
  async function proposePatternCandidateV2(projectRoot, projectId, candidate, { homeDir } = {}) {
612
614
  const v2 = await storeV2();
613
615
  const normalizedText = normalizePatternText(candidate?.text);
@@ -643,6 +645,19 @@ async function proposePatternCandidateV2(projectRoot, projectId, candidate, { ho
643
645
  confidence: 0.4,
644
646
  createdBy: 'propose',
645
647
  projectId,
648
+ // Unreviewed until `memory approve`: candidate tier keeps it out of every
649
+ // recall path; approval flips it to verified and clears the expiry.
650
+ // Only mined lessons ask for an expiry (candidate.ttlDays); a hand-written
651
+ // `memory propose` candidate stays pending until a person decides.
652
+ trustTier: 'candidate',
653
+ validUntil: Number(candidate?.ttlDays) > 0 ? Date.now() + Number(candidate.ttlDays) * DAY_MS : null,
654
+ evidence: (Array.isArray(candidate?.evidence) ? candidate.evidence : []).map((ev) => ({
655
+ kind: ev.kind,
656
+ locator: ev.locator,
657
+ observed_at: Date.now(),
658
+ fingerprint: null,
659
+ trust_tier: 'verified',
660
+ })),
646
661
  meta: { ...entry, legacyStatus: 'pending' },
647
662
  }, { homeDir });
648
663
  return entry;
@@ -684,6 +699,8 @@ async function resolvePatternCandidateV2(projectRoot, projectId, candidateId, de
684
699
  provenance: `${target.provenance ?? 'pattern-candidate'};promoted-from:${target.id}`,
685
700
  // Approval is a trust transition — the promoted record is authoritative.
686
701
  trust_tier: 'verified',
702
+ // A promoted rule must not inherit a mined lesson's expiry.
703
+ valid_until: null,
687
704
  meta: {
688
705
  ...target.meta,
689
706
  legacyStatus: 'approved',
@@ -73,7 +73,7 @@ export async function writeInstallMetadata({
73
73
  ompConfigOwnership = null,
74
74
  settingsDefaultsMigration = null,
75
75
  managedHashes = null,
76
- sidecarHashes = null,
76
+ managedSections = null,
77
77
  lockStaleMs,
78
78
  lockMaxWaitMs,
79
79
  }) {
@@ -158,17 +158,21 @@ export async function writeInstallMetadata({
158
158
  const migrationMarker = settingsDefaultsMigration ?? (previousData?.tool === 'ukit' ? previousData.settingsDefaultsMigration : null);
159
159
  if (migrationMarker) metadata.settingsDefaultsMigration = migrationMarker;
160
160
 
161
- // CR-13 provenance for `.ukit-new` sidecars. Only hashes recorded for a sidecar
162
- // UKit actually created this run are kept; every other recorded sidecar is
163
- // re-verified against disk so a record never outlives (or claims) owner content.
164
- // A sidecar whose bytes changed is dropped — it is owner-modified from then on.
161
+ // Per-section template hashes (section-merge baseline for managed templates). Kept across
162
+ // runs; entries for files rewritten this run are replaced.
163
+ const prevSections = previousData?.tool === 'ukit' && previousData.managedSections && typeof previousData.managedSections === 'object'
164
+ ? previousData.managedSections
165
+ : {};
166
+ const mergedSections = { ...prevSections, ...(managedSections ?? {}) };
167
+ if (Object.keys(mergedSections).length > 0) metadata.managedSections = mergedSections;
168
+
169
+ // Legacy `.ukit-new` provenance (sidecars are no longer written). Previously recorded
170
+ // hashes are kept only while the file on disk still matches, so a later cleanup /
171
+ // uninstall can still attribute them; nothing new is ever added.
165
172
  const previousSidecars = previousData?.tool === 'ukit' && previousData.sidecars && typeof previousData.sidecars === 'object'
166
173
  ? previousData.sidecars
167
174
  : {};
168
175
  const mergedSidecars = { ...previousSidecars };
169
- for (const [relPath, hash] of Object.entries(sidecarHashes ?? {})) {
170
- if (typeof hash === 'string') mergedSidecars[normalizeTrackedRelativePath(relPath)] = hash;
171
- }
172
176
  const verifiedSidecars = {};
173
177
  if (projectRoot) {
174
178
  for (const [relPath, hash] of Object.entries(mergedSidecars)) {
@@ -466,14 +466,21 @@ export async function runInstallPipeline({
466
466
  .filter(([p, h]) => typeof p === 'string' && typeof h === 'string')
467
467
  .map(([p, h]) => [path.join(pathConfig.projectRoot, p), h]),
468
468
  );
469
- const diffResults = await diffInstallPlan(plan, { ompOwnership, settingsMigration, recordedManagedHashes });
469
+ // Per-section template hashes recorded at the last install (absent in older install.json).
470
+ const recordedManagedSections = new Map(
471
+ Object.entries(installMetaData?.managedSections ?? {})
472
+ .filter(([p, m]) => typeof p === 'string' && m && typeof m === 'object')
473
+ .map(([p, m]) => [path.join(pathConfig.projectRoot, p), m]),
474
+ );
475
+ const diffResults = await diffInstallPlan(plan, { ompOwnership, settingsMigration, recordedManagedHashes, recordedManagedSections });
470
476
  const plannedSummary = summarizeDiff(diffResults);
471
477
 
472
478
  if (!dryRun) {
473
- const { writes, skippedUpdates, skippedByAction, sidecarHashes } = await applyDiffResults(diffResults, {
479
+ const { writes, skippedUpdates, skippedByAction } = await applyDiffResults(diffResults, {
474
480
  backupRoot: pathConfig.backupRoot,
475
481
  projectRoot: pathConfig.projectRoot,
476
482
  recordedSidecarHashes,
483
+ packageVersion,
477
484
  });
478
485
 
479
486
  for (const entry of diffResults) {
@@ -580,18 +587,17 @@ export async function runInstallPipeline({
580
587
  .filter((e) => e.managedHash && ['create', 'update', 'unchanged'].includes(e.action))
581
588
  .map((e) => [path.relative(pathConfig.projectRoot, e.targetPath).split(path.sep).join('/'), e.managedHash]),
582
589
  );
583
- // Sidecar provenance map (relative path → sha256 UKit wrote this run). Written
584
- // only after apply succeeded, so a failed create never claims ownership.
585
- const sidecarRecords = Object.fromEntries(
586
- Object.entries(sidecarHashes).map(([absPath, h]) => [
587
- path.relative(pathConfig.projectRoot, absPath).split(path.sep).join('/'),
588
- h,
589
- ]),
590
+ // Per-section template hashes for managed templates (recorded after apply succeeded;
591
+ // a conflict/skipped entry has none).
592
+ const managedSections = Object.fromEntries(
593
+ diffResults
594
+ .filter((e) => e.managedSections && ['create', 'update', 'unchanged'].includes(e.action))
595
+ .map((e) => [path.relative(pathConfig.projectRoot, e.targetPath).split(path.sep).join('/'), e.managedSections]),
590
596
  );
591
597
  await writeInstallMetadata({
592
598
  installMetaPath: pathConfig.installMetaPath,
593
599
  managedHashes,
594
- sidecarHashes: sidecarRecords,
600
+ managedSections,
595
601
  packageVersion,
596
602
  manifest,
597
603
  stackContext,
@@ -207,9 +207,7 @@ export function resolveConfigStage(config = null, path) {
207
207
 
208
208
  // decisionRuntime family stage resolver (V-03): resolves
209
209
  // `decisionRuntime.<key>.stage` for one pinned family flag ('vm',
210
- // 'supervisor', 'scheduler', 'contract', 'adapters', 'context',
211
- // 'completion', 'quality', 'promotion', 'resourcePolicy',
212
- // 'diagnostics'). Same semantics as resolveConfigStage: absent config,
210
+ // 'supervisor', 'contract', 'adapters', 'promotion', 'diagnostics'). Same semantics as resolveConfigStage: absent config,
213
211
  // absent family, non-string key, or malformed stage all resolve 'off'
214
212
  // — a bad config can never promote a decisionRuntime slice.
215
213
  export function resolveDecisionRuntimeStage(config = null, key = 'vm') {
@@ -573,13 +571,6 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
573
571
  // codeProposalsCommit is a reserved hard-false — writing a task file is
574
572
  // the ceiling; self-improve never commits code (clamped below).
575
573
  selfImprove: { enabled: true, codeProposals: true, codeProposalsCommit: false },
576
- // C52 M04.2 stage keys (SPEC §5 FR-016–FR-018). candidates: repeated
577
- // corrections/suppressions/escalations promote to a LearningCandidate
578
- // only after minOccurrences + cross-session evidence (status
579
- // 'proposed'; rule promotion still needs approval). overlays: only
580
- // approved + enabled overlays apply; base-version mismatch → conflict.
581
- candidates: { stage: 'default', minOccurrences: 3 },
582
- overlays: { stage: 'default' },
583
574
  },
584
575
  // C52 M04.1 compact resumable state (SPEC §5 FR-012–FR-015): a bounded
585
576
  // resumable-run record per route so a compacted session resumes mid-task.
@@ -590,14 +581,11 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
590
581
  // decision-first-runtime (SPEC §2 G1-FR07, §2 G2-FR07/08, §2 G4-FR07,
591
582
  // §2 G5-FR07, §2 G7-FR04/07). Pinned keys — `decisionRuntime.contract`
592
583
  // gates the G1 contract/eventStore prototype; `decisionRuntime.supervisor`
593
- // gates the G2 owned-process supervisor; `decisionRuntime.scheduler`
594
- // gates the G3 scheduler; `decisionRuntime.vm` gates the G4 plan-VM
595
- // engine; `decisionRuntime.adapters`, `decisionRuntime.context`,
596
- // `decisionRuntime.completion`, and `decisionRuntime.quality` gate the
597
- // G5 adapters/context/completion/quality slice; `decisionRuntime.promotion`
598
- // gates the G6 caller-wait promotion profile and
599
- // `decisionRuntime.resourcePolicy` gates the G6 pressure/coalescing
600
- // policy; `decisionRuntime.diagnostics` gates the G7 explainable-trace /
584
+ // gates the G2 owned-process supervisor; `decisionRuntime.vm` gates the
585
+ // G4 plan-VM engine; `decisionRuntime.adapters` gates the G5 adapters
586
+ // slice; `decisionRuntime.promotion`
587
+ // gates the G6 caller-wait promotion profile;
588
+ // `decisionRuntime.diagnostics` gates the G7 explainable-trace /
601
589
  // replay / support-record readers. 3.3.0 zero-config: every family ships
602
590
  // 'shadow' — evidence is recorded while the deterministic owners stay
603
591
  // authoritative; promotion.js promotes a family only once its frozen
@@ -606,14 +594,9 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
606
594
  decisionRuntime: {
607
595
  contract: { stage: 'shadow' },
608
596
  supervisor: { stage: 'shadow' },
609
- scheduler: { stage: 'shadow' },
610
597
  vm: { stage: 'shadow' },
611
598
  adapters: { stage: 'shadow' },
612
- context: { stage: 'shadow' },
613
- completion: { stage: 'shadow' },
614
- quality: { stage: 'shadow' },
615
599
  promotion: { stage: 'shadow' },
616
- resourcePolicy: { stage: 'shadow' },
617
600
  diagnostics: { stage: 'default' },
618
601
  },
619
602
 
@@ -629,14 +612,6 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
629
612
  roleAdvice: { stage: 'off' },
630
613
  contextSelection: { stage: 'off' },
631
614
  },
632
-
633
- // C52 M06 experiments (SPEC §5 FR-021–FR-023). 3.3.0 zero-config: enabled;
634
- // each experiment still runs only where a caller invokes it and never
635
- // auto-promotes its own result.
636
- experiments: {
637
- deliberation: { enabled: true },
638
- dynamicWorkflow: { enabled: true, maxAttemptsPerFailure: 2, noProgressCap: 3 },
639
- },
640
615
  // Flight recorder (docs/OBSERVABILITY.md): 'default' activates recorder,
641
616
  // analytics, support projection and evaluation. 'off' is the kill switch.
642
617
  observability: { stage: 'default' },
@@ -944,16 +919,18 @@ export function validateRuntimeConfig(config) {
944
919
  // C63 DR-02 + C64 DR-03/04 + C67 DR-07/08 + C68 DR-09 + C69 DR-10
945
920
  // decisionRuntime — optional-present; carries one stage key per prototype
946
921
  // (pinned: decisionRuntime.contract, decisionRuntime.supervisor,
947
- // decisionRuntime.scheduler, decisionRuntime.vm, decisionRuntime.adapters,
948
- // decisionRuntime.context, decisionRuntime.completion,
949
- // decisionRuntime.quality, decisionRuntime.promotion,
950
- // decisionRuntime.resourcePolicy, decisionRuntime.diagnostics). Absent →
951
- // valid; malformed stage → error + resolver falls back to 'off'.
922
+ // decisionRuntime.vm, decisionRuntime.adapters, decisionRuntime.promotion,
923
+ // decisionRuntime.diagnostics). Absent →
924
+ // valid; malformed stage → error + resolver falls back to 'off'. Retired
925
+ // keys (decisionRuntime.scheduler/context/completion/quality/resourcePolicy,
926
+ // experiments.*, learning.candidates/overlays — no reader, removed in
927
+ // 3.5.6) are not validated, so old configs carrying them stay valid and
928
+ // their values are ignored without a warning.
952
929
  if (config.decisionRuntime !== undefined) {
953
930
  if (!isPlainObject(config.decisionRuntime)) {
954
931
  errors.push('decisionRuntime must be an object.');
955
932
  } else {
956
- for (const key of ['contract', 'supervisor', 'scheduler', 'vm', 'adapters', 'context', 'completion', 'quality', 'promotion', 'resourcePolicy', 'diagnostics']) {
933
+ for (const key of ['contract', 'supervisor', 'vm', 'adapters', 'promotion', 'diagnostics']) {
957
934
  const stageKey = config.decisionRuntime[key];
958
935
  if (stageKey === undefined) continue;
959
936
  if (!isPlainObject(stageKey)) {
@@ -984,34 +961,6 @@ export function validateRuntimeConfig(config) {
984
961
  }
985
962
  }
986
963
  }
987
- // C52 M06 experiments — optional-present; both experiments are
988
- // disabled-by-default booleans plus bounded breakers.
989
- if (config.experiments !== undefined) {
990
- if (!isPlainObject(config.experiments)) {
991
- errors.push('experiments must be an object.');
992
- } else {
993
- if (config.experiments.deliberation !== undefined) {
994
- if (!isPlainObject(config.experiments.deliberation)) {
995
- errors.push('experiments.deliberation must be an object.');
996
- } else {
997
- pushBooleanError(errors, config.experiments.deliberation.enabled, 'experiments.deliberation.enabled');
998
- }
999
- }
1000
- if (config.experiments.dynamicWorkflow !== undefined) {
1001
- if (!isPlainObject(config.experiments.dynamicWorkflow)) {
1002
- errors.push('experiments.dynamicWorkflow must be an object.');
1003
- } else {
1004
- pushBooleanError(errors, config.experiments.dynamicWorkflow.enabled, 'experiments.dynamicWorkflow.enabled');
1005
- if (config.experiments.dynamicWorkflow.maxAttemptsPerFailure !== undefined) {
1006
- pushPositiveNumberError(errors, config.experiments.dynamicWorkflow.maxAttemptsPerFailure, 'experiments.dynamicWorkflow.maxAttemptsPerFailure');
1007
- }
1008
- if (config.experiments.dynamicWorkflow.noProgressCap !== undefined) {
1009
- pushPositiveNumberError(errors, config.experiments.dynamicWorkflow.noProgressCap, 'experiments.dynamicWorkflow.noProgressCap');
1010
- }
1011
- }
1012
- }
1013
- }
1014
- }
1015
964
 
1016
965
  // modelRoles is optional-present and additive-namespaced (SPEC-model-roles): absent →
1017
966
  // valid (pre-v3 configs); present → must be an object. Entry-level issues (unknown
@@ -1327,24 +1276,6 @@ export function validateRuntimeConfig(config) {
1327
1276
  pushBooleanError(errors, learning.selfImprove.codeProposalsCommit, 'learning.selfImprove.codeProposalsCommit');
1328
1277
  }
1329
1278
  }
1330
- // C52 M04.2 stage keys — same optional-present contract as routing.*.
1331
- if (learning.candidates !== undefined) {
1332
- if (!isPlainObject(learning.candidates)) {
1333
- errors.push('learning.candidates must be an object.');
1334
- } else {
1335
- pushStageError(errors, learning.candidates, 'learning.candidates');
1336
- if (learning.candidates.minOccurrences !== undefined) {
1337
- pushPositiveNumberError(errors, learning.candidates.minOccurrences, 'learning.candidates.minOccurrences');
1338
- }
1339
- }
1340
- }
1341
- if (learning.overlays !== undefined) {
1342
- if (!isPlainObject(learning.overlays)) {
1343
- errors.push('learning.overlays must be an object.');
1344
- } else {
1345
- pushStageError(errors, learning.overlays, 'learning.overlays');
1346
- }
1347
- }
1348
1279
  }
1349
1280
  }
1350
1281
 
@@ -501,7 +501,14 @@ export async function uninstallUkit({ projectRoot, dryRun = false }) {
501
501
  const sidecarRel = `${entry.normalizedRelative}.ukit-new`;
502
502
  const recordedSidecarHash = installData.sidecars?.[sidecarRel];
503
503
  const sidecarState = await readSidecarState(sidecarAbs);
504
- if (sidecarState.state === 'file' && typeof recordedSidecarHash === 'string' && recordedSidecarHash === sidecarState.hash) {
504
+ // Also attributable: bytes equal to the shipped template (what old versions wrote).
505
+ const shippedForSidecar = managedMap.has(entry.normalizedRelative) && sidecarState.state === 'file'
506
+ ? await fs.readFile(managedMap.get(entry.normalizedRelative)).catch(() => null)
507
+ : null;
508
+ if (sidecarState.state === 'file' && (
509
+ (typeof recordedSidecarHash === 'string' && recordedSidecarHash === sidecarState.hash)
510
+ || (shippedForSidecar !== null && sha256Hex(shippedForSidecar) === sidecarState.hash)
511
+ )) {
505
512
  regularPaths.push({ abs: sidecarAbs, recursive: false });
506
513
  } else if (sidecarState.state !== 'absent') {
507
514
  preservedSidecars.push(sidecarAbs);
@@ -22,8 +22,8 @@ export const DECISION_FAMILIES = new Set([
22
22
  'verify',
23
23
  'review',
24
24
  'resume',
25
- 'learn',
26
25
  'memory',
26
+ 'learn',
27
27
  'runtime',
28
28
  ]);
29
29
 
@@ -273,22 +273,6 @@ export const DECISION_REGISTRY = Object.freeze([
273
273
  cacheSensitivity: 'none',
274
274
  leasePolicy: 'none',
275
275
  },
276
- {
277
- decisionKey: 'learn.candidate-class.v1',
278
- schemaVersion: 1,
279
- family: 'learn',
280
- owner: 'learningCandidates',
281
- kind: 'choice',
282
- description: 'Learning candidate classification for a captured signal. Reserved for the memoryV2 decision lane; promotion gates via decisionPlane.families.learn.stage.',
283
- candidatePolicy: 'owner-shortlist',
284
- hardConstraints: ['promotion-approval'],
285
- probabilityPolicy: 'raw-label',
286
- fallbackPolicy: 'deterministic-classifier',
287
- telemetryClass: 'decision',
288
- rolloutStage: 'off',
289
- cacheSensitivity: 'none',
290
- leasePolicy: 'none',
291
- },
292
276
  {
293
277
  decisionKey: 'review.verdict.v1',
294
278
  schemaVersion: 1,
@@ -449,6 +433,22 @@ export const DECISION_REGISTRY = Object.freeze([
449
433
  cacheSensitivity: 'none',
450
434
  leasePolicy: 'none',
451
435
  },
436
+ {
437
+ decisionKey: 'learn.candidate-class.v1',
438
+ schemaVersion: 1,
439
+ family: 'learn',
440
+ owner: 'lessonClass',
441
+ kind: 'noul',
442
+ description: 'Whether one mined pattern is a real recurring lesson (asked once per ambiguous candidate, wire name carries `#c<n>`). A low answer can only downgrade a candidate to noise; it never approves or promotes. Gated by decisionPlane.families.learn.stage; session end and `ukit memory learn` only.',
443
+ candidatePolicy: 'ambiguous-mined-patterns',
444
+ hardConstraints: ['no-promotion', 'downgrade-only'],
445
+ probabilityPolicy: 'raw-label',
446
+ fallbackPolicy: 'deterministic-rules',
447
+ telemetryClass: 'decision',
448
+ rolloutStage: 'off',
449
+ cacheSensitivity: 'none',
450
+ leasePolicy: 'none',
451
+ },
452
452
  ]);
453
453
 
454
454
  // Deep-freeze the shipped catalog — entries are shared metadata consumed by
@@ -2,7 +2,7 @@
2
2
  // C65 G3-FR03/FR04 — registered semantic decisions + bounded fallback.
3
3
  //
4
4
  // createRuntimeDecider({ client, registry?, confidenceFloor?, now? }) produces
5
- // the `decideFn` runtimeScheduler expects: one ambiguous classified item →
5
+ // a `decideFn`: one ambiguous classified item →
6
6
  // exactly one client.requestBatch → TypedDecision, or a typed conservative
7
7
  // Fallback on every failure mode. The gateway is contacted ONLY for items
8
8
  // classified 'model_decision' with a registered decisionKey — known signals
@@ -33,7 +33,7 @@ export const RUNTIME_DECISIONS = Object.freeze([
33
33
  decisionKey: 'runtime.stall_action.v1',
34
34
  schemaVersion: 1,
35
35
  family: 'runtime',
36
- owner: 'runtimeScheduler',
36
+ owner: 'runtimeDecide',
37
37
  kind: 'choice',
38
38
  description: 'Action for an ambiguous stalled/timeout observation without explicit spec policy.',
39
39
  candidatePolicy: 'conservative-stall-actions',
@@ -51,7 +51,7 @@ export const RUNTIME_DECISIONS = Object.freeze([
51
51
  decisionKey: 'runtime.wake_needed.v1',
52
52
  schemaVersion: 1,
53
53
  family: 'runtime',
54
- owner: 'runtimeScheduler',
54
+ owner: 'runtimeDecide',
55
55
  kind: 'choice',
56
56
  description: 'Whether an ambiguous runtime event needs to wake a host/human, from an unparseable or unknown payload.',
57
57
  candidatePolicy: 'conservative-wake-actions',
@@ -69,7 +69,7 @@ export const RUNTIME_DECISIONS = Object.freeze([
69
69
  decisionKey: 'runtime.safe_retry.v1',
70
70
  schemaVersion: 1,
71
71
  family: 'runtime',
72
- owner: 'runtimeScheduler',
72
+ owner: 'runtimeDecide',
73
73
  kind: 'choice',
74
74
  description: 'Whether an ambiguous failure-adjacent event is safe to retry within registered bounds.',
75
75
  candidatePolicy: 'conservative-retry-actions',
@@ -231,7 +231,7 @@ export function createRuntimeDecider({
231
231
  return fallback('invalid', 'escalate');
232
232
  }
233
233
  // Only 'model_decision' items reach the gateway — known local signals are
234
- // decided upstream by runtimeFilter and pass through untouched.
234
+ // decided by the caller and pass through untouched.
235
235
  if (item.action !== 'model_decision') {
236
236
  return item;
237
237
  }
@@ -6,6 +6,7 @@ import { createHash } from 'node:crypto';
6
6
  import { withFileLock } from '../core/fileOps.js';
7
7
 
8
8
  import { getArtifactPath, getIndexDir, INDEX_ARTIFACTS, INDEX_SCHEMA_VERSION, isLikelyTestFilePath } from './paths.js';
9
+ import { embedConfig, looksLikeQuestion, semanticCandidates, fuseSemantic, semanticStoreSignature } from './semanticLane.js';
9
10
  import { importsNeedAliasContext, loadImportAliasContext, resolveImportSpecifier } from './importResolution.js';
10
11
  import {
11
12
  buildSearchDescriptor,
@@ -57,7 +58,7 @@ function safeSchemaArtifact(artifact) {
57
58
  }
58
59
 
59
60
  // contentLane=false skips the error-string content search (context-resolution paths never pay for it).
60
- export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5, contentLane = true } = {}) {
61
+ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5, contentLane = true, semantic = false } = {}) {
61
62
  const normalizedQuery = String(query ?? '').trim();
62
63
  if (!normalizedQuery) {
63
64
  return [];
@@ -78,11 +79,15 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
78
79
  query: normalizedQuery,
79
80
  limit,
80
81
  contentLane,
82
+ semantic: semantic && embedConfig() ? `1:${await semanticStoreSignature(absoluteRoot)}` : 0,
81
83
  });
82
84
  if (QUERY_RESULT_CACHE.has(queryCacheKey)) {
83
85
  return QUERY_RESULT_CACHE.get(queryCacheKey);
84
86
  }
85
87
  const queryPromise = (async () => {
88
+ // `laneStatus.fellBack`: the lane was asked for (question-shaped, lexical not decisive) and
89
+ // produced nothing (timeout / HTTP error / no vectors). Such a result must not be cached.
90
+ const laneStatus = { fellBack: false };
86
91
  const { files, searchDescriptorsByFile, tokenWeights } = await loadQuerySearchBundle(absoluteRoot);
87
92
  const preferredArchetypes = inferPreferredArchetypes(queryDescriptor.tokens);
88
93
  const includeLikelyTestFiles = shouldIncludeLikelyTestFiles(queryDescriptor);
@@ -156,7 +161,10 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
156
161
  }
157
162
 
158
163
  if (directScores.size === 0) {
159
- return withContentLaneStatus(Object.freeze([]), contentLaneRan, contentCutShort);
164
+ const onlySemantic = semantic ? await applySemanticLane({ absoluteRoot, query: normalizedQuery, ranked: [], includeLikelyTestFiles, files, laneStatus }) : null;
165
+ if (laneStatus.fellBack) QUERY_RESULT_CACHE.delete(queryCacheKey);
166
+ if (onlySemantic) return withContentLaneStatus(freezeQueryResults(onlySemantic.slice(0, limit)), contentLaneRan, contentCutShort);
167
+ return withContentLaneStatus(Object.freeze([]), contentLaneRan, contentCutShort, laneStatus.fellBack);
160
168
  }
161
169
 
162
170
  const {
@@ -205,7 +213,9 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
205
213
  const fused = contentLane && ranked.length > 0 && ranked[0].score < FUSION_WEAK_SCORE && queryDescriptor.tokens.size >= FUSION_MIN_TOKENS
206
214
  ? await fuseWeakQuery({ absoluteRoot, query: normalizedQuery, ranked, searchDescriptorsByFile, includeLikelyTestFiles })
207
215
  : null;
208
- return withContentLaneStatus(freezeQueryResults((fused ?? ranked).slice(0, limit)), contentLaneRan, contentCutShort);
216
+ const semanticMerged = !fused && semantic ? await applySemanticLane({ absoluteRoot, query: normalizedQuery, ranked, includeLikelyTestFiles, files, laneStatus }) : null;
217
+ if (laneStatus.fellBack) QUERY_RESULT_CACHE.delete(queryCacheKey);
218
+ return withContentLaneStatus(freezeQueryResults((fused ?? semanticMerged ?? ranked).slice(0, limit)), contentLaneRan, contentCutShort, laneStatus.fellBack);
209
219
  })().catch((error) => {
210
220
  QUERY_RESULT_CACHE.delete(queryCacheKey);
211
221
  throw error;
@@ -215,6 +225,31 @@ export async function queryCodeIndex({ rootDir = process.cwd(), query, limit = 5
215
225
  return queryPromise;
216
226
  }
217
227
 
228
+ // Real-embedding lane: only when the CLI passes semantic:true AND UKIT_INDEX_EMBED_URL is set.
229
+ // Applies to question-shaped queries only; any problem returns null (lexical result unchanged).
230
+ const SEMANTIC_CONFIDENT_MARGIN = 2;
231
+ async function applySemanticLane({ absoluteRoot, query, ranked, includeLikelyTestFiles, files, laneStatus = {} }) {
232
+ try {
233
+ if (!embedConfig() || !looksLikeQuestion(query)) return null;
234
+ // Lexical is already decisive (top-1 clear of top-2): keep it exactly, no network call.
235
+ if (ranked.length > 1 && ranked[0].score - ranked[1].score >= SEMANTIC_CONFIDENT_MARGIN) return null;
236
+ const known = new Set(safeItems(files).map((f) => f?.filePath));
237
+ const candidates = await semanticCandidates({
238
+ rootDir: absoluteRoot,
239
+ query,
240
+ // Vectors can outlive a deleted/renamed file: only paths in the current index qualify.
241
+ accept: (filePath) => known.has(filePath) && (includeLikelyTestFiles || !isLikelyTestFilePath(filePath)),
242
+ weight: mirrorPrior,
243
+ });
244
+ const fused = fuseSemantic({ ranked, candidates });
245
+ if (!fused) laneStatus.fellBack = true;
246
+ return fused;
247
+ } catch {
248
+ laneStatus.fellBack = true;
249
+ return null;
250
+ }
251
+ }
252
+
218
253
  // Opt-in lane fusion (default OFF): a weak natural-language query (best score below
219
254
  // FUSION_WEAK_SCORE, >= FUSION_MIN_TOKENS tokens) is re-ranked by RRF over the scored list
220
255
  // and a hashed-embedding lane (the retriever.js vector lane). Enabled by
@@ -1561,9 +1596,11 @@ export function queryMatchedSymbolNames(result) {
1561
1596
  // Non-enumerable (array equality and JSON stay unchanged), like boundedSourceSearch rows.truncated:
1562
1597
  // `contentLane` is true when the content search ran; `contentLaneTruncated` lists why it was cut
1563
1598
  // short ('verify-cap', 'time-budget', 'max-files', ...) so a partial scan never reads as "no match".
1564
- function withContentLaneStatus(results, ran, truncated) {
1599
+ function withContentLaneStatus(results, ran, truncated, semanticFellBack = false) {
1565
1600
  // results arrive frozen, so copy before attaching the status and freeze again.
1566
1601
  const out = [...results];
1602
+ // true when the embedding lane was asked for and returned nothing: callers must not persist this result.
1603
+ Object.defineProperty(out, 'semanticFellBack', { value: Boolean(semanticFellBack), enumerable: false });
1567
1604
  Object.defineProperty(out, 'contentLane', { value: ran, enumerable: false });
1568
1605
  Object.defineProperty(out, 'contentLaneTruncated', { value: Object.freeze([...truncated]), enumerable: false });
1569
1606
  return Object.freeze(out);
@@ -273,8 +273,8 @@ export const ROUTE_SHADOW_QUESTIONS = Object.freeze([
273
273
  // capability.impact.v1 — noul kind; no threshold baseline exists on
274
274
  // routeSummary (capabilityPolicy.recommended is unpopulated upstream), so
275
275
  // the question has no comparison value.
276
- // learn.candidate-class.v1 — reserved for the memoryV2 `decision` plane
277
- // (memoryFlags.js), not the route boundary.
276
+ // learn.candidate-class.v1 — the `learn` family classifies mined lesson candidates
277
+ // (gated by decisionPlane.families.learn.stage, off by default); it is not a route-boundary question.
278
278
  ]);
279
279
 
280
280
  // Only families whose resolved stage is not 'off' get a question.