@hivelore/core 0.35.0 → 0.36.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
@@ -49,12 +49,26 @@ declare const SensorSchema: z.ZodObject<{
49
49
  paths: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
50
50
  /** LLM-facing self-correction message: what was done wrong and what to do instead. */
51
51
  message: z.ZodString;
52
+ /**
53
+ * Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
54
+ * incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
55
+ * behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
56
+ * the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
57
+ */
58
+ incident: z.ZodOptional<z.ZodString>;
52
59
  /** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
53
60
  severity: z.ZodDefault<z.ZodEnum<["warn", "block"]>>;
54
61
  /** True when Hivelore generated this sensor automatically (vs. hand-authored). */
55
62
  autogen: z.ZodDefault<z.ZodBoolean>;
56
63
  /** ISO timestamp of the last time this sensor matched a diff. */
57
64
  last_fired: z.ZodDefault<z.ZodNullable<z.ZodString>>;
65
+ /**
66
+ * ISO timestamp of the last manual `sensors promote` back to block. Health assessment ignores
67
+ * ledger evaluations older than this — without it, a promoted sensor whose oracle was FIXED is
68
+ * re-quarantined on the next commit for up to 30 days (the stale flaps are still in the window),
69
+ * making the promotion promised by the quarantine note a no-op.
70
+ */
71
+ promoted_at: z.ZodOptional<z.ZodString>;
58
72
  }, "strip", z.ZodTypeAny, {
59
73
  message: string;
60
74
  paths: string[];
@@ -67,6 +81,8 @@ declare const SensorSchema: z.ZodObject<{
67
81
  flags?: string | undefined;
68
82
  command?: string | undefined;
69
83
  timeout_ms?: number | undefined;
84
+ incident?: string | undefined;
85
+ promoted_at?: string | undefined;
70
86
  }, {
71
87
  message: string;
72
88
  paths?: string[] | undefined;
@@ -76,9 +92,11 @@ declare const SensorSchema: z.ZodObject<{
76
92
  flags?: string | undefined;
77
93
  command?: string | undefined;
78
94
  timeout_ms?: number | undefined;
95
+ incident?: string | undefined;
79
96
  severity?: "warn" | "block" | undefined;
80
97
  autogen?: boolean | undefined;
81
98
  last_fired?: string | null | undefined;
99
+ promoted_at?: string | undefined;
82
100
  }>;
83
101
  /**
84
102
  * Progressive-disclosure activation triggers for a `skill` memory.
@@ -148,12 +166,26 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
148
166
  paths: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
149
167
  /** LLM-facing self-correction message: what was done wrong and what to do instead. */
150
168
  message: z.ZodString;
169
+ /**
170
+ * Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
171
+ * incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
172
+ * behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
173
+ * the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
174
+ */
175
+ incident: z.ZodOptional<z.ZodString>;
151
176
  /** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
152
177
  severity: z.ZodDefault<z.ZodEnum<["warn", "block"]>>;
153
178
  /** True when Hivelore generated this sensor automatically (vs. hand-authored). */
154
179
  autogen: z.ZodDefault<z.ZodBoolean>;
155
180
  /** ISO timestamp of the last time this sensor matched a diff. */
156
181
  last_fired: z.ZodDefault<z.ZodNullable<z.ZodString>>;
182
+ /**
183
+ * ISO timestamp of the last manual `sensors promote` back to block. Health assessment ignores
184
+ * ledger evaluations older than this — without it, a promoted sensor whose oracle was FIXED is
185
+ * re-quarantined on the next commit for up to 30 days (the stale flaps are still in the window),
186
+ * making the promotion promised by the quarantine note a no-op.
187
+ */
188
+ promoted_at: z.ZodOptional<z.ZodString>;
157
189
  }, "strip", z.ZodTypeAny, {
158
190
  message: string;
159
191
  paths: string[];
@@ -166,6 +198,8 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
166
198
  flags?: string | undefined;
167
199
  command?: string | undefined;
168
200
  timeout_ms?: number | undefined;
201
+ incident?: string | undefined;
202
+ promoted_at?: string | undefined;
169
203
  }, {
170
204
  message: string;
171
205
  paths?: string[] | undefined;
@@ -175,9 +209,11 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
175
209
  flags?: string | undefined;
176
210
  command?: string | undefined;
177
211
  timeout_ms?: number | undefined;
212
+ incident?: string | undefined;
178
213
  severity?: "warn" | "block" | undefined;
179
214
  autogen?: boolean | undefined;
180
215
  last_fired?: string | null | undefined;
216
+ promoted_at?: string | undefined;
181
217
  }>>;
182
218
  /** Optional progressive-disclosure triggers — only meaningful for `type: skill`. */
183
219
  activation: z.ZodOptional<z.ZodObject<{
@@ -257,6 +293,8 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
257
293
  flags?: string | undefined;
258
294
  command?: string | undefined;
259
295
  timeout_ms?: number | undefined;
296
+ incident?: string | undefined;
297
+ promoted_at?: string | undefined;
260
298
  } | undefined;
261
299
  activation?: {
262
300
  keywords: string[];
@@ -287,9 +325,11 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
287
325
  flags?: string | undefined;
288
326
  command?: string | undefined;
289
327
  timeout_ms?: number | undefined;
328
+ incident?: string | undefined;
290
329
  severity?: "warn" | "block" | undefined;
291
330
  autogen?: boolean | undefined;
292
331
  last_fired?: string | null | undefined;
332
+ promoted_at?: string | undefined;
293
333
  } | undefined;
294
334
  activation?: {
295
335
  keywords?: string[] | undefined;
@@ -341,6 +381,8 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
341
381
  flags?: string | undefined;
342
382
  command?: string | undefined;
343
383
  timeout_ms?: number | undefined;
384
+ incident?: string | undefined;
385
+ promoted_at?: string | undefined;
344
386
  } | undefined;
345
387
  activation?: {
346
388
  keywords: string[];
@@ -371,9 +413,11 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
371
413
  flags?: string | undefined;
372
414
  command?: string | undefined;
373
415
  timeout_ms?: number | undefined;
416
+ incident?: string | undefined;
374
417
  severity?: "warn" | "block" | undefined;
375
418
  autogen?: boolean | undefined;
376
419
  last_fired?: string | null | undefined;
420
+ promoted_at?: string | undefined;
377
421
  } | undefined;
378
422
  activation?: {
379
423
  keywords?: string[] | undefined;
@@ -683,6 +727,8 @@ interface PreventionReceiptRow {
683
727
  stage: "pre-commit" | "pre-push" | "ci" | "manual" | null;
684
728
  exit_code: number | null;
685
729
  message: string | null;
730
+ /** Incident provenance from the sensor frontmatter — the behaviour-harness link, when present. */
731
+ incident: string | null;
686
732
  }
687
733
  interface PreventionReceipt {
688
734
  generated_at: string;
@@ -700,6 +746,19 @@ declare function buildPreventionReceipt(events: PreventionEvent[], memories: Loa
700
746
  now?: Date;
701
747
  }): PreventionReceipt;
702
748
  declare function renderPreventionReceipt(receipt: PreventionReceipt): string;
749
+ /**
750
+ * Attribution footer for shared receipts — the growth loop. Every time a team pastes proof of
751
+ * prevented mistakes into Slack or a PR, the artifact names the tool that produced it. Kept as one
752
+ * constant so the CLI `--share` output and the CI PR comment carry identical wording.
753
+ */
754
+ declare const HIVELORE_ATTRIBUTION = "\uD83D\uDEE1\uFE0F Generated by [Hivelore](https://github.com/Doucs91/hivelore) \u2014 the deterministic policy gate for agent-written code.";
755
+ /**
756
+ * Markdown rendering of the receipt for `hivelore stats receipt --share` and the CI PR comment —
757
+ * ready to paste into Slack or a review. Includes incident provenance and the attribution footer.
758
+ * An empty window is NOT a dead end: it renders a forward CTA (turn an incident into a guardrail),
759
+ * so the receipt is useful on day one, before any prevention has been recorded.
760
+ */
761
+ declare function renderPreventionReceiptShare(receipt: PreventionReceipt): string;
703
762
  /** Read all catch events (skips malformed lines). */
704
763
  declare function loadPreventionEvents(paths: HaivePaths): Promise<PreventionEvent[]>;
705
764
  interface PreventionTrend {
@@ -1907,11 +1966,19 @@ interface CommandSensorSpec {
1907
1966
  severity: Sensor["severity"];
1908
1967
  /** LLM-facing self-correction message carried from the sensor. */
1909
1968
  message: string;
1969
+ /** Optional incident provenance carried from the sensor (ticket/prod ref this test guards). */
1970
+ incident?: string;
1910
1971
  /** Anchor/scoped paths this sensor cares about (for reporting). */
1911
1972
  paths: string[];
1912
1973
  /** Max runtime in ms (executor default applies when unset). */
1913
1974
  timeout_ms?: number;
1914
1975
  }
1976
+ /**
1977
+ * Render the incident-provenance suffix appended to a fired sensor's message. Empty when the sensor
1978
+ * carries no `incident` — so the behaviour-harness link ("guards the incident this test exists for")
1979
+ * shows up wherever a sensor speaks, without every call site re-deriving the copy.
1980
+ */
1981
+ declare function incidentSuffix(incident?: string): string;
1915
1982
  /**
1916
1983
  * Select the shell/test sensors that apply to `changedPaths`. With no changed paths (or a sensor
1917
1984
  * scoped to everywhere) the sensor is selected unconditionally. Pure: the caller executes commands.
@@ -2036,7 +2103,22 @@ declare function computeScopeHash(root: string, scopedFiles: string[]): string;
2036
2103
  * Deterministic health assessment. A flap is an adjacent fired/silent outcome change for the same
2037
2104
  * memory and identical scope hash inside the 30-day window. `unrunnable` rows never participate.
2038
2105
  */
2039
- declare function assessSensorHealth(evaluations: SensorEvaluation[], now?: Date): SensorHealth[];
2106
+ declare function assessSensorHealth(evaluations: SensorEvaluation[], now?: Date, opts?: {
2107
+ /**
2108
+ * memory_id → ISO timestamp of the sensor's last manual promotion back to block
2109
+ * (sensor.promoted_at). Evaluations at or before it are ignored: the promotion is the
2110
+ * human's assertion that the oracle was fixed, so pre-promotion flaps must not
2111
+ * re-quarantine it.
2112
+ */
2113
+ promotedAt?: ReadonlyMap<string, string>;
2114
+ }): SensorHealth[];
2115
+ /** Build the promoted_at map for {@link assessSensorHealth} from memory frontmatters. */
2116
+ declare function sensorPromotedAtMap(frontmatters: Iterable<{
2117
+ id: string;
2118
+ sensor?: {
2119
+ promoted_at?: string;
2120
+ } | null;
2121
+ }>): Map<string, string>;
2040
2122
  declare function quarantineNote(at: string, flapCount: number): string;
2041
2123
  /** Add or replace the single quarantine note. */
2042
2124
  declare function withQuarantineNote(body: string, at: string, flapCount: number): string;
@@ -2671,7 +2753,15 @@ declare function revertedShaFromCommit(commit: GitCommit): string | null;
2671
2753
  declare function existingGateMissShas(memories: LoadedMemory[]): Set<string>;
2672
2754
  declare function gatePassedShas(evaluations: SensorEvaluation[]): Set<string>;
2673
2755
  /** Build proposed, never-validated lessons from incremental revert/hotfix signals. */
2674
- declare function proposeGateMissDrafts(commits: GitCommit[], existingRevertedShas: Set<string>, passedShas: Set<string>): GateMissProposal[];
2756
+ declare function proposeGateMissDrafts(commits: GitCommit[], existingRevertedShas: Set<string>, passedShas: Set<string>, opts?: {
2757
+ /**
2758
+ * Returns true when a repo-relative path still exists on disk. Anchor candidates come from
2759
+ * the REVERT commit's file list — files the revert often just deleted. Anchoring a draft to
2760
+ * a deleted path makes the very next `sync` mark it stale, so the learning loop eats its own
2761
+ * drafts before anyone reviews them. When omitted, paths are kept (pure callers/tests).
2762
+ */
2763
+ pathExists?: (rel: string) => boolean;
2764
+ }): GateMissProposal[];
2675
2765
 
2676
2766
  /**
2677
2767
  * Pure stack-detection helpers for cold-start seeding.
@@ -2924,4 +3014,4 @@ interface AgentContext {
2924
3014
  }
2925
3015
  declare function detectAgentContext(env?: Record<string, string | undefined>): AgentContext;
2926
3016
 
2927
- 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 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 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, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, 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 PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedSensorVerdict, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, 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 SessionHandoffData, type SkillActivation, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, assessBootstrapState, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, detectAgentContext, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractSensorExamples, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasRecentBriefingMarker, hashProjectContext, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, 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 };
3017
+ 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 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 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 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 PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedSensorVerdict, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, 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 SessionHandoffData, type SkillActivation, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, assessBootstrapState, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, detectAgentContext, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractSensorExamples, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasRecentBriefingMarker, hashProjectContext, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, 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
@@ -49,12 +49,26 @@ var SensorSchema = z.object({
49
49
  paths: z.array(z.string()).default([]),
50
50
  /** LLM-facing self-correction message: what was done wrong and what to do instead. */
51
51
  message: z.string().min(1),
52
+ /**
53
+ * Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
54
+ * incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
55
+ * behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
56
+ * the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
57
+ */
58
+ incident: z.string().optional(),
52
59
  /** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
53
60
  severity: z.enum(["warn", "block"]).default("warn"),
54
61
  /** True when Hivelore generated this sensor automatically (vs. hand-authored). */
55
62
  autogen: z.boolean().default(false),
56
63
  /** ISO timestamp of the last time this sensor matched a diff. */
57
- last_fired: z.string().nullable().default(null)
64
+ last_fired: z.string().nullable().default(null),
65
+ /**
66
+ * ISO timestamp of the last manual `sensors promote` back to block. Health assessment ignores
67
+ * ledger evaluations older than this — without it, a promoted sensor whose oracle was FIXED is
68
+ * re-quarantined on the next commit for up to 30 days (the stale flaps are still in the window),
69
+ * making the promotion promised by the quarantine note a no-op.
70
+ */
71
+ promoted_at: z.string().optional()
58
72
  });
59
73
  var ActivationSchema = z.object({
60
74
  /** Case-insensitive substrings matched against the task text. */
@@ -936,7 +950,8 @@ function buildPreventionReceipt(events, memories, usage, options) {
936
950
  kind: event.kind ?? sensor?.kind ?? (event.source === "sensor" ? "regex" : null),
937
951
  stage: event.stage ?? null,
938
952
  exit_code: event.exit_code ?? null,
939
- message: sensor?.message ?? null
953
+ message: sensor?.message ?? null,
954
+ incident: sensor?.incident ?? null
940
955
  };
941
956
  }).sort((a, b) => b.at.localeCompare(a.at));
942
957
  const preventedCountTotal = Object.values(usage.by_id).reduce((sum, item) => sum + item.prevented_count, 0);
@@ -960,13 +975,44 @@ function renderPreventionReceipt(receipt) {
960
975
  const kind = row.kind ? `${row.kind} sensor` : row.source;
961
976
  const exit = row.exit_code === null ? "" : `, exit ${row.exit_code}`;
962
977
  const stage = row.stage ? ` \u2014 caught at ${row.stage}` : "";
963
- lines.push(` \u2717\u2192\u2713 ${row.at.slice(0, 10)} ${row.id.padEnd(32)} (${kind}${exit}${stage})`);
978
+ const incident = row.incident ? ` \u21A9 incident: ${row.incident}` : "";
979
+ lines.push(` \u2717\u2192\u2713 ${row.at.slice(0, 10)} ${row.id.padEnd(32)} (${kind}${exit}${stage})${incident}`);
964
980
  }
965
981
  lines.push(
966
982
  ` Trend: ${receipt.total} this window vs ${receipt.previous_total} previous window (${receipt.total <= receipt.previous_total ? "recurrences declining" : "recurrences rising"}).`
967
983
  );
968
984
  return lines.join("\n");
969
985
  }
