@hivelore/core 0.51.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
@@ -2184,12 +2184,18 @@ interface SensorSelfCheck {
2184
2184
  silent_on_current: boolean;
2185
2185
  /** Did it fire on a known-bad example from the lesson? null when no example was available. */
2186
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;
2187
2192
  /** Files whose CURRENT content the sensor matched — evidence of a false positive. */
2188
2193
  fired_on: string[];
2189
2194
  /**
2190
- * Safe to hard-block: silent on the current code AND (fires on the bad example, or there was no
2191
- * example to test). A sensor that fires on correct code is exactly what trains agents to ignore the
2192
- * 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.
2193
2199
  */
2194
2200
  passed: boolean;
2195
2201
  }
@@ -2203,12 +2209,13 @@ interface SensorSelfCheck {
2203
2209
  declare function sensorSelfCheck(sensor: Sensor, input: {
2204
2210
  currentTargets: SensorTarget[];
2205
2211
  badExamples: string[];
2212
+ correctExamples?: string[];
2206
2213
  }): SensorSelfCheck;
2207
2214
  interface ProposedSensorVerdict {
2208
2215
  /** Safe to store at the requested severity. */
2209
2216
  accepted: boolean;
2210
2217
  /** Why a block proposal was rejected (so the agent can revise and re-propose). */
2211
- reason?: "fires-on-current" | "missed-bad-example" | "brittle";
2218
+ reason?: "fires-on-current" | "fires-on-correct" | "missed-bad-example" | "brittle";
2212
2219
  self_check: SensorSelfCheck;
2213
2220
  /** Brittleness reason (hardcoded line numbers, etc.) or null. */
2214
2221
  brittle: string | null;
@@ -2222,13 +2229,32 @@ interface ProposedSensorVerdict {
2222
2229
  declare function judgeProposedSensor(sensor: Sensor, input: {
2223
2230
  currentTargets: SensorTarget[];
2224
2231
  badExamples: string[];
2232
+ correctExamples?: string[];
2225
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;
2226
2245
  /**
2227
2246
  * Pull candidate bad-code examples from a lesson body: fenced code blocks and inline code spans that
2228
2247
  * look like code (contain a call/dot/assignment). Used to confirm a generated sensor actually fires
2229
2248
  * on the mistake it describes.
2230
2249
  */
2231
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[];
2232
2258
  /**
2233
2259
  * Extract the added lines from a unified diff (lines starting with a single `+`,
2234
2260
  * excluding the `+++` file header). Mirrors the diff-handling already used by the
@@ -3440,4 +3466,4 @@ interface ReviewDraftOptions {
3440
3466
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
3441
3467
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
3442
3468
 
3443
- 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, 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, 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 };
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
@@ -4317,11 +4317,19 @@ function sensorSelfCheck(sensor, input) {
4317
4317
  (example) => runRegexSensor("self-check", sensor, { path: "<example>", content: example }) !== null
4318
4318
  );
4319
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
+ }
4320
4327
  return {
4321
4328
  silent_on_current: silentOnCurrent,
4322
4329
  fires_on_bad: firesOnBad,
4330
+ fires_on_correct: firesOnCorrect,
4323
4331
  fired_on: firedOn,
4324
- passed: silentOnCurrent && firesOnBad !== false
4332
+ passed: silentOnCurrent && firesOnBad !== false && firesOnCorrect !== true
4325
4333
  };
4326
4334
  }
4327
4335
  function judgeProposedSensor(sensor, input) {
@@ -4332,12 +4340,47 @@ function judgeProposedSensor(sensor, input) {
4332
4340
  if (input.currentTargets.length > 0 && !self_check.silent_on_current) {
4333
4341
  return { accepted: false, reason: "fires-on-current", self_check, brittle };
4334
4342
  }
4343
+ if (self_check.fires_on_correct === true) {
4344
+ return { accepted: false, reason: "fires-on-correct", self_check, brittle };
4345
+ }
4335
4346
  if (self_check.fires_on_bad === false) {
4336
4347
  return { accepted: false, reason: "missed-bad-example", self_check, brittle };
4337
4348
  }
4338
4349
  }
4339
4350
  return { accepted: true, self_check, brittle };
4340
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
+ ];
4341
4384
  function extractSensorExamples(body) {
4342
4385
  const examples = [];
4343
4386
  for (const match of body.matchAll(/```[^\n]*\n([\s\S]*?)```/g)) {
@@ -4350,6 +4393,17 @@ function extractSensorExamples(body) {
4350
4393
  }
4351
4394
  return examples;
4352
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
+ }
4353
4407
  function addedLinesFromDiff(diff) {
4354
4408
  const targets = sensorTargetsFromDiff(diff);
4355
4409
  if (targets.length > 0) return targets.map((target) => target.content).join("\n");
@@ -4572,8 +4626,12 @@ function suggestSensorSeed(body, anchorPaths, options = {}) {
4572
4626
  const paths = options.paths ?? anchorPaths;
4573
4627
  if (paths.length === 0) return null;
4574
4628
  const negativeText = body.split(/\*\*Instead,\s*use:\*\*|^##\s+Instead\b/im)[0] ?? body;
4575
- const assignment = pickAssignmentPattern(negativeText);
4576
- 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;
4577
4635
  const required = !assignment && !lowercaseValue ? pickRequiredCompanion(body) : null;
4578
4636
  let companion = null;
4579
4637
  if (required) {
@@ -4590,7 +4648,7 @@ function suggestSensorSeed(body, anchorPaths, options = {}) {
4590
4648
  companion = { trigger, required, plain };
4591
4649
  }
4592
4650
  }
4593
- const fallbackToken = pickDistinctiveToken(negativeText, required ? [required] : []);
4651
+ const fallbackToken = pickDistinctiveToken(negativeText, [...required ? [required] : [], ...recommended]);
4594
4652
  const token = assignment?.label ?? lowercaseValue?.label ?? companion?.trigger ?? fallbackToken;
4595
4653
  if (!token) return null;
4596
4654
  const pattern = assignment?.pattern ?? lowercaseValue?.pattern ?? (companion?.plain ? `\\b${escapeRegExp(companion.trigger)}\\b` : escapeRegExp(companion?.trigger ?? token));
@@ -4617,6 +4675,16 @@ function suggestSensorFromMemory(body, anchorPaths, options = {}) {
4617
4675
  last_fired: null
4618
4676
  };
4619
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
+ }
4620
4688
  function pickRequiredCompanion(text) {
4621
4689
  const tok = "([A-Za-z`'\"$][\\w.$-]{2,79})";
4622
4690
  const patterns = [
@@ -5332,7 +5400,10 @@ function assessBehaviourCoverage(input) {
5332
5400
  };
5333
5401
  }
5334
5402
  function renderBehaviourCoverageLine(m) {
5335
- 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
+ }
5336
5407
  if (m.totalOracles === 0) {
5337
5408
  return `0/${m.mainAreas.length} area(s) guarded by a behavioural oracle (no test/shell sensors yet)`;
5338
5409
  }
@@ -6632,6 +6703,7 @@ export {
6632
6703
  evaluateSkillActivation,
6633
6704
  existingGateMissShas,
6634
6705
  extractActionsBriefBody,
6706
+ extractCorrectApproachExamples,
6635
6707
  extractReferencedPaths,
6636
6708
  extractReviewLearnings,
6637
6709
  extractSensorExamples,
@@ -6666,6 +6738,7 @@ export {
6666
6738
  isEnvWorkaroundMemory,
6667
6739
  isFreshIsoDate,
6668
6740
  isGlobPath,
6741
+ isHarnessErrorOutput,
6669
6742
  isLikelyGuessable,
6670
6743
  isNoiseSubject,
6671
6744
  isProductionCodeFile,