@hivelore/core 0.56.0 → 0.57.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1077,6 +1077,124 @@ 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
+
1162
+ /**
1163
+ * Did the tagged releases actually reach the registry?
1164
+ *
1165
+ * `enforce finish` verified commit, version, tag, push and CI — the whole release chain except its
1166
+ * last link. Three consecutive releases sat tagged and green while npm stayed several versions
1167
+ * behind, because the publish workflow SKIPS (rather than fails) when its token is absent. Nothing
1168
+ * reported it: green CI on an unpublished release looks exactly like a shipped one.
1169
+ *
1170
+ * The severity split is the whole design. `finish` runs BEFORE you publish, so "HEAD's version is
1171
+ * not on the registry yet" is the NORMAL state and can only ever be informational — a gate that
1172
+ * cannot pass in the normal flow is a gate people switch off. What is a real defect is an
1173
+ * INTERMEDIATE tagged version the registry skipped: it was tagged, so it was meant to ship, and it
1174
+ * silently never did.
1175
+ *
1176
+ * Pure: the registry lookup and the tag listing happen in the caller.
1177
+ */
1178
+ type NpmPublicationCode = "npm-published" | "npm-publish-pending" | "npm-releases-skipped" | "npm-publication-unverified";
1179
+ interface NpmPublicationInput {
1180
+ packageName: string;
1181
+ /** Version in the working tree (the lockstep version). */
1182
+ localVersion: string;
1183
+ /** Latest version on the registry, or null when it could not be reached. */
1184
+ publishedVersion: string | null;
1185
+ /** Tagged versions strictly between `publishedVersion` and `localVersion`. */
1186
+ taggedBetween: readonly string[];
1187
+ /** How to publish, injected so core stays free of tooling opinions. */
1188
+ publishHint?: string;
1189
+ }
1190
+ interface NpmPublicationVerdict {
1191
+ code: NpmPublicationCode;
1192
+ severity: "ok" | "info" | "warn";
1193
+ message: string;
1194
+ fix?: string;
1195
+ }
1196
+ declare function classifyNpmPublication(input: NpmPublicationInput): NpmPublicationVerdict;
1197
+
1080
1198
  type MemoryPriority = "must_read" | "useful" | "background";
1081
1199
  /**
1082
1200
  * Normalized priority evidence. A caller fills only the signals it can compute; unknown ones default
@@ -1104,6 +1222,12 @@ interface PrioritySignals {
1104
1222
  moduleOrDomainMatch: boolean;
1105
1223
  /** A memory tag matched a task token. */
1106
1224
  tagTaskMatch: boolean;
1225
+ /**
1226
+ * How much information the matched anchor carries in THIS repo, 0..1 (see `anchor-specificity.ts`).
1227
+ * 1 (the default) means "unknown or highly specific" and preserves the historical behaviour
1228
+ * exactly, so a repo without git history ranks as it always did.
1229
+ */
1230
+ anchorSpecificity?: number;
1107
1231
  }
1108
1232
  declare const DEFAULT_PRIORITY_SIGNALS: PrioritySignals;
1109
1233
  /** Convenience: build a full signal set from a partial one. */
