@fenglimg/fabric-server 2.3.0-rc.1 → 2.3.0-rc.11

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 (3) hide show
  1. package/dist/index.d.ts +242 -6
  2. package/dist/index.js +1666 -368
  3. package/package.json +5 -2
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { FabExtractKnowledgeInput, FabExtractKnowledgeOutput, FabReviewInput, FabReviewOutput, FabPendingInput, FabPendingOutput } from '@fenglimg/fabric-shared/schemas/api-contracts';
3
- import { EventLedgerEventInput, EventLedgerEvent, RuleDescriptionIndexItem, LedgerEntry, AgentsMeta } from '@fenglimg/fabric-shared';
3
+ import { RuleDescription, EventLedgerEventInput, EventLedgerEvent, RuleDescriptionIndexItem, RecallScore, RecallScoreBreakdown, LedgerEntry, AgentsMeta } from '@fenglimg/fabric-shared';
4
4
  import { PayloadGuardOptions } from '@fenglimg/fabric-shared/node/mcp-payload-guard';
5
5
 
6
6
  interface InFlightTracker {
@@ -32,6 +32,16 @@ type DoctorHealth = {
32
32
  warnings: number;
33
33
  };
34
34
  };
35
+ type BacklogAgeMetric = {
36
+ count: number;
37
+ oldest_days: number | null;
38
+ median_age_days: number;
39
+ ages_days: number[];
40
+ };
41
+ declare function checkBacklogAge(projectRoot: string, nowMs?: number): Promise<BacklogAgeMetric>;
42
+ declare function renderBacklogAgeLine(metric: BacklogAgeMetric): string;
43
+
44
+ declare function extractRuleDescription(source: string): RuleDescription | undefined;
35
45
 
