@hivelore/core 0.56.0 → 0.57.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.
package/dist/index.d.ts CHANGED
@@ -1077,6 +1077,88 @@ declare function decideVerdict(input: GateVerdictInput): GateVerdict;
1077
1077
  */
1078
1078
  declare function buildBaselineHealthFinding(findings: GateFinding[], health: BaselineHealth, shouldBlock: boolean): GateFinding | null;
1079
1079
 
1080
+ /**
1081
+ * How much does an anchor actually TELL US?
1082
+ *
1083
+ * A memory anchored to a file matched by the change is treated as `must_read` — the strongest
1084
+ * ranking signal there is, ahead of anything semantic. That is right when the anchor is specific.
1085
+ * It is wrong when the anchor is a file every commit touches.
1086
+ *
1087
+ * Measured on this repository (60 commits, 116 anchored memories):
1088
+ *
1089
+ * - the MEDIAN memory claims relevance on 12 of 60 commits (20%)
1090
+ * - the p90 memory claims 36 of 60 (60%)
1091
+ * - the worst claim 37–42, and every one of them is anchored to a `package.json`
1092
+ *
1093
+ * A version bump touches `package.json`, so a lesson about cross-package dependency ranges declares
1094
+ * itself `must_read` on every release commit. On a typical commit here, ~34 memories all claimed the
1095
+ * top rank at once and the briefing had 8 slots: recall@8 was pinned near its arithmetic ceiling,
1096
+ * and the slots went to whichever plausible memory sorted first rather than to the one that mattered.
1097
+ * That is the mechanism behind a field report scoring briefing usefulness 30/100 while the eval
1098
+ * harness reported 98% recall — the eval asks "given a query written to find memory X, does X
1099
+ * surface?", which never exposes anchors competing with each other.
1100
+ *
1101
+ * The correction is the oldest one in information retrieval: weight a match by how rare it is.
1102
+ * An anchor on a file touched by 3% of commits is strong evidence; the same match on a file touched
1103
+ * by 60% of them is nearly none, and must be corroborated before it outranks everything else.
1104
+ *
1105
+ * Pure: churn is measured elsewhere (git), scored here.
1106
+ */
1107
+ /** How many of the sampled commits touched each project-relative path. */
1108
+ type AnchorChurn = ReadonlyMap<string, number>;
1109
+ /**
1110
+ * Anchors touched by more than this share of recent commits carry too little information to
1111
+ * promote a memory on their own. 0.35 keeps genuinely component-scoped anchors (a module a third of
1112
+ * the work touches is still a real signal) while demoting repo-wide files like `package.json`,
1113
+ * lockfiles and CI config.
1114
+ */
1115
+ declare const WEAK_ANCHOR_CHURN_RATIO = 0.35;
1116
+ /** Unknown churn must never penalise: a repo with no git history ranks exactly as it did before. */
1117
+ declare const DEFAULT_SPECIFICITY = 1;
1118
+ /**
1119
+ * Specificity of the BEST anchor that matched, in 0..1.
1120
+ *
1121
+ * 1 = this path is barely ever touched, so matching it is strong evidence.
1122
+ * 0 = every commit touches it, so matching it says nothing.
1123
+ *
1124
+ * The best (rarest) matching anchor wins: a memory anchored to both `package.json` and one precise
1125
+ * file is precise when the precise file is what changed.
1126
+ */
1127
+ declare function anchorSpecificity(matchedPaths: readonly string[], churn: AnchorChurn, totalCommits: number): number;
1128
+ /** True when this anchor is too common in this repo to promote a memory by itself. */
1129
+ declare function isWeakAnchor(specificity: number): boolean;
1130
+ declare function normalizeChurnPath(value: string): string;
1131
+ /**
1132
+ * Roll per-file commit counts up to the anchor paths a memory actually declares, so a directory or
1133
+ * glob anchor inherits the churn of everything under it. Without this, `packages/cli/` would look
1134
+ * unknown (no commit touches a directory) and silently keep the strong default.
1135
+ */
1136
+ declare function churnForAnchors(anchorPaths: readonly string[], fileChurn: AnchorChurn): AnchorChurn;
1137
+ interface AnchorAuditRow {
1138
+ id: string;
1139
+ /** Specificity of this memory's most discriminating anchor, 0..1. */
1140
+ specificity: number;
1141
+ /** The anchors that make it broad, with the share of commits touching each. */
1142
+ broad: Array<{
1143
+ path: string;
1144
+ ratio: number;
1145
+ }>;
1146
+ }
1147
+ /**
1148
+ * Which memories claim relevance on nearly every change?
1149
+ *
1150
+ * A memory anchored only to high-churn files is not wrong — the lesson really is about that file —
1151
+ * but it cannot help a briefing choose. It occupies a slot on every commit and displaces the lesson
1152
+ * that is actually about the work in hand. Surfacing the list turns an invisible ranking problem
1153
+ * into a corpus-hygiene task with an obvious fix: add the precise path the lesson is really about.
1154
+ *
1155
+ * Pure. Sorted worst-first so a report can take the head.
1156
+ */
1157
+ declare function auditAnchorSpecificity(memories: ReadonlyArray<{
1158
+ id: string;
1159
+ anchorPaths: readonly string[];
1160
+ }>, fileChurn: AnchorChurn, totalCommits: number): AnchorAuditRow[];
1161
+
1080
1162
  type MemoryPriority = "must_read" | "useful" | "background";