@@ -1893,6 +2017,17 @@ interface HaiveConfig {
1893
2017
  commandSensorUnrunnable?: "warn" | "block";
1894
2018
  /** Require explicit resolution of a diff that demotes, rewrites, or removes a BLOCK sensor. */
1895
2019
  sensorWeakeningGate?: "warn" | "block";
2020
+ /**
2021
+ * Whether `hivelore enforce finish` checks that tagged releases actually reached the npm
2022
+ * registry. Default on; set "off" for repos that publish elsewhere or not at all.
2023
+ *
2024
+ * It never blocks. `finish` runs BEFORE you publish, so "HEAD is not on npm yet" is the normal
2025
+ * state and is reported as info. A tagged version the registry SKIPPED is reported as a warning:
2026
+ * it was tagged, so it was meant to ship. Three consecutive releases were lost that way — the
2027
+ * publish workflow skips rather than fails when NPM_TOKEN is absent, and green CI on an
2028
+ * unpublished release looks exactly like a shipped one.
2029
+ */
2030
+ npmPublishCheck?: "off" | "warn";
1896
2031
  /**
1897
2032
  * How `hivelore enforce finish` reacts to hard failures observed this session that were never
1898
2033
  * captured as a lesson (`mem_tried`):
@@ -3888,4 +4023,4 @@ interface ReviewDraftOptions {
3888
4023
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
3889
4024
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
3890
4025
 
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 };
4026
+ 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, type NpmPublicationCode, type NpmPublicationInput, type NpmPublicationVerdict, 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, classifyNpmPublication, 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,116 @@ 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
+
1465
+ // src/npm-publication.ts
1466
+ function compareVersions(a, b) {
1467
+ const pa = a.split(/[.-]/).map((p) => Number.parseInt(p, 10) || 0);
1468
+ const pb = b.split(/[.-]/).map((p) => Number.parseInt(p, 10) || 0);
1469
+ for (let i = 0; i < Math.max(pa.length, pb.length, 3); i++) {
1470
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
1471
+ if (diff !== 0) return diff;
1472
+ }
1473
+ return 0;
1474
+ }
1475
+ function classifyNpmPublication(input) {
1476
+ const { packageName, localVersion, publishedVersion } = input;
1477
+ const hint = input.publishHint ?? `publish ${packageName} ${localVersion}`;
1478
+ if (!publishedVersion) {
1479
+ return {
1480
+ code: "npm-publication-unverified",
1481
+ severity: "info",
1482
+ message: `Could not reach the registry to check whether ${packageName} ${localVersion} is published.`
1483
+ };
1484
+ }
1485
+ if (compareVersions(publishedVersion, localVersion) >= 0) {
1486
+ return {
1487
+ code: "npm-published",
1488
+ severity: "ok",
1489
+ message: `${packageName} ${publishedVersion} is on npm.`
1490
+ };
1491
+ }
1492
+ const skipped = [...input.taggedBetween].sort(compareVersions);
1493
+ if (skipped.length > 0) {
1494
+ return {
1495
+ code: "npm-releases-skipped",
1496
+ severity: "warn",
1497
+ message: `${skipped.length} tagged release(s) never reached npm \u2014 ${packageName} is on ${publishedVersion}: ${skipped.map((v) => `v${v}`).join(", ")}.`,
1498
+ fix: `Registry versions are not cumulative, so publishing the newest is enough: ${hint}. If the release workflow keeps skipping, its publish credentials are missing.`
1499
+ };
1500
+ }
1501
+ return {
1502
+ code: "npm-publish-pending",
1503
+ severity: "info",
1504
+ message: `${packageName} ${localVersion} is not on npm yet (registry has ${publishedVersion}) \u2014 expected at this point; publish is the next step.`,
1505
+ fix: hint
1506
+ };
1507
+ }
1508
+
1399
1509
  // src/priority.ts
1400
1510
  var DEFAULT_PRIORITY_SIGNALS = {
1401
1511
  type: "",
@@ -1407,7 +1517,8 @@ var DEFAULT_PRIORITY_SIGNALS = {
1407
1517
  strongSemantic: false,
1408
1518
  usefulSemantic: false,
1409
1519
  moduleOrDomainMatch: false,
1410
- tagTaskMatch: false
1520
+ tagTaskMatch: false,
1521
+ anchorSpecificity: DEFAULT_SPECIFICITY
1411
1522
  };
1412
1523
  function prioritySignals(partial) {
1413
1524
  return { ...DEFAULT_PRIORITY_SIGNALS, ...partial };
@@ -1415,9 +1526,13 @@ function prioritySignals(partial) {
1415
1526
  function classifyMemoryPriority(signals) {
1416
1527
  const isNegative = signals.type === "attempt";
1417
1528
  const isSkill2 = signals.type === "skill";
1418
- if (signals.requiresHumanApproval || signals.directAnchor || signals.directSymbol || isNegative && (signals.exactTaskMatch || signals.strongSemantic) || isSkill2 && (signals.exactTaskMatch || signals.strongSemantic)) {
1529
+ const weakAnchor = signals.directAnchor && isWeakAnchor(signals.anchorSpecificity ?? DEFAULT_SPECIFICITY);
1530
+ const strongAnchor = signals.directAnchor && !weakAnchor;
1531
+ const corroborated = signals.strongSemantic || signals.directSymbol;
1532
+ if (signals.requiresHumanApproval || strongAnchor || signals.directSymbol || weakAnchor && corroborated || isNegative && (signals.exactTaskMatch || signals.strongSemantic) || isSkill2 && (signals.exactTaskMatch || signals.strongSemantic)) {
1419
1533
  return "must_read";
1420
1534
  }
1535
+ if (weakAnchor) return "useful";
1421
1536
  if (isStackPackSeed({ tags: signals.tags }) || isEnvWorkaroundMemory({ tags: signals.tags })) {
1422
1537
  if (isStackPackSeed({ tags: signals.tags }) && (signals.exactTaskMatch || signals.strongSemantic)) {
1423
1538
  return "useful";
@@ -7153,6 +7268,7 @@ export {
7153
7268
  DEFAULT_DORMANT_DAYS,
7154
7269
  DEFAULT_POSTURE,
7155
7270
  DEFAULT_PRIORITY_SIGNALS,
7271
+ DEFAULT_SPECIFICITY,
7156
7272
  ENV_WORKAROUND_TAGS,
7157
7273
  FRICTION_FIELD_MAX,
7158
7274
  FRICTION_LOG_FILE,
@@ -7189,6 +7305,7 @@ export {
7189
7305
  USAGE_FILE,
7190
7306
  USAGE_LOG_DIR,
7191
7307
  USAGE_LOG_FILE,
7308
+ WEAK_ANCHOR_CHURN_RATIO,
7192
7309
  addedLineNumbersFromDiff,
7193
7310
  addedLinesFromDiff,
7194
7311
  aggregateRetrieval,
@@ -7196,6 +7313,7 @@ export {
7196
7313
  aggregateUsage,
7197
7314
  allocateBudget,
7198
7315
  anchorMatchesComponent,
7316
+ anchorSpecificity,
7199
7317
  antiPatternGateParams,
7200
7318
  appendEvalHistory,
7201
7319
  appendFrictionReport,
@@ -7211,6 +7329,7 @@ export {
7211
7329
  assessBootstrapState,
7212
7330
  assessScaffoldLoop,
7213
7331
  assessSensorHealth,
7332
+ auditAnchorSpecificity,
7214
7333
  bridgeMemorySummary,
7215
7334
  briefingMarkerPath,
7216
7335
  briefingMarkersDir,
@@ -7226,7 +7345,9 @@ export {
7226
7345
  buildProposeCommand,
7227
7346
  buildReport,
7228
7347
  bumpRead,
7348
+ churnForAnchors,
7229
7349
  classifyMemoryPriority,
7350
+ classifyNpmPublication,
7230
7351
  codeMapContentHash,
7231
7352
  codeMapPath,
7232
7353
  collectTimelineEntries,
@@ -7319,6 +7440,7 @@ export {
7319
7440
  isStackPackSeed,
7320
7441
  isStylisticRule,
7321
7442
  isTemplateProjectContext,
7443
+ isWeakAnchor,
7322
7444
  judgeProposedSensor,
7323
7445
  lessonShortName,
7324
7446
  listMarkdownFilesRecursive,
@@ -7345,6 +7467,7 @@ export {
7345
7467
  mineSensorSeedFromDiff,
7346
7468
  moduleNameOf,
7347
7469
  newMemoryId,
7470
+ normalizeChurnPath,
7348
7471
  normalizeFindingSeverity,
7349
7472
  normalizeFramework,
7350
7473
  normalizeFrictionSummary,