@hivelore/core 0.57.6 → 0.58.0

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
@@ -1600,6 +1600,23 @@ declare function pathsOverlap(a: string, b: string): boolean;
1600
1600
  declare function memoryMatchesAnchorPaths(memory: LoadedMemory["memory"], inputPaths: string[]): boolean;
1601
1601
  declare function isGlobPath(p: string): boolean;
1602
1602
  declare function globToRegExp(pattern: string): RegExp;
1603
+ /** Below this many semantic hits a distribution is not meaningful — behave exactly as before. */
1604
+ declare const ADAPTIVE_FLOOR_MIN_SAMPLES = 12;
1605
+ /**
1606
+ * A distribution-aware floor for semantic-only hits.
1607
+ *
1608
+ * Field report 2026-09-01 §4.1: on a broad corpus (~40 memories) cosine scores compress into a
1609
+ * narrow band (everything > 0.55), so an ABSOLUTE `min_semantic_score` sorts nothing — the same
1610
+ * three or four unrelated memories surface for every task at ~0.6. The fix the report asks for is
1611
+ * to judge a score against the corpus distribution rather than in the absolute.
1612
+ *
1613
+ * This returns `mean + halfStdDev`, which self-adjusts: on a compressed distribution it rises toward
1614
+ * the mean and trims the undifferentiated mass; on a discriminating one it sits between the winner
1615
+ * and the noise. It NEVER drops below the caller's explicit floor, NEVER excludes the single top
1616
+ * hit, and does nothing at all below {@link ADAPTIVE_FLOOR_MIN_SAMPLES} samples (so small corpora —
1617
+ * and the retrieval eval — are unaffected). Pure.
1618
+ */
1619
+ declare function adaptiveSemanticFloor(scores: number[], explicitFloor?: number): number;
1603
1620
  declare function relPathFrom(root: string, abs: string): string;
1604
1621
 
1605
1622
  /**
@@ -2726,6 +2743,11 @@ declare const SENSOR_ABSENT_LOOKBACK = 2;
2726
2743
  * (wrong kind, missing/invalid pattern) so callers can skip it safely.
2727
2744
  */
2728
2745
  declare function compileRegexSensor(sensor: Sensor): RegExp | null;
2746
+ /**
2747
+ * Blank comment spans in scannable text so a sensor's regex matches CODE, not the prose that
2748
+ * documents it. Returns `content` unchanged for unknown file types. Pure.
2749
+ */
2750
+ declare function stripCommentsForScan(content: string, path: string): string;
2729
2751
  /**
2730
2752
  * Run a single regex sensor over one target. Returns the first matching line as a hit,
2731
2753
  * or null. Deterministic and side-effect-free.
@@ -3976,6 +3998,17 @@ declare function isAutoRecap(body: string): boolean;
3976
3998
  * returned unchanged.
3977
3999
  */
3978
4000
  declare function compactAutoRecapBody(body: string, maxChars?: number): string;
4001
+ /**
4002
+ * The excerpt of a recap that belongs at the TOP of every briefing: only what the next session must
4003
+ * act on — the goal in one line and the next steps.
4004
+ *
4005
+ * A full human/post_task recap (goal + accomplished + discoveries + next steps) ran ~3000 tokens and
4006
+ * was re-emitted at the head of EVERY briefing, so a session with five briefings paid five times to
4007
+ * re-read a wall the agent had just written (field report 2026-09-01 §5.6). The full body stays in
4008
+ * the corpus — reachable with `mem_get <id>` — this only trims what the briefing head carries. Auto
4009
+ * recaps still route through {@link compactAutoRecapBody}. Pure.
4010
+ */
4011
+ declare function recapBriefingExcerpt(body: string, maxChars?: number): string;
3979
4012
 
3980
4013
  /** Filename of the ephemeral handoff at the repo root. */
3981
4014
  declare const HANDOFF_FILENAME = "NEXT.md";