1081
1163
  /**
1082
1164
  * Normalized priority evidence. A caller fills only the signals it can compute; unknown ones default
@@ -1104,6 +1186,12 @@ interface PrioritySignals {
1104
1186
  moduleOrDomainMatch: boolean;
1105
1187
  /** A memory tag matched a task token. */
1106
1188
  tagTaskMatch: boolean;
1189
+ /**
1190
+ * How much information the matched anchor carries in THIS repo, 0..1 (see `anchor-specificity.ts`).
1191
+ * 1 (the default) means "unknown or highly specific" and preserves the historical behaviour
1192
+ * exactly, so a repo without git history ranks as it always did.
1193
+ */
1194
+ anchorSpecificity?: number;
1107
1195
  }
1108
1196
  declare const DEFAULT_PRIORITY_SIGNALS: PrioritySignals;
1109
1197
  /** Convenience: build a full signal set from a partial one. */
@@ -3888,4 +3976,4 @@ interface ReviewDraftOptions {
3888
3976
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
3889
3977
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
3890
3978
 
3891
- export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, AnchorSchema, type AntiPatternGate, type AppendFrictionInput, type AppendFrictionResult, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BaselineHealth, type BehaviourCoverageInput, type BehaviourCoverageMetrics, type BehaviourOracleInfo, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, CONTENT_CATCH_CODES, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractCheck, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_POSTURE, DEFAULT_PRIORITY_SIGNALS, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DistilledFailureLesson, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, FRICTION_FIELD_MAX, FRICTION_LOG_FILE, FRICTION_STATE_FILE, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, type FrictionGroup, type FrictionKind, type FrictionReport, type FrictionState, type FrictionStateEntry, type FrictionStatus, GATE_REMINDER_WINDOW_MS, GUESSABLE_THRESHOLD, type GateFinding, type GateMissProposal, type GatePolicy, type GatePolicyInput, type GatePosture, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateSeverity, type GateStage, type GateTuningSuggestion, type GateVerdict, type GateVerdictInput, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, HIVELORE_ATTRIBUTION, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type IncidentHints, type InvalidMemoryFile, LEGACY_CONFIG_FILE, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, PREVENTION_DEBOUNCE_MS, PREVENTION_RECEIPT_MARKER, PROCESS_GATE_CODES, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, type PreventionCommentFinding, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedEvalSpec, type ProposedSensorVerdict, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, SETUP_GATE_CODES, STACK_PACK_TAG, type ScaffoldLoopGap, type ScaffoldOptions, type ScaffoldStyle, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, anchorMatchesComponent, antiPatternGateParams, appendEvalHistory, appendFrictionReport, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildBaselineHealthFinding, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, classifyMemoryPriority, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeBaselineHealth, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, decideVerdict, dedupeRefusals, deriveConfidence, deriveMainAreas, describePosture, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, explainSensorRejection, extractActionsBriefBody, extractCorrectApproachExamples, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, formatFrictionIssue, frictionFingerprint, frictionLogPath, frictionStatePath, gatePassedShas, generateBridges, getUsage, globToRegExp, groupFriction, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isHarnessErrorOutput, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadFrictionState, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, mineSensorSeedFromDiff, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeFramework, normalizeFrictionSummary, normalizeKind, normalizeScaffoldStyle, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readFrictionReports, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordGateReminder, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionComment, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveGatePolicy, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runValidationContract, runtimeJournalPath, saveCodeMap, saveConfig, saveFrictionState, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeCodeMap, serializeMemory, setFrictionStatus, shouldExpandGateReminder, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
3979
+ export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, type AnchorAuditRow, type AnchorChurn, AnchorSchema, type AntiPatternGate, type AppendFrictionInput, type AppendFrictionResult, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BaselineHealth, type BehaviourCoverageInput, type BehaviourCoverageMetrics, type BehaviourOracleInfo, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, CONTENT_CATCH_CODES, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractCheck, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_POSTURE, DEFAULT_PRIORITY_SIGNALS, DEFAULT_SPECIFICITY, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DistilledFailureLesson, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, FRICTION_FIELD_MAX, FRICTION_LOG_FILE, FRICTION_STATE_FILE, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, type FrictionGroup, type FrictionKind, type FrictionReport, type FrictionState, type FrictionStateEntry, type FrictionStatus, GATE_REMINDER_WINDOW_MS, GUESSABLE_THRESHOLD, type GateFinding, type GateMissProposal, type GatePolicy, type GatePolicyInput, type GatePosture, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateSeverity, type GateStage, type GateTuningSuggestion, type GateVerdict, type GateVerdictInput, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, HIVELORE_ATTRIBUTION, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type IncidentHints, type InvalidMemoryFile, LEGACY_CONFIG_FILE, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, PREVENTION_DEBOUNCE_MS, PREVENTION_RECEIPT_MARKER, PROCESS_GATE_CODES, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, type PreventionCommentFinding, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedEvalSpec, type ProposedSensorVerdict, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, SETUP_GATE_CODES, STACK_PACK_TAG, type ScaffoldLoopGap, type ScaffoldOptions, type ScaffoldStyle, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, WEAK_ANCHOR_CHURN_RATIO, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, anchorMatchesComponent, anchorSpecificity, antiPatternGateParams, appendEvalHistory, appendFrictionReport, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, auditAnchorSpecificity, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildBaselineHealthFinding, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, churnForAnchors, classifyMemoryPriority, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeBaselineHealth, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, decideVerdict, dedupeRefusals, deriveConfidence, deriveMainAreas, describePosture, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, explainSensorRejection, extractActionsBriefBody, extractCorrectApproachExamples, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, formatFrictionIssue, frictionFingerprint, frictionLogPath, frictionStatePath, gatePassedShas, generateBridges, getUsage, globToRegExp, groupFriction, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isHarnessErrorOutput, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, isWeakAnchor, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadFrictionState, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, mineSensorSeedFromDiff, moduleNameOf, newMemoryId, normalizeChurnPath, normalizeFindingSeverity, normalizeFramework, normalizeFrictionSummary, normalizeKind, normalizeScaffoldStyle, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readFrictionReports, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordGateReminder, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionComment, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveGatePolicy, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runValidationContract, runtimeJournalPath, saveCodeMap, saveConfig, saveFrictionState, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeCodeMap, serializeMemory, setFrictionStatus, shouldExpandGateReminder, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
package/dist/index.js CHANGED
@@ -1396,6 +1396,72 @@ function buildBaselineHealthFinding(findings, health, shouldBlock) {
1396
1396
  };
1397
1397
  }