986
+ var HIVELORE_ATTRIBUTION = "\u{1F6E1}\uFE0F Generated by [Hivelore](https://github.com/Doucs91/hivelore) \u2014 the deterministic policy gate for agent-written code.";
987
+ function renderPreventionReceiptShare(receipt) {
988
+ const lines = [`### \u{1F6E1}\uFE0F Hivelore prevention receipt \u2014 last ${receipt.window_days} days`, ""];
989
+ if (receipt.total === 0) {
990
+ lines.push(
991
+ "No repeat mistakes reached review in this window.",
992
+ "",
993
+ "Turn a past incident into a guardrail so it can never come back:",
994
+ '`hivelore memory tried \u2026 --sensor-command "<your test>"` (add `--incident <ref>` to link the incident it guards).'
995
+ );
996
+ } else {
997
+ lines.push(
998
+ `**${receipt.total} repeat mistake${receipt.total === 1 ? "" : "s"} refused before ${receipt.total === 1 ? "it" : "they"} reached review.**`,
999
+ ""
1000
+ );
1001
+ for (const row of receipt.events) {
1002
+ const kind = row.kind ? `${row.kind} sensor` : row.source;
1003
+ const exit = row.exit_code === null ? "" : `, exit ${row.exit_code}`;
1004
+ const stage = row.stage ? ` \u2014 caught at ${row.stage}` : "";
1005
+ const incident = row.incident ? ` \u21A9 incident: ${row.incident}` : "";
1006
+ lines.push(`- \u2717\u2192\u2713 \`${row.at.slice(0, 10)}\` **${row.title}** (${kind}${exit}${stage})${incident}`);
1007
+ }
1008
+ lines.push(
1009
+ "",
1010
+ `_Trend: ${receipt.total} this window vs ${receipt.previous_total} previous window (${receipt.total <= receipt.previous_total ? "recurrences declining" : "recurrences rising"})._`
1011
+ );
1012
+ }
1013
+ lines.push("", `<sub>${HIVELORE_ATTRIBUTION}</sub>`);
1014
+ return lines.join("\n");
1015
+ }
970
1016
  async function loadPreventionEvents(paths) {
971
1017
  const file = preventionLogPath(paths);
972
1018
  if (!existsSync4(file)) return [];
@@ -3912,6 +3958,10 @@ function runSensors(memories, targets) {
3912
3958
  }
3913
3959
  return hits;
3914
3960
  }