36
46
  interface AlwaysActiveBody {
37
47
  /** store-qualified id (`<alias>:<stableId>`). */
@@ -78,6 +88,16 @@ interface KnowledgeCensus {
78
88
  */
79
89
  declare function buildKnowledgeCensus(projectRoot: string): Promise<KnowledgeCensus>;
80
90
  declare function buildAlwaysActiveBodies(projectRoot: string): Promise<AlwaysActiveBody[]>;
91
+ interface StoreCanonicalEntry {
92
+ stableId: string;
93
+ qualifiedId: string;
94
+ file: string;
95
+ type: string;
96
+ layer: "team" | "personal";
97
+ body: string;
98
+ description: NonNullable<ReturnType<typeof extractRuleDescription>>;
99
+ }
100
+ declare function collectStoreCanonicalEntries(projectRoot: string): Promise<StoreCanonicalEntry[]>;
81
101
 
82
102
  interface UnboundProjectViolation {
83
103
  /** The store already bound as the active write target. */
@@ -196,6 +216,11 @@ type CiteCoverageReport = {
196
216
  uncorrelatable_edits?: number;
197
217
  recall_backed_edits?: number;
198
218
  recall_coverage_rate?: number | null;
219
+ recall_diagnostics?: {
220
+ recalls_in_window: number;
221
+ recall_sessions: number;
222
+ recall_sessions_correlated: number;
223
+ };
199
224
  exposed_and_mutated?: {
200
225
  count: number;
201
226
  ids?: string[];
@@ -394,6 +419,29 @@ interface Bm25Model {
394
419
  * query property).
395
420
  */
396
421
  scoreDoc(id: string, queryTerms: string[]): number;
422
+ /**
423
+ * P1 recall-engine-refactor (TASK-002): the plain JSON-safe snapshot of the
424
+ * corpus statistics this model scores against, attached so the model can be
425
+ * serialized to disk (`serializeBm25Model`) and a cold hook can `rehydrate`
426
+ * an identical scorer without re-tokenizing the corpus.
427
+ */
428
+ readonly __serialized: SerializedBm25Model;
429
+ }
430
+ interface SerializedBm25Model {
431
+ /** Schema/format version — bump on any layout change so a stale on-disk cache
432
+ * (different shape) is detected and discarded rather than mis-rehydrated. */
433
+ version: 1;
434
+ totalDocs: number;
435
+ /** term → document frequency (union-of-fields df), as [term, count] pairs. */
436
+ documentFrequency: [string, number][];
437
+ /** Per-field corpus average length. */
438
+ avgFieldLength: Record<Bm25Field, number>;
439
+ /** Per-doc stats: id → { per-field [term,freq] pairs, per-field length }. */
440
+ perDoc: {
441
+ id: string;
442
+ fieldTermFreq: Record<Bm25Field, [string, number][]>;
443
+ fieldLength: Record<Bm25Field, number>;
444
+ }[];
397
445
  }
398
446
  /**
399
447
  * Build a BM25F model over `docs`. Corpus statistics (per-field document
@@ -507,6 +555,45 @@ declare function runDoctorConflictLint(projectRoot: string, opts?: {
507
555
  judge?: ConflictJudge;
508
556
  }): Promise<ConflictLintReport>;
509
557
 
558
+ declare function readEmbedConfig(projectRoot: string): {
559
+ enabled: boolean;
560
+ weight: number;
561
+ model: string;
562
+ };
563
+ declare function readFusion(projectRoot: string): "additive" | "rrf" | "auto";
564
+
565
+ interface Embedder {
566
+ embed(texts: string[]): Promise<number[][]>;
567
+ }
568
+ declare const OPTIONAL_EMBED_PACKAGE = "fastembed";
569
+ /**
570
+ * Is the optional embedder package resolvable FROM THE SERVER'S module location —
571
+ * i.e. from exactly where `loadEmbedder`'s dynamic `import()` will look for it?
572
+ *
573
+ * This is the honest "is fastembed installed?" probe. The naive alternative — a
574
+ * `createRequire(import.meta.url)` check run inside the CLI package — answers from
575
+ * the WRONG base: in a pnpm / non-hoisted layout (or a dev-linked global install)
576
+ * fastembed lives under the SERVER's `node_modules` (it is the server's
577
+ * optionalDependency), so the CLI cannot resolve it even though the server — the
578
+ * only code that actually imports it — can. That mismatch made `fabric info
579
+ * --recall` report "not installed" on a perfectly working setup. Callers that
580
+ * surface embedder availability MUST use this server-anchored probe.
581
+ */
582
+ declare function isEmbedderResolvable(): boolean;
583
+ declare function defaultEmbedCacheDir(): string;
584
+ /**
585
+ * Lazy-load the optional fastembed embedder, pinned to CPU + cache-only. Returns
586
+ * null (cached) when the package is not installed or initialization throws, so
587
+ * every caller degrades to the text-only path. Never throws.
588
+ *
589
+ * v2.1 ③: `modelName` (a fastembed EmbeddingModel enum value) selects the
590
+ * embedding model — the caller threads `embed_model` config through so the
591
+ * Chinese-heavy KB no longer embeds against fastembed's English default. The
592
+ * load is cached per-process; the FIRST model wins (a config change needs a
593
+ * server restart, already the norm for MCP config changes).
594
+ */
595
+ declare function loadEmbedder(modelName?: string): Promise<Embedder | null>;
596
+
510
597
  interface RetiredToken {
511
598
  /** The exact dead token as it appears in agent-facing text. */
512
599
  token: string;
@@ -594,8 +681,10 @@ declare function reviewKnowledge(projectRoot: string, input: FabReviewInput): Pr
594
681
  * from `reviewKnowledge`. list browses the store-backed pending backlog;
595
682
  * search ranges over BOTH pending and canonical knowledge. Neither mutates
596
683
  * state — the fab_pending tool is registered readOnlyHint:true / idempotentHint:true.
597
- * The underlying listPending / searchEntries helpers are unchanged (verbatim
598
- * relocation), so behavior is identical to the prior fab_review list/search.
684
+ * P1 recall-engine-refactor (TASK-005): search now routes through `triageSearch`,
685
+ * which gates on the substring query then RANKS the matches via the shared
686
+ * rankDescriptionItems('triage') — NO top_k, NO floor, so pending review never
687
+ * silently drops a match. The old substring-only search machine is gone.
599
688
  */
600
689
  declare function reviewPending(projectRoot: string, input: FabPendingInput): Promise<FabPendingOutput>;
601
690
 
@@ -630,6 +719,148 @@ declare const COLD_EVAL_RUBRIC: string;
630
719
  */
631
720
  declare function buildColdEvalBatch(candidates: ColdEvalCandidate[]): ColdEvalBatch;
632
721
 
722
+ interface RelatedBrokenLink {
723
+ /** The entry (store-qualified id) that declared the `related` edge. */
724
+ source: string;
725
+ /** The unresolvable related value. */
726
+ target: string;
727
+ }
728
+ interface RelatedHubEntry {
729
+ stableId: string;
730
+ inDegree: number;
731
+ }
732
+ interface RelatedGraphInspection {
733
+ brokenLinks: RelatedBrokenLink[];
734
+ hubEntries: RelatedHubEntry[];
735
+ /** Total canonical entries scanned. */
736
+ totalEntries: number;
737
+ }
738
+ /** A single node fed into the pure graph builder. */
739
+ interface RelatedGraphNode {
740
+ /** Store-qualified id (`<alias>:<stableId>`). */
741
+ qualifiedId: string;
742
+ /** The entry's declared `related` edges (frontmatter), if any. */
743
+ related?: string[];
744
+ }
745
+ /**
746
+ * Build the related-edge graph from a list of nodes and report broken links +
747
+ * hub ranking. Pure — no I/O — so the broken-link / in-degree logic can be
748
+ * tested with hand-built fixtures.
749
+ *
750
+ * A "broken link" is a `related` value that does not appear as any node's
751
+ * store-qualified id NOR bare stable_id in the corpus. Store-qualified
752
+ * references (`alias:id`) and bare references (`id`) both resolve, because the
753
+ * id index carries both forms for every node.
754
+ */
755
+ declare function buildRelatedGraph(nodes: RelatedGraphNode[]): RelatedGraphInspection;
756
+ /**
757
+ * Walk the store canonical corpus and build the related graph. Never throws —
758
+ * collectStoreCanonicalEntries degrades to [] when no store is in the read-set.
759
+ *
760
+ * Note: the previous (dead, never-wired) draft of this module re-parsed each
761
+ * entry's frontmatter via extractRuleDescription(entry.file) — passing a FILE
762
+ * PATH where a raw-markdown SOURCE was expected, which silently produced no
763
+ * edges. StoreCanonicalEntry already carries the parsed `description`, so we
764
+ * read `description.related` directly (the single source the recall path uses).
765
+ */
766
+ declare function inspectRelatedGraph(projectRoot: string): Promise<RelatedGraphInspection>;
767
+
768
+ interface StoreReachability {
769
+ uuid: string;
770
+ alias: string;
771
+ reachable: boolean;
772
+ reason?: string;
773
+ }
774
+ interface PrecheckResult {
775
+ stores: StoreReachability[];
776
+ allReachable: boolean;
777
+ }
778
+ declare function clearPrecheckCache(): void;
779
+ /**
780
+ * Evaluate a single store directory's reachability. A store is reachable when
781
+ * BOTH hold:
782
+ * 1. The store directory exists on disk.
783
+ * 2. The directory contains either a `store.json` (valid JSON, local-only
784
+ * store) OR a `.git/` subdirectory (git-cloned store).
785
+ *
786
+ * Pure (filesystem-only, no config resolution) so the rule is testable with a
787
+ * temp directory regardless of the machine's ~/.fabric layout.
788
+ */
789
+ declare function evaluateStoreDir(storeDir: string, identity: {
790
+ uuid: string;
791
+ alias: string;
792
+ }): StoreReachability;
793
+ /**
794
+ * Check that every store in the project's read-set is reachable on disk.
795
+ * Results are cached for 60s (CACHE_TTL_MS). Call `clearPrecheckCache()` when a
796
+ * store mount / unmount operation invalidates the cache.
797
+ *
798
+ * `globalRoot` is injectable for hermetic tests; production callers use the
799
+ * resolved ~/.fabric root.
800
+ */
801
+ declare function precheckStoreReachability(projectRoot: string, globalRoot?: string, now?: number): Promise<PrecheckResult>;
802
+
803
+ interface ConsumptionLintConfig {
804
+ /** Rolling window in days (default 30). */
805
+ windowDays: number;
806
+ /** How many top-consumed entries to report (default 10). */
807
+ topN: number;
808
+ /** Minimum CORPUS size before the lint runs at all (fresh-install guard). */
809
+ minTotalEntries: number;
810
+ /**
811
+ * Data-maturity gate axis 1: minimum number of metrics windows (rows) that
812
+ * recorded ≥1 consumption counter before zero-consumed is trustworthy.
813
+ */
814
+ minConsumedWindows: number;
815
+ /**
816
+ * Data-maturity gate axis 2: minimum total consumption events in the window
817
+ * before zero-consumed is trustworthy.
818
+ */
819
+ minConsumedEvents: number;
820
+ }
821
+ interface ConsumptionEntry {
822
+ /** Store-qualified id (`<alias>:<stableId>`). */
823
+ stableId: string;
824
+ count: number;
825
+ }
826
+ interface ConsumptionInspection {
827
+ topConsumed: ConsumptionEntry[];
828
+ /**
829
+ * Corpus entries never consumed in the window. ALWAYS [] when the data is not
830
+ * mature (dataMature === false) — the gate suppresses the noisy signal.
831
+ */
832
+ zeroConsumed: string[];
833
+ /** Total corpus entries considered for the zero-consumed denominator. */
834
+ totalEntries: number;
835
+ /** Distinct entries with ≥1 consumption in the window. */
836
+ consumedEntries: number;
837
+ /** Number of metrics windows (rows) that carried ≥1 consumption counter. */
838
+ consumedWindows: number;
839
+ /** Sum of all consumption counts in the window. */
840
+ totalConsumedEvents: number;
841
+ /** True when both maturity axes clear their thresholds. */
842
+ dataMature: boolean;
843
+ windowDays: number;
844
+ }
845
+ /**
846
+ * Aggregate consumption from metrics rows against the canonical corpus id list.
847
+ * Pure — no I/O — so the windowing, prefix parsing, top-N ranking, zero-consumed
848
+ * computation, and the maturity gate are all testable with fixtures.
849
+ *
850
+ * @param rows metrics.jsonl rows (any window/order)
851
+ * @param allQualifiedIds store-qualified ids of the canonical corpus
852
+ * @param now current epoch ms (injected for deterministic windowing)
853
+ */
854
+ declare function aggregateConsumption(rows: MetricsRow[], allQualifiedIds: string[], now: number, config?: Partial<ConsumptionLintConfig>): ConsumptionInspection;
855
+ /**
856
+ * Read metrics.jsonl + the canonical corpus and aggregate consumption. Never
857
+ * throws — readMetrics returns [] on a missing ledger and collectStoreCanonical
858
+ * Entries returns [] when no store is in the read-set.
859
+ *
860
+ * `now` is injectable for deterministic tests.
861
+ */
862
+ declare function inspectConsumption(projectRoot: string, config?: Partial<ConsumptionLintConfig>, now?: number): Promise<ConsumptionInspection>;
863
+
633
864
  type StoredEventLedgerEvent = EventLedgerEvent;
634
865
  type ReadEventLedgerOptions = {
635
866
  event_type?: EventLedgerEvent["event_type"];
@@ -729,6 +960,7 @@ type PlanContextResult = {
729
960
  previous_revision_hash?: string;
730
961
  redirects?: Record<string, string>;
731
962
  related_appended?: Record<string, string>;
963
+ candidate_scores?: Map<string, RecallScore>;
732
964
  /** Internal service→tool signal; stripped before MCP output. */
733
965
  payload_trimmed?: boolean;
734
966
  /** Internal service→tool signal; stripped before MCP output. */
@@ -764,17 +996,21 @@ type RecallInput = PlanContextInput & {
764
996
  */
765
997
  include_related?: boolean;
766
998
  };
999
+ type FullRuleDescription = PlanContextResult["candidates"][number]["description"];
1000
+ type RecallEntryDescription = Pick<FullRuleDescription, "summary" | "must_read_if" | "intent_clues"> & Partial<Pick<FullRuleDescription, "knowledge_type">>;
767
1001
  type RecallEntry = {
768
1002
  stable_id: string;
769
1003
  rank: number;
770
- description: PlanContextResult["candidates"][number]["description"];
1004
+ description: RecallEntryDescription;
771
1005
  read_path?: string;
772
1006
  store?: {
773
1007
  alias: string;
774
1008
  };
775
1009
  body_in_context?: boolean;
1010
+ score?: number;
1011
+ score_breakdown?: RecallScoreBreakdown;
776
1012
  };
777
- type RecallResult = Omit<PlanContextResult, "selection_token" | "payload_trimmed" | "payload_over_budget" | "entries" | "candidates"> & {
1013
+ type RecallResult = Omit<PlanContextResult, "selection_token" | "payload_trimmed" | "payload_over_budget" | "entries" | "candidates" | "candidate_scores"> & {
778
1014
  entries: RecallEntry[];
779
1015
  directive: string;
780
1016
  next_steps?: string[];
@@ -921,4 +1157,4 @@ interface ShutdownHandlerDeps {
921
1157
  */
922
1158
  declare function createShutdownHandler(deps: ShutdownHandlerDeps): () => void;
923
1159
 
924
- export { AGENTS_MD_RESOURCE_URI, type AlwaysActiveBody, type ArchiveHistoryEntry, type ArchiveHistoryReport, COLD_EVAL_RUBRIC, type CiteCoverageReport, type ColdEvalBatch, type ColdEvalCandidate, type ColdEvalVerdict, type ConflictEntry, type ConflictJudge, type ConflictLintReport, type ConflictPair, type ConflictVerdict, DEFAULT_CONFLICT_SIMILARITY_THRESHOLD, type DoctorApplyLintMutation, type DoctorApplyLintMutationKind, type DoctorApplyLintReport, type DoctorFixReport, type DoctorIssue, type DoctorReport, EVENT_LEDGER_PATH, type EnrichDescriptionsCandidate, type EnrichDescriptionsMode, type EnrichDescriptionsReport, FABRIC_SERVER_INSTRUCTIONS, type HistoryAllReport, type HistoryDayRow, type InFlightTracker, type KnowledgeCensus, LEDGER_PATH, LEGACY_LEDGER_PATH, METRICS_LEDGER_PATH, METRIC_COUNTER_NAMES, type MetricCounterName, type MetricsRow, type PlanContextInput, type PlanContextResult, RETIRED_TOKENS, type RecallInput, type RecallResult, type RequirementProfile, type RetiredReferenceHit, type RetiredReferenceInspection, type RetiredToken, type SelectionTokenState, type ShutdownHandlerDeps, type SurfaceVerdict, type UnboundProjectViolation, type WhyNotSurfacedResult, appendEventLedgerEvent, buildAlwaysActiveBodies, buildColdEvalBatch, buildKnowledgeCensus, bumpCounter, contextCache, createFabricServer, createInFlightTracker, createShutdownHandler, detectUnboundProject, drainCounters, enrichDescriptions, explainWhyNotSurfaced, extractKnowledge, findConflictCandidates, flushAndSyncEventLedger, flushMetrics, formatPreexistingRootMessage, getEventLedgerPath, getLedgerPath, getLegacyLedgerPath, getMetricsLedgerPath, inspectRetiredReferences, lintConflicts, loadConflictEntries, pairSimilarity, planContext, readEventLedger, readLedger, readMetrics, readSelectionToken, recall, rehydrateAgentsMetaAt, resolveLedgerPaths, reviewKnowledge, reviewPending, runDoctorApplyLint, runDoctorArchiveHistory, runDoctorCiteCoverage, runDoctorConflictLint, runDoctorFix, runDoctorHistoryAll, runDoctorReport, startMetricsFlush, startRotationTick, startStdioServer, stopMetricsFlush, stopRotationTick };
1160
+ export { AGENTS_MD_RESOURCE_URI, type AlwaysActiveBody, type ArchiveHistoryEntry, type ArchiveHistoryReport, type BacklogAgeMetric, COLD_EVAL_RUBRIC, type CiteCoverageReport, type ColdEvalBatch, type ColdEvalCandidate, type ColdEvalVerdict, type ConflictEntry, type ConflictJudge, type ConflictLintReport, type ConflictPair, type ConflictVerdict, type ConsumptionEntry, type ConsumptionInspection, type ConsumptionLintConfig, DEFAULT_CONFLICT_SIMILARITY_THRESHOLD, type DoctorApplyLintMutation, type DoctorApplyLintMutationKind, type DoctorApplyLintReport, type DoctorFixReport, type DoctorIssue, type DoctorReport, EVENT_LEDGER_PATH, type EnrichDescriptionsCandidate, type EnrichDescriptionsMode, type EnrichDescriptionsReport, FABRIC_SERVER_INSTRUCTIONS, type HistoryAllReport, type HistoryDayRow, type InFlightTracker, type KnowledgeCensus, LEDGER_PATH, LEGACY_LEDGER_PATH, METRICS_LEDGER_PATH, METRIC_COUNTER_NAMES, type MetricCounterName, type MetricsRow, OPTIONAL_EMBED_PACKAGE, type PlanContextInput, type PlanContextResult, type PrecheckResult, RETIRED_TOKENS, type RecallInput, type RecallResult, type RelatedBrokenLink, type RelatedGraphInspection, type RelatedGraphNode, type RelatedHubEntry, type RequirementProfile, type RetiredReferenceHit, type RetiredReferenceInspection, type RetiredToken, type SelectionTokenState, type ShutdownHandlerDeps, type StoreCanonicalEntry, type StoreReachability, type SurfaceVerdict, type UnboundProjectViolation, type WhyNotSurfacedResult, aggregateConsumption, appendEventLedgerEvent, buildAlwaysActiveBodies, buildColdEvalBatch, buildKnowledgeCensus, buildRelatedGraph, bumpCounter, checkBacklogAge, clearPrecheckCache, collectStoreCanonicalEntries, contextCache, createFabricServer, createInFlightTracker, createShutdownHandler, defaultEmbedCacheDir, detectUnboundProject, drainCounters, enrichDescriptions, evaluateStoreDir, explainWhyNotSurfaced, extractKnowledge, findConflictCandidates, flushAndSyncEventLedger, flushMetrics, formatPreexistingRootMessage, getEventLedgerPath, getLedgerPath, getLegacyLedgerPath, getMetricsLedgerPath, inspectConsumption, inspectRelatedGraph, inspectRetiredReferences, isEmbedderResolvable, lintConflicts, loadConflictEntries, loadEmbedder, pairSimilarity, planContext, precheckStoreReachability, readEmbedConfig, readEventLedger, readFusion, readLedger, readMetrics, readSelectionToken, recall, rehydrateAgentsMetaAt, renderBacklogAgeLine, resolveLedgerPaths, reviewKnowledge, reviewPending, runDoctorApplyLint, runDoctorArchiveHistory, runDoctorCiteCoverage, runDoctorConflictLint, runDoctorFix, runDoctorHistoryAll, runDoctorReport, startMetricsFlush, startRotationTick, startStdioServer, stopMetricsFlush, stopRotationTick };