1398
1398
 
1399
+ // src/anchor-specificity.ts
1400
+ var WEAK_ANCHOR_CHURN_RATIO = 0.35;
1401
+ var DEFAULT_SPECIFICITY = 1;
1402
+ function anchorSpecificity(matchedPaths, churn, totalCommits) {
1403
+ if (totalCommits <= 0 || matchedPaths.length === 0) return DEFAULT_SPECIFICITY;
1404
+ let best = 0;
1405
+ let sawKnown = false;
1406
+ for (const path22 of matchedPaths) {
1407
+ const touched = churn.get(normalizeChurnPath(path22));
1408
+ if (touched === void 0) continue;
1409
+ sawKnown = true;
1410
+ best = Math.max(best, 1 - Math.min(1, touched / totalCommits));
1411
+ }
1412
+ return sawKnown ? best : DEFAULT_SPECIFICITY;
1413
+ }
1414
+ function isWeakAnchor(specificity) {
1415
+ return specificity < 1 - WEAK_ANCHOR_CHURN_RATIO;
1416
+ }
1417
+ function normalizeChurnPath(value) {
1418
+ return value.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
1419
+ }
1420
+ function churnForAnchors(anchorPaths, fileChurn) {
1421
+ const out = /* @__PURE__ */ new Map();
1422
+ for (const raw of anchorPaths) {
1423
+ const anchor = normalizeChurnPath(raw);
1424
+ const direct = fileChurn.get(anchor);
1425
+ if (direct !== void 0) {
1426
+ out.set(anchor, direct);
1427
+ continue;
1428
+ }
1429
+ let max = 0;
1430
+ let matched = false;
1431
+ for (const [file, count] of fileChurn) {
1432
+ if (!pathCoveredByAnchor(anchor, file)) continue;
1433
+ matched = true;
1434
+ max = Math.max(max, count);
1435
+ }
1436
+ if (matched) out.set(anchor, max);
1437
+ }
1438
+ return out;
1439
+ }
1440
+ function pathCoveredByAnchor(anchor, file) {
1441
+ if (anchor === file) return true;
1442
+ if (!anchor.includes("*")) return file.startsWith(`${anchor}/`);
1443
+ const pattern = anchor.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0").replace(/\*/g, "[^/]*").replace(//g, ".*");
1444
+ try {
1445
+ return new RegExp(`^${pattern}$`).test(file);
1446
+ } catch {
1447
+ return false;
1448
+ }
1449
+ }
1450
+ function auditAnchorSpecificity(memories, fileChurn, totalCommits) {
1451
+ if (totalCommits <= 0) return [];
1452
+ const rows = [];
1453
+ for (const memory of memories) {
1454
+ if (memory.anchorPaths.length === 0) continue;
1455
+ const rolled = churnForAnchors(memory.anchorPaths, fileChurn);
1456
+ if (rolled.size === 0) continue;
1457
+ const specificity = anchorSpecificity(memory.anchorPaths, rolled, totalCommits);
1458
+ if (!isWeakAnchor(specificity)) continue;
1459
+ const broad = [...rolled].map(([path22, count]) => ({ path: path22, ratio: count / totalCommits })).filter((entry) => entry.ratio > WEAK_ANCHOR_CHURN_RATIO).sort((a, b) => b.ratio - a.ratio);
1460
+ rows.push({ id: memory.id, specificity, broad });
1461
+ }
1462
+ return rows.sort((a, b) => a.specificity - b.specificity);
1463
+ }
1464
+
1399
1465
  // src/priority.ts