@@ -4144,4 +4177,4 @@ interface ReviewDraftOptions {
4144
4177
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
4145
4178
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
4146
4179
 
4147
- 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, type GithubReleaseCode, type GithubReleaseInput, type GithubReleaseVerdict, 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, changedPathsFromDiff, churnForAnchors, classifyGithubRelease, classifyMemoryPriority, classifyNpmPublication, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compareVersions, 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, runPresenceSensors, 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 };
4180
+ export { ADAPTIVE_FLOOR_MIN_SAMPLES, 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, type GithubReleaseCode, type GithubReleaseInput, type GithubReleaseVerdict, 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, adaptiveSemanticFloor, 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, changedPathsFromDiff, churnForAnchors, classifyGithubRelease, classifyMemoryPriority, classifyNpmPublication, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compareVersions, 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, recapBriefingExcerpt, recommendFeedbackAdjustment, recordApplied, recordGateReminder, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionComment, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveGatePolicy, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runPresenceSensors, 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, stripCommentsForScan, 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
@@ -517,6 +517,22 @@ function globLiteralPrefix(pattern) {
517
517
  const slash = norm.slice(0, firstGlob).lastIndexOf("/");
518
518
  return slash < 0 ? "" : norm.slice(0, slash);
519
519
  }
520
+ var ADAPTIVE_FLOOR_MIN_SAMPLES = 12;
521
+ function adaptiveSemanticFloor(scores, explicitFloor = 0) {
522
+ if (scores.length < ADAPTIVE_FLOOR_MIN_SAMPLES) return explicitFloor;
523
+ let sum = 0;
524
+ let top = -Infinity;
525
+ for (const s of scores) {
526
+ sum += s;
527
+ if (s > top) top = s;
528
+ }
529
+ const mean = sum / scores.length;
530
+ let variance = 0;
531
+ for (const s of scores) variance += (s - mean) ** 2;
532
+ const std = Math.sqrt(variance / scores.length);
533
+ const distributional = mean + 0.5 * std;
534
+ return Math.max(explicitFloor, Math.min(distributional, top - 1e-6));
535
+ }
520
536
  function relPathFrom(root, abs) {
521
537
  return path3.relative(root, abs).replace(/\\/g, "/");
522
538
  }
@@ -1096,6 +1112,7 @@ function renderPreventionReceiptShare(receipt) {
1096
1112
  var PREVENTION_RECEIPT_MARKER = "<!-- haive:prevention-receipt -->";
1097
1113
  function renderPreventionComment(receipt, findings = []) {
1098
1114
  const fired = findings.filter((f) => f.code === "sensor-block" || f.code === "sensor-warn");
1115
+ if (fired.length === 0 && receipt.total === 0) return "";
1099
1116
  const lines = [PREVENTION_RECEIPT_MARKER, "", "## Hivelore prevention receipt", ""];
1100
1117
  if (fired.length === 0) {
1101
1118
  lines.push("No documented sensor fired on this PR.", "");
@@ -1803,7 +1820,7 @@ function generateBridges(memories, sensors, opts) {
1803
1820
 
1804
1821
  // src/sensors.ts
1805
1822
  function sensorPatternBrittleness(pattern) {
1806
- const literal = pattern.replace(/\\[a-zA-Z]/g, " ").replace(/\[[^\]]*\]/g, " ").replace(/\{[^}]*\}/g, " ").replace(/\b\d{1,3}(?:\s*\\?\.\s*\d{1,3}){2,3}\b/g, " ");
1823
+ const literal = pattern.replace(/(?:\/|%|\\[/*]|\[[^\]]*[/*][^\]]*\])[^\d]{0,4}\d{3,}/g, " ").replace(/\\[a-zA-Z]/g, " ").replace(/\[[^\]]*\]/g, " ").replace(/\{[^}]*\}/g, " ").replace(/\b\d{1,3}(?:\s*\\?\.\s*\d{1,3}){2,3}\b/g, " ");
1807
1824
  const range = literal.match(/\d{2,}\s*-\s*\d{2,}/);
1808
1825
  if (range) return `hardcoded line/number range "${range[0].replace(/\s+/g, "")}" \u2014 rots when code shifts`;
1809
1826
  const numeric = literal.match(/\d{3,}/);
@@ -1846,20 +1863,137 @@ function compileAbsentRegex(sensor) {
1846
1863
  return null;
1847
1864
  }
1848
1865
  }
1866
+ var C_FAMILY = { line: ["//"], block: ["/*", "*/"], starContinuation: true };
1867
+ var HASH_FAMILY = { line: ["#"], block: null, starContinuation: false };
1868
+ var CSS_FAMILY = { line: [], block: ["/*", "*/"], starContinuation: true };
1869
+ var SCSS_FAMILY = { line: ["//"], block: ["/*", "*/"], starContinuation: true };
1870
+ var SQL_FAMILY = { line: ["--"], block: ["/*", "*/"], starContinuation: false };
1871
+ var HTML_FAMILY = { line: [], block: ["<!--", "-->"], starContinuation: false };
1872
+ var COMMENT_SYNTAX_BY_EXT = {
1873
+ ts: C_FAMILY,
1874
+ tsx: C_FAMILY,
1875
+ js: C_FAMILY,
1876
+ jsx: C_FAMILY,
1877
+ mjs: C_FAMILY,
1878
+ cjs: C_FAMILY,
1879
+ java: C_FAMILY,
1880
+ c: C_FAMILY,
1881
+ h: C_FAMILY,
1882
+ cpp: C_FAMILY,
1883
+ hpp: C_FAMILY,
1884
+ cc: C_FAMILY,
1885
+ hh: C_FAMILY,
1886
+ cs: C_FAMILY,
1887
+ go: C_FAMILY,
1888
+ rs: C_FAMILY,
1889
+ kt: C_FAMILY,
1890
+ kts: C_FAMILY,
1891
+ swift: C_FAMILY,
1892
+ scala: C_FAMILY,
1893
+ php: C_FAMILY,
1894
+ dart: C_FAMILY,
1895
+ m: C_FAMILY,
1896
+ mm: C_FAMILY,
1897
+ py: HASH_FAMILY,
1898
+ rb: HASH_FAMILY,
1899
+ sh: HASH_FAMILY,
1900
+ bash: HASH_FAMILY,
1901
+ zsh: HASH_FAMILY,
1902
+ yml: HASH_FAMILY,
1903
+ yaml: HASH_FAMILY,
1904
+ toml: HASH_FAMILY,
1905
+ properties: HASH_FAMILY,
1906
+ conf: HASH_FAMILY,
1907
+ cfg: HASH_FAMILY,
1908
+ pl: HASH_FAMILY,
1909
+ pm: HASH_FAMILY,
1910
+ r: HASH_FAMILY,
1911
+ css: CSS_FAMILY,
1912
+ scss: SCSS_FAMILY,
1913
+ less: SCSS_FAMILY,
1914
+ sql: SQL_FAMILY,
1915
+ html: HTML_FAMILY,
1916
+ htm: HTML_FAMILY,
1917
+ xml: HTML_FAMILY,
1918
+ vue: HTML_FAMILY,
1919
+ svelte: HTML_FAMILY,
1920
+ md: HTML_FAMILY,
1921
+ markdown: HTML_FAMILY
1922
+ };
1923
+ function commentSyntaxForPath(path22) {
1924
+ const base = path22.split(/[\\/]/).pop() ?? "";
1925
+ const dot = base.lastIndexOf(".");
1926
+ if (dot < 0) return null;
1927
+ return COMMENT_SYNTAX_BY_EXT[base.slice(dot + 1).toLowerCase()] ?? null;
1928
+ }
1929
+ function blankCommentsOnLine(line, syntax) {
1930
+ if (syntax.starContinuation && /^\*(\s|\/|$)/.test(line.trimStart())) {
1931
+ return " ".repeat(line.length);
1932
+ }
1933
+ let out = "";
1934
+ let stringDelim = null;
1935
+ for (let i = 0; i < line.length; i++) {
1936
+ const ch = line[i];
1937
+ if (stringDelim) {
1938
+ out += ch;
1939
+ if (ch === "\\" && i + 1 < line.length) {
1940
+ out += line[i + 1];
1941
+ i++;
1942
+ continue;
1943
+ }
1944
+ if (ch === stringDelim) stringDelim = null;
1945
+ continue;
1946
+ }
1947
+ if (ch === '"' || ch === "'" || ch === "`") {
1948
+ stringDelim = ch;
1949
+ out += ch;
1950
+ continue;
1951
+ }
1952
+ if (syntax.block) {
1953
+ const [open, close] = syntax.block;
1954
+ if (line.startsWith(open, i)) {
1955
+ const closeIdx = line.indexOf(close, i + open.length);
1956
+ const end = closeIdx === -1 ? line.length : closeIdx + close.length;
1957
+ out += " ".repeat(end - i);
1958
+ if (closeIdx === -1) break;
1959
+ i = end - 1;
1960
+ continue;
1961
+ }
1962
+ }
1963
+ let hitLineComment = false;
1964
+ for (const lc of syntax.line) {
1965
+ if (line.startsWith(lc, i)) {
1966
+ out += " ".repeat(line.length - i);
1967
+ hitLineComment = true;
1968
+ break;
1969
+ }
1970
+ }
1971
+ if (hitLineComment) break;
1972
+ out += ch;
1973
+ }
1974
+ return out;
1975
+ }
1976
+ function stripCommentsForScan(content, path22) {
1977
+ const syntax = commentSyntaxForPath(path22);
1978
+ if (!syntax) return content;
1979
+ return content.split("\n").map((l) => blankCommentsOnLine(l, syntax)).join("\n");
1980
+ }
1849
1981
  function runRegexSensor(memoryId, sensor, target) {
1850
1982
  const re = compileRegexSensor(sensor);
1851
1983
  if (!re) return null;
1852
1984
  const absentRe = compileAbsentRegex(sensor);
1853
- const lines = target.content.split("\n");
1854
- for (let i = 0; i < lines.length; i++) {
1855
- const rawLine = lines[i];
1985
+ const rawLines = target.content.split("\n");
1986
+ const scanLines = stripCommentsForScan(target.content, target.path).split("\n");
1987
+ for (let i = 0; i < rawLines.length; i++) {
1988
+ const rawLine = rawLines[i];
1989
+ const scanLine = scanLines[i] ?? rawLine;
1856
1990
  re.lastIndex = 0;
1857
- if (!re.test(rawLine)) continue;
1991
+ if (!re.test(scanLine)) continue;
1858
1992
  if (absentRe) {
1859
1993
  const from = Math.max(0, i - SENSOR_ABSENT_LOOKBACK);
1860
- const to = Math.min(lines.length, i + SENSOR_ABSENT_WINDOW + 1);
1994
+ const to = Math.min(scanLines.length, i + SENSOR_ABSENT_WINDOW + 1);
1861
1995
  absentRe.lastIndex = 0;
1862
- if (absentRe.test(lines.slice(from, to).join("\n"))) continue;
1996
+ if (absentRe.test(scanLines.slice(from, to).join("\n"))) continue;
1863
1997
  }
1864
1998
  const brittle = sensor.kind === "regex" && sensor.pattern ? sensorPatternBrittleness(sensor.pattern) : null;
1865
1999
  const severity = brittle ? "warn" : sensor.severity;
@@ -5016,8 +5150,20 @@ function extractActionsBriefBody(markdown, maxChars = MAX_DEFAULT_CHARS) {
5016
5150
  buf.push(t);
5017
5151
  }
5018
5152
  if (buf.length) paragraphs.push(buf.join(" ").trim());
5019
- let out = paragraphs[0] ?? stripped.slice(0, maxChars);
5020
- if (!out.trim()) out = stripped.slice(0, maxChars);
5153
+ if (paragraphs.length === 0) {
5154
+ let out2 = stripped.slice(0, maxChars);
5155
+ if (out2.length > maxChars) out2 = out2.slice(0, maxChars).trimEnd() + "\u2026";
5156
+ return out2;
5157
+ }
5158
+ const collected = [];
5159
+ let length = 0;
5160
+ for (const paragraph of paragraphs) {
5161
+ const cost = (collected.length ? 2 : 0) + paragraph.length;
5162
+ if (collected.length > 0 && length + cost > maxChars) break;
5163
+ collected.push(paragraph);
5164
+ length += cost;
5165
+ }
5166
+ let out = collected.join("\n\n");
5021
5167
  if (out.length > maxChars) out = out.slice(0, maxChars).trimEnd() + "\u2026";
5022
5168
  return out;
5023
5169
  }
@@ -7080,10 +7226,7 @@ Subject: ${seed.what}
7080
7226
  **Why it failed / do NOT use:** ${seed.why_failed}
7081
7227
  `;
7082
7228
  const gateLine = gatePassed ? "\nThe gate PASSED this commit \u2014 a validated sensor here upgrades the harness.\n" : "";
7083
- const candidate = suggestSensorSeed(seed.what, paths);
7084
- const sensorHint = candidate ? `
7085
- proposed_sensor_seed: ${JSON.stringify(candidate)}
7086
- ` : "\nproposed_sensor_seed: inspect the revert diff, then author a deterministic candidate with `hivelore sensors propose <id>`.\n";
7229
+ const sensorHint = "\nproposed_sensor_seed: inspect the revert diff, then author a deterministic candidate with `hivelore sensors propose --from-fix <revert-sha>` (it mines the fix diff and validates).\n";
7087
7230
  out.push({
7088
7231
  slug: `gate-miss-${failedSha.slice(0, 12)}`,
7089
7232
  reverted_sha: failedSha,
@@ -7220,6 +7363,20 @@ _No notable discoveries captured. Run post_task / \`mem_session_end\` for a rich
7220
7363
  **Discoveries:**
7221
7364
  ${trimmed}`;
7222
7365
  }
7366
+ function recapBriefingExcerpt(body, maxChars = 700) {
7367
+ if (isAutoRecap(body)) return compactAutoRecapBody(body);
7368
+ const section = (name) => body.match(name)?.[1]?.trim() ?? "";
7369
+ const goal = section(/##+\s*Goal[^\n]*\n+([\s\S]*?)(?=\n##+\s|\n*$)/i);
7370
+ const next = section(/##+\s*Next steps?[^\n]*\n([\s\S]*?)(?=\n##+\s|\n*$)/i);
7371
+ if (!goal && !next) return body.length > maxChars ? body.slice(0, maxChars).trimEnd() + "\u2026" : body;
7372
+ const parts = [];
7373
+ if (goal) parts.push(`_${goal.split("\n")[0].trim()}_`);
7374
+ parts.push(next ? `**Next steps:**
7375
+ ${next}` : "_No next steps recorded \u2014 `mem_get <id>` for the full recap._");
7376
+ let out = parts.join("\n\n");
7377
+ if (out.length > maxChars) out = out.slice(0, maxChars).trimEnd() + "\u2026";
7378
+ return out;
7379
+ }
7223
7380
 
7224
7381
  // src/handoff.ts
7225
7382
  import { writeFile as writeFile13, readFile as readFile18, stat as stat4 } from "fs/promises";
@@ -7400,6 +7557,7 @@ ${learning.instruction}
7400
7557
  return drafts;
7401
7558
  }
7402
7559
  export {
7560
+ ADAPTIVE_FLOOR_MIN_SAMPLES,
7403
7561
  AUTOPILOT_DEFAULTS,
7404
7562
  ActivationSchema,
7405
7563
  AnchorSchema,
@@ -7462,6 +7620,7 @@ export {
7462
7620
  USAGE_LOG_DIR,
7463
7621
  USAGE_LOG_FILE,
7464
7622
  WEAK_ANCHOR_CHURN_RATIO,
7623
+ adaptiveSemanticFloor,
7465
7624
  addedLineNumbersFromDiff,
7466
7625
  addedLinesFromDiff,
7467
7626
  aggregateRetrieval,
@@ -7664,6 +7823,7 @@ export {
7664
7823
  readRuntimeJournalTail,
7665
7824
  readSessionHandoff,
7666
7825
  readUsageEvents,
7826
+ recapBriefingExcerpt,
7667
7827
  recommendFeedbackAdjustment,
7668
7828
  recordApplied,
7669
7829
  recordGateReminder,
@@ -7715,6 +7875,7 @@ export {
7715
7875
  shouldExpandGateReminder,
7716
7876
  snapshotContract,
7717
7877
  specificityScore,
7878
+ stripCommentsForScan,
7718
7879
  stripPrivate,
7719
7880
  suggestGate,
7720
7881
  suggestSensorFromMemory,