ds4-context-engine 0.1.1 → 0.2.0-beta.1

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.
@@ -12,6 +12,7 @@ import type {
12
12
  const NUMBER_FORMAT = new Intl.NumberFormat("en-US");
13
13
  const SUBCOMMANDS = [
14
14
  "status",
15
+ "adapter",
15
16
  "tokens",
16
17
  "manifest",
17
18
  "explain",
@@ -26,6 +27,8 @@ const SUBCOMMANDS = [
26
27
  "memory",
27
28
  "privacy",
28
29
  "model",
30
+ "quality",
31
+ "ranking",
29
32
  "continuation",
30
33
  "artifacts",
31
34
  "compaction",
@@ -154,6 +157,8 @@ function formatStatus(diagnostics: RuntimeDiagnostics): string {
154
157
  `State: ${diagnostics.phase}`,
155
158
  `Planner: ${diagnostics.plannerVersion} (${diagnostics.lastManifest?.planning?.mode ?? diagnostics.contextMode})`,
156
159
  `Extension / Pi target: ${diagnostics.extensionVersion} / ${diagnostics.supportedPiVersion}`,
160
+ `Adapter contract: ${diagnostics.adapter.contractVersion}`,
161
+ `Adapter capabilities: ${diagnostics.adapter.enabled.length} enabled / ${diagnostics.adapter.disabled.length} disabled`,
157
162
  `Session: ${session?.sessionId ?? "unavailable"}`,
158
163
  `Session entries: ${count(session?.totalEntries)}`,
159
164
  `Current branch entries: ${count(session?.branchEntries)}`,
@@ -182,6 +187,8 @@ function formatStatus(diagnostics: RuntimeDiagnostics): string {
182
187
  `Calibration samples: ${count(diagnostics.modelAwareness?.calibration.acceptedSamples)} accepted`,
183
188
  `Native continuation: ${diagnostics.nativeContinuation.status} (${diagnostics.nativeContinuation.last?.mode ?? "no request"})`,
184
189
  `Continuation saved items: ${count(diagnostics.nativeContinuation.last?.omittedInputItems)}`,
190
+ `Quality metrics: ${diagnostics.quality.enabled ? `${count(diagnostics.quality.storedSamples)} sample(s)` : "disabled"}`,
191
+ `Learned ranking: ${diagnostics.ranking.status} (${diagnostics.ranking.modelLoaded ? diagnostics.ranking.modelId ?? "loaded" : "no model"})`,
185
192
  `Artifact offload: ${count(diagnostics.artifacts.offloadedCount)} result(s), ${count(diagnostics.artifacts.offloadedBytes)} bytes`,
186
193
  `Artifact tokens saved: ${count(diagnostics.artifacts.estimatedTokensSaved)} estimated`,
187
194
  `Artifact objects / refs: ${count(diagnostics.artifacts.stats.objects)} / ${count(diagnostics.artifacts.stats.references)}`,
@@ -365,6 +372,12 @@ function formatRetrieved(diagnostics: RuntimeDiagnostics): string {
365
372
  `Status: ${retrieval.status}`,
366
373
  `Query terms: ${retrieval.queryTerms.length > 0 ? retrieval.queryTerms.join(", ") : "none"}`,
367
374
  `Candidates: ${count(retrieval.candidateCount)}`,
375
+ `Lexical / vector / fused: ${count(retrieval.semantic.lexicalCandidates)} / ${count(retrieval.semantic.vectorCandidates)} / ${count(retrieval.semantic.fusedCandidates)}`,
376
+ `Embedding model: ${retrieval.semantic.provider && retrieval.semantic.model ? `${retrieval.semantic.provider}/${retrieval.semantic.model}` : "disabled"}`,
377
+ `Embedding dimensions/mode:${count(retrieval.semantic.dimensions).padStart(9)} / ${retrieval.semantic.destination ?? "n/a"}`,
378
+ `Vector index/cache hit: ${retrieval.semantic.indexFresh ? "fresh" : "stale/unavailable"} / ${retrieval.semantic.queryCacheHit ? "yes" : "no"}`,
379
+ `Embedding calls source/query:${count(retrieval.semantic.sourceEmbeddingCalls).padStart(6)} / ${count(retrieval.semantic.queryEmbeddingCalls)}`,
380
+ ...(retrieval.semantic.fallbackReason ? [`Semantic fallback: ${retrieval.semantic.fallbackReason}`] : []),
368
381
  `Alternate-branch blocked:${count(retrieval.alternateBranchCandidates).padStart(9)}`,
369
382
  `Duplicate candidates: ${count(retrieval.duplicateCandidates)}`,
370
383
  `Planner exclusions: ${count(retrieval.plannerExcludedCount)}`,
@@ -404,6 +417,11 @@ function formatProject(diagnostics: RuntimeDiagnostics): string {
404
417
  `Skipped large/binary/secret:${count(sync?.skippedLarge).padStart(7)} / ${count(sync?.skippedBinary)} / ${count(sync?.skippedSensitive)}`,
405
418
  `Query terms: ${project.queryTerms.length > 0 ? project.queryTerms.join(", ") : "none"}`,
406
419
  `Candidates / duplicates: ${count(project.candidateCount)} / ${count(project.duplicateCandidates)}`,
420
+ `Lexical / vector / fused: ${count(project.semantic.lexicalCandidates)} / ${count(project.semantic.vectorCandidates)} / ${count(project.semantic.fusedCandidates)}`,
421
+ `Embedding model: ${project.semantic.provider && project.semantic.model ? `${project.semantic.provider}/${project.semantic.model}` : "disabled"}`,
422
+ `Embedding dimensions/mode: ${count(project.semantic.dimensions)} / ${project.semantic.destination ?? "n/a"}`,
423
+ `Vector index/cache hit: ${project.semantic.indexFresh ? "fresh" : "stale/unavailable"} / ${project.semantic.queryCacheHit ? "yes" : "no"}`,
424
+ ...(project.semantic.fallbackReason ? [`Semantic fallback: ${project.semantic.fallbackReason}`] : []),
407
425
  `Invalidated / reindexed: ${count(project.invalidatedSnippets)} / ${count(project.reindexedFiles)}`,
408
426
  `Planner exclusions: ${count(project.plannerExcludedCount)}`,
409
427
  `Selected / maximum tokens: ${count(project.selectedTokens)} / ${count(project.maxTokens)}`,
@@ -449,6 +467,7 @@ function formatMemory(runtime: Ds4ContextRuntime, diagnostics: RuntimeDiagnostic
449
467
  `Active / inactive: ${count(diagnostics.memory.activeMemories)} / ${count(diagnostics.memory.inactiveMemories)}`,
450
468
  `Selected / excluded: ${count(diagnostics.memory.selectedMemories.length)} / ${count(diagnostics.memory.excludedMemories)}`,
451
469
  `Selected tokens: ${count(diagnostics.memory.selectedMemoryTokens)}`,
470
+ `Cross-session: ${diagnostics.memory.crossSession.status} (${count(diagnostics.memory.crossSession.contributingSessions)} contributing / ${count(diagnostics.memory.crossSession.discoveredSessions)} discovered)`,
452
471
  ...diagnostics.memory.warnings.map((warning) => `Warning: ${warning}`),
453
472
  "",
454
473
  ...(memories.length === 0
@@ -463,6 +482,33 @@ function formatMemory(runtime: Ds4ContextRuntime, diagnostics: RuntimeDiagnostic
463
482
  "Add: /context memory add [--scope session|project] [--classification LEVEL] [--key KEY] [--source ID,ID] <claim>",
464
483
  "Replace: /context memory supersede MEMORY_ID [--classification LEVEL] [--source ID,ID] <new claim>",
465
484
  "Invalidate/expire: /context memory invalidate|expire MEMORY_ID [reason]",
485
+ "Sources: /context memory sources|exclude SESSION_ID [reason]|include SESSION_ID",
486
+ ].join("\n");
487
+ }
488
+
489
+ function formatProjectMemorySources(runtime: Ds4ContextRuntime, diagnostics: RuntimeDiagnostics): string {
490
+ const cross = diagnostics.memory.crossSession;
491
+ const sources = runtime.projectMemorySources();
492
+ return [
493
+ "DS4 Cross-Session Project Memory Sources",
494
+ "",
495
+ `Enabled / status: ${cross.enabled ? "yes" : "no"} / ${cross.status}`,
496
+ `Discovered / contributing:${count(cross.discoveredSessions).padStart(8)} / ${count(cross.contributingSessions)}`,
497
+ `Excluded / unavailable: ${count(cross.excludedSessions).padStart(8)} / ${count(cross.unavailableSessions)}`,
498
+ `Incremental / rebuilt: ${count(cross.incrementalSessions).padStart(8)} / ${count(cross.rebuiltSessions)}`,
499
+ ...cross.warnings.map((warning) => `Warning: ${warning}`),
500
+ "",
501
+ ...(sources.length === 0
502
+ ? ["No project memory source sessions have been discovered."]
503
+ : sources.map((source, index) => [
504
+ `${index + 1}. ${source.sessionId} ${source.status} mutations=${count(source.indexedMutations)} active=${count(source.activeProjectMemories + source.activeProjectPins)}`,
505
+ ` records=${count(source.indexedRecords)} malformed=${count(source.malformedLines)} file=${JSON.stringify(source.sessionFile)}`,
506
+ ...(source.exclusionReason ? [` exclusion: ${source.exclusionReason}`] : []),
507
+ ...(source.lastError ? [` error: ${source.lastError}`] : []),
508
+ ].join("\n"))),
509
+ "",
510
+ "Exclude: /context memory exclude SESSION_ID [reason]",
511
+ "Restore: /context memory include SESSION_ID",
466
512
  ].join("\n");
467
513
  }
468
514
 
@@ -528,6 +574,71 @@ function formatModelAwareness(diagnostics: RuntimeDiagnostics): string {
528
574
  ].join("\n");
529
575
  }
530
576
 
577
+ function formatQuality(diagnostics: RuntimeDiagnostics): string {
578
+ const quality = diagnostics.quality;
579
+ const aggregate = quality.aggregate;
580
+ const percentage = (rate: number | null): string => rate === null ? "n/a" : `${(rate * 100).toFixed(2)}%`;
581
+ const reasonSummary = (reasons: Readonly<Record<string, number>>): string => {
582
+ const entries = Object.entries(reasons);
583
+ return entries.length > 0
584
+ ? entries.map(([reason, total]) => `${reason}=${count(total)}`).join(", ")
585
+ : "none";
586
+ };
587
+ const budgetLines = Object.entries(aggregate.budgetUtilization).map(([kind, budget]) =>
588
+ ` ${kind.padEnd(12)} ${count(budget.selectedTokens)} / ${count(budget.limitTokens)} (${(budget.utilization * 100).toFixed(2)}%), dropped ${count(budget.droppedTokens)}`
589
+ );
590
+ return [
591
+ "DS4 Context Quality",
592
+ "",
593
+ `Status: ${quality.enabled ? "enabled" : "disabled (opt-in)"}`,
594
+ `Metrics version: ${quality.metricsVersion}`,
595
+ `Samples stored/labeled: ${count(quality.storedSamples)} / ${count(aggregate.labeledSampleCount)}`,
596
+ `Corrupt samples ignored: ${count(quality.ignoredSamples)}`,
597
+ `Primary quality score: ${(aggregate.qualityScore * 100).toFixed(2)}%`,
598
+ `Evidence recall: ${percentage(aggregate.evidenceRecall.rate)} (${count(aggregate.evidenceRecall.numerator)}/${count(aggregate.evidenceRecall.denominator)})`,
599
+ `Irrelevant-token ratio: ${percentage(aggregate.irrelevantTokenRatio.rate)}`,
600
+ `Duplicate references: ${count(aggregate.duplicateEvidence.duplicateReferences)} / ${count(aggregate.duplicateEvidence.selectedReferences)}`,
601
+ `Provenance coverage: ${percentage(aggregate.provenanceCoverage.rate)}`,
602
+ `Current request retained: ${percentage(aggregate.currentRequestRetention.rate)}`,
603
+ `Atomic groups valid: ${percentage(aggregate.atomicGroupValidity.rate)}`,
604
+ `Overflow / fallback rate: ${percentage(aggregate.overflowRate.rate)} / ${percentage(aggregate.fallbackRate.rate)}`,
605
+ `Selected / dropped tokens: ${count(aggregate.selectedTokens)} / ${count(aggregate.droppedTokens)}`,
606
+ `Planning mean / p95: ${quality.timing.meanPlanningDurationMs === undefined ? "n/a" : `${quality.timing.meanPlanningDurationMs.toFixed(3)} ms`} / ${quality.timing.p95PlanningDurationMs === undefined ? "n/a" : `${quality.timing.p95PlanningDurationMs.toFixed(3)} ms`}`,
607
+ "Category budget utilization:",
608
+ ...(budgetLines.length > 0 ? budgetLines : [" no samples"]),
609
+ `Selection reasons: ${reasonSummary(aggregate.selectionReasons)}`,
610
+ `Drop reasons: ${reasonSummary(aggregate.dropReasons)}`,
611
+ ...(quality.lastError ? [`Last quality warning: ${quality.lastError}`] : []),
612
+ "",
613
+ "Quality storage contains counts, versions, labels and timings only; prompt and evidence text are never persisted.",
614
+ ].join("\n");
615
+ }
616
+
617
+ function formatRanking(diagnostics: RuntimeDiagnostics): string {
618
+ const ranking = diagnostics.ranking;
619
+ return [
620
+ "DS4 Learned Ranking",
621
+ "",
622
+ `Mode / status: ${ranking.mode} / ${ranking.status}`,
623
+ `Feature schema: ${ranking.featureVersion}`,
624
+ `Model: ${ranking.modelId ?? "unavailable"}`,
625
+ `Model path: ${ranking.modelPath ?? "unavailable"}`,
626
+ `Loaded / promoted: ${ranking.modelLoaded ? "yes" : "no"} / ${ranking.promoted ? "yes" : "no"}`,
627
+ `Training samples: ${count(ranking.trainingSamples)}`,
628
+ `Malformed / duplicate: ${count(ranking.malformedFeedback)} / ${count(ranking.duplicateFeedback)}`,
629
+ `Latest candidates: ${count(ranking.candidateCount)}`,
630
+ `Top changed in shadow: ${ranking.topChanged ? "yes" : "no"}`,
631
+ `Pairwise disagreements: ${count(ranking.pairwiseDisagreements)}`,
632
+ `Mean rank shift: ${ranking.meanRankShift.toFixed(6)}`,
633
+ `Inference duration: ${ranking.durationMs.toFixed(3)} ms`,
634
+ ...(ranking.fallbackReason ? [`Static fallback: ${ranking.fallbackReason}`] : []),
635
+ ...ranking.warnings.map((warning) => `Warning: ${warning}`),
636
+ "",
637
+ "Feedback stores only bounded numeric features, hashes, label, version, and classification in Pi JSONL.",
638
+ "Shadow mode records aggregate comparison only and never changes selected context.",
639
+ ].join("\n");
640
+ }
641
+
531
642
  function formatNativeContinuation(diagnostics: RuntimeDiagnostics): string {
532
643
  const continuation = diagnostics.nativeContinuation;
533
644
  const latest = continuation.last;
@@ -585,6 +696,27 @@ function formatArtifacts(diagnostics: RuntimeDiagnostics): string {
585
696
  ].join("\n");
586
697
  }
587
698
 
699
+ function formatAdapter(diagnostics: RuntimeDiagnostics): string {
700
+ const negotiation = diagnostics.adapter;
701
+ return [
702
+ "DS4 Runtime Adapter",
703
+ "",
704
+ `Runtime: Pi`,
705
+ `Contract: ${negotiation.contractVersion}`,
706
+ `Enabled requested: ${count(negotiation.enabled.length)}`,
707
+ `Disabled requested: ${count(negotiation.disabled.length)}`,
708
+ "",
709
+ ...negotiation.statuses.map((status) =>
710
+ `${status.id}: ${status.supported ? `supported (${status.version ?? "unversioned"})` : `unavailable (${status.reason ?? "no reason"})`}; ${status.enabled ? "enabled" : status.requested ? "disabled safely" : "not requested"}`
711
+ ),
712
+ ...(negotiation.diagnostics.length > 0
713
+ ? ["", ...negotiation.diagnostics.map((diagnostic) =>
714
+ `${diagnostic.severity.toUpperCase()} ${diagnostic.code}: ${diagnostic.message}`
715
+ )]
716
+ : []),
717
+ ].join("\n");
718
+ }
719
+
588
720
  function formatCompaction(diagnostics: RuntimeDiagnostics, preview: boolean): string {
589
721
  const compaction = diagnostics.compaction;
590
722
  return [
@@ -632,6 +764,11 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
632
764
  return;
633
765
  }
634
766
 
767
+ if (subcommand === "adapter") {
768
+ present(ctx, formatAdapter(runtime.diagnostics(ctx)));
769
+ return;
770
+ }
771
+
635
772
  if (subcommand === "tokens") {
636
773
  present(ctx, formatTokens(runtime.diagnostics(ctx)));
637
774
  return;
@@ -716,7 +853,27 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
716
853
  present(ctx, formatMemory(runtime, runtime.diagnostics(ctx)));
717
854
  return;
718
855
  }
856
+ if (nested.command === "sources") {
857
+ present(ctx, formatProjectMemorySources(runtime, runtime.diagnostics(ctx)));
858
+ return;
859
+ }
719
860
  const parsed = parseCommandArgs(nested.args);
861
+ if (nested.command === "exclude" || nested.command === "include") {
862
+ assertOptions(parsed.options, []);
863
+ const sessionId = parsed.positionals[0];
864
+ if (!sessionId) {
865
+ throw new Error(`Usage: /context memory ${nested.command} SESSION_ID${nested.command === "exclude" ? " [reason]" : ""}`);
866
+ }
867
+ runtime.setProjectMemorySourceExcluded(
868
+ sessionId,
869
+ nested.command === "exclude",
870
+ nested.command === "exclude"
871
+ ? parsed.positionals.slice(1).join(" ") || undefined
872
+ : undefined,
873
+ );
874
+ present(ctx, `Project memory source ${sessionId} ${nested.command === "exclude" ? "excluded" : "restored"}`);
875
+ return;
876
+ }
720
877
  if (nested.command === "add") {
721
878
  assertOptions(parsed.options, ["scope", "key", "source", "classification"]);
722
879
  const scope = (parsed.options.get("scope") ?? "session").toLowerCase();
@@ -769,7 +926,7 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
769
926
  present(ctx, `Memory ${memory.id} is ${memory.status}`);
770
927
  return;
771
928
  }
772
- throw new Error("Usage: /context memory [list|add|supersede|invalidate|expire]");
929
+ throw new Error("Usage: /context memory [list|sources|exclude|include|add|supersede|invalidate|expire]");
773
930
  }
774
931
 
775
932
  if (subcommand === "privacy") {
@@ -782,6 +939,55 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
782
939
  return;
783
940
  }
784
941
 
942
+ if (subcommand === "quality") {
943
+ present(ctx, formatQuality(runtime.diagnostics(ctx)));
944
+ return;
945
+ }
946
+
947
+ if (subcommand === "ranking") {
948
+ const nested = splitCommand(subcommandArgs, "status");
949
+ if (nested.command === "status") {
950
+ if (nested.args.trim()) throw new Error("Usage: /context ranking [status|feedback|train]");
951
+ present(ctx, formatRanking(runtime.diagnostics(ctx)));
952
+ return;
953
+ }
954
+ if (nested.command === "feedback") {
955
+ const parsed = parseCommandArgs(nested.args);
956
+ assertOptions(parsed.options, ["classification"]);
957
+ const label = parsed.positionals[0];
958
+ const candidateId = parsed.positionals[1];
959
+ if ((label !== "useful" && label !== "irrelevant") || !candidateId || parsed.positionals.length !== 2) {
960
+ throw new Error("Usage: /context ranking feedback useful|irrelevant CANDIDATE_ID [--classification CLASS]");
961
+ }
962
+ const feedback = runtime.recordRankingFeedback(
963
+ candidateId,
964
+ label,
965
+ classificationOption(parsed.options.get("classification")),
966
+ ctx,
967
+ (customType, data) => pi.appendEntry(customType, data),
968
+ );
969
+ present(ctx, `Ranking feedback ${feedback.feedbackId} recorded as ${feedback.label} (${feedback.classification})`);
970
+ return;
971
+ }
972
+ if (nested.command === "train") {
973
+ if (nested.args.trim()) throw new Error("Usage: /context ranking train");
974
+ await ctx.waitForIdle();
975
+ const result = runtime.trainRankingModel(ctx);
976
+ present(ctx, [
977
+ "DS4 Ranking Model Trained",
978
+ "",
979
+ `Model: ${result.modelId}`,
980
+ `Samples: ${count(result.sampleCount)} (${count(result.positiveSamples)} useful / ${count(result.negativeSamples)} irrelevant)`,
981
+ `Repositories: ${count(result.repositoryCount)}`,
982
+ `Artifact: ${result.modelPath}`,
983
+ ...(result.warnings.length > 0 ? [`Warnings: ${result.warnings.length}`] : []),
984
+ "Active mode remains gated until held-out promotion succeeds.",
985
+ ].join("\n"));
986
+ return;
987
+ }
988
+ throw new Error("Usage: /context ranking [status|feedback|train]");
989
+ }
990
+
785
991
  if (subcommand === "continuation") {
786
992
  present(ctx, formatNativeContinuation(runtime.diagnostics(ctx)));
787
993
  return;
@@ -836,6 +1042,9 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
836
1042
  && diagnostics.memory.warnings.length === 0
837
1043
  && diagnostics.privacy.warnings.length === 0
838
1044
  && diagnostics.nativeContinuation.warnings.length === 0
1045
+ && diagnostics.quality.ignoredSamples === 0
1046
+ && diagnostics.quality.lastError === undefined
1047
+ && diagnostics.ranking.warnings.length === 0
839
1048
  && artifactIntegrityIssues === 0
840
1049
  && diagnostics.artifacts.warnings.length === 0;
841
1050
  present(
@@ -854,6 +1063,9 @@ export function registerContextCommand(pi: ExtensionAPI, runtime: Ds4ContextRunt
854
1063
  `Privacy enforcement: ${diagnostics.privacy.enforcement}`,
855
1064
  `Privacy warnings: ${count(diagnostics.privacy.warnings.length)}`,
856
1065
  `Continuation warnings: ${count(diagnostics.nativeContinuation.warnings.length)}`,
1066
+ `Quality samples/ignored: ${count(diagnostics.quality.storedSamples)} / ${count(diagnostics.quality.ignoredSamples)}`,
1067
+ `Quality warning: ${diagnostics.quality.lastError ?? "none"}`,
1068
+ `Ranking status/warnings: ${diagnostics.ranking.status} / ${count(diagnostics.ranking.warnings.length)}`,
857
1069
  `Artifact missing/corrupt: ${count(diagnostics.artifacts.stats.missing)} / ${count(diagnostics.artifacts.stats.corrupt)}`,
858
1070
  `Artifact warnings: ${count(diagnostics.artifacts.warnings.length)}`,
859
1071
  ].join("\n"),
@@ -22,6 +22,7 @@ export function registerDs4ContextEngine(
22
22
  ...(dependencies.now ? { now: dependencies.now } : {}),
23
23
  ...(dependencies.idGenerator ? { idGenerator: dependencies.idGenerator } : {}),
24
24
  ...(dependencies.logSink ? { logSink: dependencies.logSink } : {}),
25
+ ...(dependencies.embeddingPort ? { embeddingPort: dependencies.embeddingPort } : {}),
25
26
  });
26
27
 
27
28
  const continuationStream = createOpenAIResponsesContinuationStream({