1400
1466
  var DEFAULT_PRIORITY_SIGNALS = {
1401
1467
  type: "",
@@ -1407,7 +1473,8 @@ var DEFAULT_PRIORITY_SIGNALS = {
1407
1473
  strongSemantic: false,
1408
1474
  usefulSemantic: false,
1409
1475
  moduleOrDomainMatch: false,
1410
- tagTaskMatch: false
1476
+ tagTaskMatch: false,
1477
+ anchorSpecificity: DEFAULT_SPECIFICITY
1411
1478
  };
1412
1479
  function prioritySignals(partial) {
1413
1480
  return { ...DEFAULT_PRIORITY_SIGNALS, ...partial };
@@ -1415,9 +1482,13 @@ function prioritySignals(partial) {
1415
1482
  function classifyMemoryPriority(signals) {
1416
1483
  const isNegative = signals.type === "attempt";
1417
1484
  const isSkill2 = signals.type === "skill";
1418
- if (signals.requiresHumanApproval || signals.directAnchor || signals.directSymbol || isNegative && (signals.exactTaskMatch || signals.strongSemantic) || isSkill2 && (signals.exactTaskMatch || signals.strongSemantic)) {
1485
+ const weakAnchor = signals.directAnchor && isWeakAnchor(signals.anchorSpecificity ?? DEFAULT_SPECIFICITY);
1486
+ const strongAnchor = signals.directAnchor && !weakAnchor;
1487
+ const corroborated = signals.strongSemantic || signals.directSymbol;
1488
+ if (signals.requiresHumanApproval || strongAnchor || signals.directSymbol || weakAnchor && corroborated || isNegative && (signals.exactTaskMatch || signals.strongSemantic) || isSkill2 && (signals.exactTaskMatch || signals.strongSemantic)) {
1419
1489
  return "must_read";
1420
1490
  }
1491
+ if (weakAnchor) return "useful";
1421
1492
  if (isStackPackSeed({ tags: signals.tags }) || isEnvWorkaroundMemory({ tags: signals.tags })) {
1422
1493
  if (isStackPackSeed({ tags: signals.tags }) && (signals.exactTaskMatch || signals.strongSemantic)) {
1423
1494
  return "useful";
@@ -7153,6 +7224,7 @@ export {
7153
7224
  DEFAULT_DORMANT_DAYS,
7154
7225
  DEFAULT_POSTURE,
7155
7226
  DEFAULT_PRIORITY_SIGNALS,
7227
+ DEFAULT_SPECIFICITY,
7156
7228
  ENV_WORKAROUND_TAGS,
7157
7229
  FRICTION_FIELD_MAX,
7158
7230
  FRICTION_LOG_FILE,
@@ -7189,6 +7261,7 @@ export {
7189
7261
  USAGE_FILE,
7190
7262
  USAGE_LOG_DIR,
7191
7263
  USAGE_LOG_FILE,
7264
+ WEAK_ANCHOR_CHURN_RATIO,
7192
7265
  addedLineNumbersFromDiff,
7193
7266
  addedLinesFromDiff,
7194
7267
  aggregateRetrieval,
@@ -7196,6 +7269,7 @@ export {
7196
7269
  aggregateUsage,
7197
7270
  allocateBudget,
7198
7271
  anchorMatchesComponent,
7272
+ anchorSpecificity,
7199
7273
  antiPatternGateParams,
7200
7274
  appendEvalHistory,
7201
7275
  appendFrictionReport,
@@ -7211,6 +7285,7 @@ export {
7211
7285
  assessBootstrapState,
7212
7286
  assessScaffoldLoop,
7213
7287
  assessSensorHealth,
7288
+ auditAnchorSpecificity,
7214
7289
  bridgeMemorySummary,
7215
7290
  briefingMarkerPath,
7216
7291
  briefingMarkersDir,
@@ -7226,6 +7301,7 @@ export {
7226
7301
  buildProposeCommand,
7227
7302
  buildReport,
7228
7303
  bumpRead,
7304
+ churnForAnchors,
7229
7305
  classifyMemoryPriority,
7230
7306
  codeMapContentHash,
7231
7307
  codeMapPath,
@@ -7319,6 +7395,7 @@ export {
7319
7395
  isStackPackSeed,
7320
7396
  isStylisticRule,
7321
7397
  isTemplateProjectContext,
7398
+ isWeakAnchor,
7322
7399
  judgeProposedSensor,
7323
7400
  lessonShortName,
7324
7401
  listMarkdownFilesRecursive,
@@ -7345,6 +7422,7 @@ export {
7345
7422
  mineSensorSeedFromDiff,
7346
7423
  moduleNameOf,
7347
7424
  newMemoryId,
7425
+ normalizeChurnPath,
7348
7426
  normalizeFindingSeverity,
7349
7427
  normalizeFramework,
7350
7428
  normalizeFrictionSummary,