3961
+ function incidentSuffix(incident) {
3962
+ const ref = incident?.trim();
3963
+ return ref ? ` \u21A9 guards incident: ${ref}` : "";
3964
+ }
3915
3965
  function selectCommandSensors(memories, changedPaths) {
3916
3966
  const specs = [];
3917
3967
  for (const memory of memories) {
@@ -3929,6 +3979,7 @@ function selectCommandSensors(memories, changedPaths) {
3929
3979
  kind: sensor.kind,
3930
3980
  severity: sensor.severity,
3931
3981
  message: sensor.message,
3982
+ ...sensor.incident ? { incident: sensor.incident } : {},
3932
3983
  paths: sensor.paths.length > 0 ? sensor.paths : anchorPaths,
3933
3984
  ...sensor.timeout_ms ? { timeout_ms: sensor.timeout_ms } : {}
3934
3985
  });
@@ -4113,11 +4164,16 @@ function computeScopeHash(root, scopedFiles) {
4113
4164
  return "";
4114
4165
  }
4115
4166
  }
4116
- function assessSensorHealth(evaluations, now = /* @__PURE__ */ new Date()) {
4167
+ function assessSensorHealth(evaluations, now = /* @__PURE__ */ new Date(), opts = {}) {
4117
4168
  const cutoff = now.getTime() - 30 * DAY_MS;
4118
4169
  const byMemory = /* @__PURE__ */ new Map();
4119
4170
  for (const e of evaluations) {
4120
4171
  if (e.memory_id === "__gate__" || e.kind !== "shell" && e.kind !== "test") continue;
4172
+ const promotedAtIso = opts.promotedAt?.get(e.memory_id);
4173
+ if (promotedAtIso) {
4174
+ const promoted = Date.parse(promotedAtIso);
4175
+ if (Number.isFinite(promoted) && Date.parse(e.at) <= promoted) continue;
4176
+ }
4121
4177
  const list = byMemory.get(e.memory_id) ?? [];
4122
4178
  list.push(e);
4123
4179
  byMemory.set(e.memory_id, list);
@@ -4157,6 +4213,13 @@ function assessSensorHealth(evaluations, now = /* @__PURE__ */ new Date()) {
4157
4213
  }
4158
4214
  return out.sort((a, b) => a.memory_id.localeCompare(b.memory_id));
4159
4215
  }
4216
+ function sensorPromotedAtMap(frontmatters) {
4217
+ const out = /* @__PURE__ */ new Map();
4218
+ for (const fm of frontmatters) {
4219
+ if (fm.sensor?.promoted_at) out.set(fm.id, fm.sensor.promoted_at);
4220
+ }
4221
+ return out;
4222
+ }
4160
4223
  function quarantineNote(at, flapCount) {
4161
4224
  return `> Quarantined ${at}: oracle flapped ${flapCount}\xD7 on identical inputs \u2014 demoted block\u2192warn. Fix the test, then re-promote with \`hivelore sensors promote <id>\`.`;
4162
4225
  }
@@ -5349,7 +5412,7 @@ function shaMatches(set, sha) {
5349
5412
  }
5350
5413
  return false;
5351
5414
  }
5352
- function proposeGateMissDrafts(commits, existingRevertedShas, passedShas) {
5415
+ function proposeGateMissDrafts(commits, existingRevertedShas, passedShas, opts = {}) {
5353
5416
  const seeds = proposeSeedsFromCommits(commits, commits.length);
5354
5417
  const bySha = new Map(commits.map((commit) => [commit.sha, commit]));
5355
5418
  const seen = new Set(existingRevertedShas);
@@ -5361,7 +5424,7 @@ function proposeGateMissDrafts(commits, existingRevertedShas, passedShas) {
5361
5424
  if (shaMatches(seen, failedSha)) continue;
5362
5425
  seen.add(failedSha);
5363
5426
  const gatePassed = shaMatches(passedShas, failedSha);
5364
- const paths = (commit.files ?? []).slice(0, 8);
5427
+ const paths = (commit.files ?? []).filter((p) => !p.startsWith(".ai/")).filter((p) => opts.pathExists?.(p) ?? true).slice(0, 8);
5365
5428
  const base = `# Gate miss: ${seed.what}
5366
5429
 
5367
5430
  A git ${seed.kind} indicates that a change escaped the existing harness. This is a proposed lesson only; review the actual regression before validating it.
@@ -5374,7 +5437,7 @@ Subject: ${seed.what}
5374
5437
  **Why it failed / do NOT use:** ${seed.why_failed}
5375
5438
  `;
5376
5439
  const gateLine = gatePassed ? "\nThe gate PASSED this commit \u2014 a validated sensor here upgrades the harness.\n" : "";
5377
- const candidate = suggestSensorSeed(base, paths);
5440
+ const candidate = suggestSensorSeed(seed.what, paths);
5378
5441
  const sensorHint = candidate ? `
5379
5442
  proposed_sensor_seed: ${JSON.stringify(candidate)}
5380
5443
  ` : "\nproposed_sensor_seed: inspect the revert diff, then author a deterministic candidate with `hivelore sensors propose <id>`.\n";
@@ -5669,6 +5732,7 @@ export {
5669
5732
  HAIVE_DIR,
5670
5733
  HAIVE_OWNED_FILES,
5671
5734
  HANDOFF_FILENAME,
5735
+ HIVELORE_ATTRIBUTION,
5672
5736
  MEMORIES_DIR,
5673
5737
  MIN_WORD_LEN,
5674
5738
  MemoryFrontmatterSchema,
@@ -5769,6 +5833,7 @@ export {
5769
5833
  handoffFilePath,
5770
5834
  hasRecentBriefingMarker,
5771
5835
  hashProjectContext,
5836
+ incidentSuffix,
5772
5837
  inferModulesFromPaths,
5773
5838
  isAutoPromoteEligible,
5774
5839
  isAutoRecap,
@@ -5850,6 +5915,7 @@ export {
5850
5915
  renderBootstrapChecklist,
5851
5916
  renderCaughtForYou,
5852
5917
  renderPreventionReceipt,
5918
+ renderPreventionReceiptShare,
5853
5919
  resolveBriefingBudget,
5854
5920
  resolveHaivePaths,
5855
5921
  resolveManifestFiles,
@@ -5869,6 +5935,7 @@ export {
5869
5935
  sensorAppliesToPath,
5870
5936
  sensorLedgerPath,
5871
5937
  sensorPatternBrittleness,
5938
+ sensorPromotedAtMap,
5872
5939
  sensorSelfCheck,
5873
5940
  sensorTargetsFromDiff,
5874
5941
  serializeMemory,