@hivelore/core 0.49.0 → 0.52.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
@@ -1418,7 +1418,9 @@ interface AstExport {
1418
1418
  */
1419
1419
  declare function parseFileAst(source: string, ext: string): Promise<AstExport[] | null>;
1420
1420
 
1421
- declare const CONFIG_FILE = "haive.config.json";
1421
+ declare const CONFIG_FILE = "hivelore.config.json";
1422
+ /** Pre-rename filename. Read as a fallback and migrated to CONFIG_FILE on the next write. */
1423
+ declare const LEGACY_CONFIG_FILE = "haive.config.json";
1422
1424
  /** A remote or local repo to pull shared memories from. */
1423
1425
  interface CrossRepoSource {
1424
1426
  /** Human-readable name for this source (used in imported memory tags). */
@@ -1580,6 +1582,13 @@ interface HaiveConfig {
1580
1582
  * Default: "anchored" — makes "known bad approaches are blocked" true for the precise case.
1581
1583
  */
1582
1584
  antiPatternGate?: "off" | "review" | "anchored" | "strict";
1585
+ /**
1586
+ * Surface the aggregated "N documented lessons plausibly match this diff — review" finding at the
1587
+ * gate (fuzzy anchor/literal/semantic matches that never hard-block). Default **false**: in practice
1588
+ * it fired on nearly every commit and was skimmed past, training people to ignore the gate — only a
1589
+ * deterministic sensor block is signal. Set true (or use antiPatternGate:"review") to restore it.
1590
+ */
1591
+ reviewMatches?: boolean;
1583
1592
  /**
1584
1593
  * First-agent bootstrap gate. The trigger is the COLD STATE of the corpus, not a command or flag:
1585
1594
  * when the knowledge layer is empty, the very first agent is forced to fill the baseline — a filled
@@ -1688,7 +1697,10 @@ declare function antiPatternGateParams(gate: AntiPatternGate): {
1688
1697
  block_on: "any" | "high-confidence" | "never";
1689
1698
  anchored_blocks: boolean;
1690
1699
  };
1700
+ /** The canonical config path to WRITE to (the current name). */
1691
1701
  declare function configPath(paths: HaivePaths): string;
1702
+ /** Path to READ from: the current file if present, else the legacy `haive.config.json`, else current. */
1703
+ declare function resolveConfigPath(paths: HaivePaths): string;
1692
1704
  declare function loadConfig(paths: HaivePaths): Promise<HaiveConfig>;
1693
1705
  declare function loadConfigSync(paths: HaivePaths): HaiveConfig;
1694
1706
  declare function saveConfig(paths: HaivePaths, config: HaiveConfig): Promise<void>;
@@ -2172,12 +2184,18 @@ interface SensorSelfCheck {
2172
2184
  silent_on_current: boolean;
2173
2185
  /** Did it fire on a known-bad example from the lesson? null when no example was available. */
2174
2186
  fires_on_bad: boolean | null;
2187
+ /**
2188
+ * Did it fire on the lesson's stated CORRECT approach (the `Instead, use:` snippet)? true = the
2189
+ * sensor is INVERTED — it would block the recommended fix. null when no correct example was given.
2190
+ */
2191
+ fires_on_correct: boolean | null;
2175
2192
  /** Files whose CURRENT content the sensor matched — evidence of a false positive. */
2176
2193
  fired_on: string[];
2177
2194
  /**
2178
- * Safe to hard-block: silent on the current code AND (fires on the bad example, or there was no
2179
- * example to test). A sensor that fires on correct code is exactly what trains agents to ignore the
2180
- * gate — this is the gate that keeps the auto-generation layer honest.
2195
+ * Safe to hard-block: silent on the current code, does NOT fire on the stated correct approach,
2196
+ * AND (fires on the bad example, or there was no example to test). A sensor that fires on correct
2197
+ * code is exactly what trains agents to ignore the gate — this is the gate that keeps the
2198
+ * auto-generation layer honest.
2181
2199
  */
2182
2200
  passed: boolean;
2183
2201
  }
@@ -2191,12 +2209,13 @@ interface SensorSelfCheck {
2191
2209
  declare function sensorSelfCheck(sensor: Sensor, input: {
2192
2210
  currentTargets: SensorTarget[];
2193
2211
  badExamples: string[];
2212
+ correctExamples?: string[];
2194
2213
  }): SensorSelfCheck;
2195
2214
  interface ProposedSensorVerdict {
2196
2215
  /** Safe to store at the requested severity. */
2197
2216
  accepted: boolean;
2198
2217
  /** Why a block proposal was rejected (so the agent can revise and re-propose). */
2199
- reason?: "fires-on-current" | "missed-bad-example" | "brittle";
2218
+ reason?: "fires-on-current" | "fires-on-correct" | "missed-bad-example" | "brittle";
2200
2219
  self_check: SensorSelfCheck;
2201
2220
  /** Brittleness reason (hardcoded line numbers, etc.) or null. */
2202
2221
  brittle: string | null;
@@ -2210,13 +2229,32 @@ interface ProposedSensorVerdict {
2210
2229
  declare function judgeProposedSensor(sensor: Sensor, input: {
2211
2230
  currentTargets: SensorTarget[];
2212
2231
  badExamples: string[];
2232
+ correctExamples?: string[];
2213
2233
  }): ProposedSensorVerdict;
2234
+ /**
2235
+ * A command oracle that exits non-zero has either FAILED an assertion (a real signal) or errored
2236
+ * before it could reach one — a missing module, an import/collection failure, a syntax error, or
2237
+ * "no tests found". Only the former proves anything. This distinguishes them from the output tail.
2238
+ *
2239
+ * Used by the prove-RED replay: at the pre-fix `red_ref` the code/test under guard often does not
2240
+ * exist yet, so `node t.js` exits 1 for "Cannot find module" — that is the harness failing to run,
2241
+ * NOT the oracle catching the incident. Classifying it as RED-proven would fabricate a guarantee.
2242
+ * Conservative by design: when in doubt at prove-RED, "could not run" (no proof) is the safe verdict.
2243
+ */
2244
+ declare function isHarnessErrorOutput(output: string): boolean;
2214
2245
  /**
2215
2246
  * Pull candidate bad-code examples from a lesson body: fenced code blocks and inline code spans that
2216
2247
  * look like code (contain a call/dot/assignment). Used to confirm a generated sensor actually fires
2217
2248
  * on the mistake it describes.
2218
2249
  */
2219
2250
  declare function extractSensorExamples(body: string): string[];
2251
+ /**
2252
+ * Pull the lesson's stated CORRECT approach — the text of an `**Instead, use:** …` line or an
2253
+ * `## Instead` section (the shape `mem_tried --instead` and the attempt template write). This is code
2254
+ * the sensor must NEVER match: a block pattern that fires on it is inverted (it would refuse the very
2255
+ * fix the lesson prescribes). Returns the raw snippet(s); the caller runs the sensor against them.
2256
+ */
2257
+ declare function extractCorrectApproachExamples(body: string): string[];
2220
2258
  /**
2221
2259
  * Extract the added lines from a unified diff (lines starting with a single `+`,
2222
2260
  * excluding the `+++` file header). Mirrors the diff-handling already used by the
@@ -3428,4 +3466,4 @@ interface ReviewDraftOptions {
3428
3466
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
3429
3467
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
3430
3468
 
3431
- export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, AnchorSchema, type AntiPatternGate, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, 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, 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 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_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, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, GUESSABLE_THRESHOLD, type GateMissProposal, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateTuningSuggestion, 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, 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, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, 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, 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, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, deriveMainAreas, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeFramework, 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, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeMemory, 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 };
3469
+ export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, AnchorSchema, type AntiPatternGate, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, 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, 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 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_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, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, GUESSABLE_THRESHOLD, type GateMissProposal, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateTuningSuggestion, 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, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, 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, 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, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, deriveMainAreas, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractCorrectApproachExamples, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, 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, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeFramework, 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, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeMemory, 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
@@ -2526,9 +2526,10 @@ function queryCodeMap(map, options) {
2526
2526
  // src/config.ts
2527
2527
  import { existsSync as existsSync7 } from "fs";
2528
2528
  import { readFileSync } from "fs";
2529
- import { readFile as readFile7, writeFile as writeFile4 } from "fs/promises";
2529
+ import { readFile as readFile7, rm, writeFile as writeFile4 } from "fs/promises";
2530
2530
  import path9 from "path";
2531
- var CONFIG_FILE = "haive.config.json";
2531
+ var CONFIG_FILE = "hivelore.config.json";
2532
+ var LEGACY_CONFIG_FILE = "haive.config.json";
2532
2533
  var DEFAULT_BRIEFING_EXCLUDE_TAGS = [
2533
2534
  "positioning",
2534
2535
  "competitive",
@@ -2624,8 +2625,14 @@ function antiPatternGateParams(gate) {
2624
2625
  function configPath(paths) {
2625
2626
  return path9.join(paths.haiveDir, CONFIG_FILE);
2626
2627
  }
2628
+ function resolveConfigPath(paths) {
2629
+ const current = configPath(paths);
2630
+ if (existsSync7(current)) return current;
2631
+ const legacy = path9.join(paths.haiveDir, LEGACY_CONFIG_FILE);
2632
+ return existsSync7(legacy) ? legacy : current;
2633
+ }
2627
2634
  async function loadConfig(paths) {
2628
- const file = configPath(paths);
2635
+ const file = resolveConfigPath(paths);
2629
2636
  if (!existsSync7(file)) return { ...DEFAULT_CONFIG };
2630
2637
  try {
2631
2638
  const raw = await readFile7(file, "utf8");
@@ -2640,7 +2647,7 @@ async function loadConfig(paths) {
2640
2647
  }
2641
2648
  }
2642
2649
  function loadConfigSync(paths) {
2643
- const file = configPath(paths);
2650
+ const file = resolveConfigPath(paths);
2644
2651
  if (!existsSync7(file)) return { ...DEFAULT_CONFIG };
2645
2652
  try {
2646
2653
  const parsed = JSON.parse(readFileSync(file, "utf8"));
@@ -2652,6 +2659,13 @@ function loadConfigSync(paths) {
2652
2659
  }
2653
2660
  async function saveConfig(paths, config) {
2654
2661
  await writeFile4(configPath(paths), JSON.stringify(config, null, 2) + "\n", "utf8");
2662
+ const legacy = path9.join(paths.haiveDir, LEGACY_CONFIG_FILE);
2663
+ if (existsSync7(legacy)) {
2664
+ try {
2665
+ await rm(legacy, { force: true });
2666
+ } catch {
2667
+ }
2668
+ }
2655
2669
  }
2656
2670
  function mergeConfig(base, override) {
2657
2671
  return {
@@ -4303,11 +4317,19 @@ function sensorSelfCheck(sensor, input) {
4303
4317
  (example) => runRegexSensor("self-check", sensor, { path: "<example>", content: example }) !== null
4304
4318
  );
4305
4319
  }
4320
+ let firesOnCorrect = null;
4321
+ const correctExamples = (input.correctExamples ?? []).filter((e) => e.trim().length > 0);
4322
+ if (correctExamples.length > 0) {
4323
+ firesOnCorrect = correctExamples.some(
4324
+ (example) => runRegexSensor("self-check", sensor, { path: "<correct>", content: example }) !== null
4325
+ );
4326
+ }
4306
4327
  return {
4307
4328
  silent_on_current: silentOnCurrent,
4308
4329
  fires_on_bad: firesOnBad,
4330
+ fires_on_correct: firesOnCorrect,
4309
4331
  fired_on: firedOn,
4310
- passed: silentOnCurrent && firesOnBad !== false
4332
+ passed: silentOnCurrent && firesOnBad !== false && firesOnCorrect !== true
4311
4333
  };
4312
4334
  }
4313
4335
  function judgeProposedSensor(sensor, input) {
@@ -4318,12 +4340,47 @@ function judgeProposedSensor(sensor, input) {
4318
4340
  if (input.currentTargets.length > 0 && !self_check.silent_on_current) {
4319
4341
  return { accepted: false, reason: "fires-on-current", self_check, brittle };
4320
4342
  }
4343
+ if (self_check.fires_on_correct === true) {
4344
+ return { accepted: false, reason: "fires-on-correct", self_check, brittle };
4345
+ }
4321
4346
  if (self_check.fires_on_bad === false) {
4322
4347
  return { accepted: false, reason: "missed-bad-example", self_check, brittle };
4323
4348
  }
4324
4349
  }
4325
4350
  return { accepted: true, self_check, brittle };
4326
4351
  }
4352
+ function isHarnessErrorOutput(output) {
4353
+ if (!output) return false;
4354
+ return HARNESS_ERROR_SIGNATURES.some((re) => re.test(output));
4355
+ }
4356
+ var HARNESS_ERROR_SIGNATURES = [
4357
+ /cannot find module/i,
4358
+ // node CJS require of a missing file/dep
4359
+ /ERR_MODULE_NOT_FOUND/,
4360
+ // node ESM import of a missing file/dep
4361
+ /\bMODULE_NOT_FOUND\b/,
4362
+ // node error code
4363
+ /ModuleNotFoundError/,
4364
+ // python
4365
+ /\bImportError\b/,
4366
+ // python import failure at collection
4367
+ /\bSyntaxError\b/,
4368
+ // parse failure at load (any runtime)
4369
+ /no test files? found/i,
4370
+ // vitest / jest — nothing ran
4371
+ /no tests found/i,
4372
+ // jest
4373
+ /no tests ran/i,
4374
+ // pytest -q
4375
+ /collected 0 items/i,
4376
+ // pytest — nothing collected
4377
+ /error(s)? (?:while )?collecting/i,
4378
+ // pytest collection error
4379
+ /cannot find package/i,
4380
+ // go
4381
+ /no( buildable)? go( source)? files/i
4382
+ // go: nothing to build
4383
+ ];
4327
4384
  function extractSensorExamples(body) {
4328
4385
  const examples = [];
4329
4386
  for (const match of body.matchAll(/```[^\n]*\n([\s\S]*?)```/g)) {
@@ -4336,6 +4393,17 @@ function extractSensorExamples(body) {
4336
4393
  }
4337
4394
  return examples;
4338
4395
  }
4396
+ function extractCorrectApproachExamples(body) {
4397
+ const out = [];
4398
+ for (const match of body.matchAll(/\*\*Instead,?\s*use:?\*\*\s*([^\n]+)/gi)) {
4399
+ const snippet = (match[1] ?? "").trim();
4400
+ if (snippet) out.push(snippet);
4401
+ }
4402
+ const sectionMatch = body.match(/^#{2,}\s+Instead\b[^\n]*\n+([^\n]+)/im);
4403
+ const sectionLine = sectionMatch?.[1]?.trim();
4404
+ if (sectionLine) out.push(sectionLine);
4405
+ return out;
4406
+ }
4339
4407
  function addedLinesFromDiff(diff) {
4340
4408
  const targets = sensorTargetsFromDiff(diff);
4341
4409
  if (targets.length > 0) return targets.map((target) => target.content).join("\n");
@@ -4558,8 +4626,12 @@ function suggestSensorSeed(body, anchorPaths, options = {}) {
4558
4626
  const paths = options.paths ?? anchorPaths;
4559
4627
  if (paths.length === 0) return null;
4560
4628
  const negativeText = body.split(/\*\*Instead,\s*use:\*\*|^##\s+Instead\b/im)[0] ?? body;
4561
- const assignment = pickAssignmentPattern(negativeText);
4562
- const lowercaseValue = assignment ? null : pickLowercaseValuePattern(negativeText);
4629
+ const recommended = recommendedTokens(body);
4630
+ const isRecommended = (token2) => !!token2 && recommended.has(token2.toLowerCase());
4631
+ const assignmentRaw = pickAssignmentPattern(negativeText);
4632
+ const assignment = isRecommended(assignmentRaw?.label.split(/[:=]/)[0]) ? null : assignmentRaw;
4633
+ const lowercaseRaw = assignment ? null : pickLowercaseValuePattern(negativeText);
4634
+ const lowercaseValue = isRecommended(lowercaseRaw?.label.split(/[:=]/)[0]) ? null : lowercaseRaw;
4563
4635
  const required = !assignment && !lowercaseValue ? pickRequiredCompanion(body) : null;
4564
4636
  let companion = null;
4565
4637
  if (required) {
@@ -4576,7 +4648,7 @@ function suggestSensorSeed(body, anchorPaths, options = {}) {
4576
4648
  companion = { trigger, required, plain };
4577
4649
  }
4578
4650
  }
4579
- const fallbackToken = pickDistinctiveToken(negativeText, required ? [required] : []);
4651
+ const fallbackToken = pickDistinctiveToken(negativeText, [...required ? [required] : [], ...recommended]);
4580
4652
  const token = assignment?.label ?? lowercaseValue?.label ?? companion?.trigger ?? fallbackToken;
4581
4653
  if (!token) return null;
4582
4654
  const pattern = assignment?.pattern ?? lowercaseValue?.pattern ?? (companion?.plain ? `\\b${escapeRegExp(companion.trigger)}\\b` : escapeRegExp(companion?.trigger ?? token));
@@ -4603,6 +4675,16 @@ function suggestSensorFromMemory(body, anchorPaths, options = {}) {
4603
4675
  last_fired: null
4604
4676
  };
4605
4677
  }
4678
+ function recommendedTokens(body) {
4679
+ const tokens = /* @__PURE__ */ new Set();
4680
+ for (const clause of extractCorrectApproachExamples(body)) {
4681
+ for (const match of clause.matchAll(CODE_TOKEN_RE)) {
4682
+ const raw = (match[1] ?? match[2] ?? match[3] ?? "").replace(/^[^\w.-]+|[^\w.-]+$/g, "");
4683
+ if (raw.length >= 3) tokens.add(raw.toLowerCase());
4684
+ }
4685
+ }
4686
+ return tokens;
4687
+ }
4606
4688
  function pickRequiredCompanion(text) {
4607
4689
  const tok = "([A-Za-z`'\"$][\\w.$-]{2,79})";
4608
4690
  const patterns = [
@@ -5318,7 +5400,10 @@ function assessBehaviourCoverage(input) {
5318
5400
  };
5319
5401
  }
5320
5402
  function renderBehaviourCoverageLine(m) {
5321
- if (m.mainAreas.length === 0) return "no main code areas detected";
5403
+ if (m.mainAreas.length === 0) {
5404
+ if (m.totalOracles === 0) return "no main code areas detected";
5405
+ return `${m.totalOracles} behavioural oracle(s) present (${m.armedOracles} armed, ${m.redProvenOracles} red-proven); no main code areas derived yet to attribute them to`;
5406
+ }
5322
5407
  if (m.totalOracles === 0) {
5323
5408
  return `0/${m.mainAreas.length} area(s) guarded by a behavioural oracle (no test/shell sensors yet)`;
5324
5409
  }
@@ -6524,6 +6609,7 @@ export {
6524
6609
  HAIVE_OWNED_FILES,
6525
6610
  HANDOFF_FILENAME,
6526
6611
  HIVELORE_ATTRIBUTION,
6612
+ LEGACY_CONFIG_FILE,
6527
6613
  MEMORIES_DIR,
6528
6614
  MIN_WORD_LEN,
6529
6615
  MemoryFrontmatterSchema,
@@ -6617,6 +6703,7 @@ export {
6617
6703
  evaluateSkillActivation,
6618
6704
  existingGateMissShas,
6619
6705
  extractActionsBriefBody,
6706
+ extractCorrectApproachExamples,
6620
6707
  extractReferencedPaths,
6621
6708
  extractReviewLearnings,
6622
6709
  extractSensorExamples,
@@ -6651,6 +6738,7 @@ export {
6651
6738
  isEnvWorkaroundMemory,
6652
6739
  isFreshIsoDate,
6653
6740
  isGlobPath,
6741
+ isHarnessErrorOutput,
6654
6742
  isLikelyGuessable,
6655
6743
  isNoiseSubject,
6656
6744
  isProductionCodeFile,
@@ -6732,6 +6820,7 @@ export {
6732
6820
  renderPreventionReceipt,
6733
6821
  renderPreventionReceiptShare,
6734
6822
  resolveBriefingBudget,
6823
+ resolveConfigPath,
6735
6824
  resolveHaivePaths,
6736
6825
  resolveManifestFiles,
6737
6826
  resolveProjectInfo,