@hivelore/core 0.58.0 → 0.59.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
@@ -2745,7 +2745,10 @@ declare const SENSOR_ABSENT_LOOKBACK = 2;
2745
2745
  declare function compileRegexSensor(sensor: Sensor): RegExp | null;
2746
2746
  /**
2747
2747
  * Blank comment spans in scannable text so a sensor's regex matches CODE, not the prose that
2748
- * documents it. Returns `content` unchanged for unknown file types. Pure.
2748
+ * documents it including MULTI-LINE block comments whose forbidden token sits on a middle line
2749
+ * that starts with neither the opener nor `*` (field report 2026-09-04 §3.1: a `bg-emerald-600` in a
2750
+ * multi-line CSS comment still tripped the sensor because the earlier fix was purely per-line).
2751
+ * Returns `content` unchanged for unknown file types. Pure.
2749
2752
  */
2750
2753
  declare function stripCommentsForScan(content: string, path: string): string;
2751
2754
  /**
@@ -4009,6 +4012,18 @@ declare function compactAutoRecapBody(body: string, maxChars?: number): string;
4009
4012
  * recaps still route through {@link compactAutoRecapBody}. Pure.
4010
4013
  */
4011
4014
  declare function recapBriefingExcerpt(body: string, maxChars?: number): string;
4015
+ /** Heading that separates the current recap from the archived per-session history. */
4016
+ declare const RECAP_HISTORY_HEADING = "## Session history";
4017
+ /** How many past sessions to retain — bounded so the recap file cannot grow without limit. */
4018
+ declare const RECAP_HISTORY_MAX = 6;
4019
+ /**
4020
+ * Fold the previous recap into a bounded per-session history so a topic-upsert stops destroying the
4021
+ * record of earlier sessions (field report 2026-09-01 §5.6: "I can't know what the last three
4022
+ * sessions did"). The NEW session's full recap stays at the top — so `recapBriefingExcerpt` still
4023
+ * surfaces only the latest goal + next steps — with the previous session archived as one compact
4024
+ * entry beneath a `## Session history` heading, capped at {@link RECAP_HISTORY_MAX} entries. Pure.
4025
+ */
4026
+ declare function buildRecapWithHistory(newMainBody: string, previousBody: string | null, previousDateISO: string | null, maxEntries?: number): string;
4012
4027
 
4013
4028
  /** Filename of the ephemeral handoff at the repo root. */
4014
4029
  declare const HANDOFF_FILENAME = "NEXT.md";
@@ -4177,4 +4192,4 @@ interface ReviewDraftOptions {
4177
4192
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
4178
4193
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
4179
4194
 
4180
- export { ADAPTIVE_FLOOR_MIN_SAMPLES, AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, type AnchorAuditRow, type AnchorChurn, AnchorSchema, type AntiPatternGate, type AppendFrictionInput, type AppendFrictionResult, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BaselineHealth, type BehaviourCoverageInput, type BehaviourCoverageMetrics, type BehaviourOracleInfo, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, CONTENT_CATCH_CODES, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractCheck, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_POSTURE, DEFAULT_PRIORITY_SIGNALS, DEFAULT_SPECIFICITY, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DistilledFailureLesson, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, FRICTION_FIELD_MAX, FRICTION_LOG_FILE, FRICTION_STATE_FILE, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, type FrictionGroup, type FrictionKind, type FrictionReport, type FrictionState, type FrictionStateEntry, type FrictionStatus, GATE_REMINDER_WINDOW_MS, GUESSABLE_THRESHOLD, type GateFinding, type GateMissProposal, type GatePolicy, type GatePolicyInput, type GatePosture, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateSeverity, type GateStage, type GateTuningSuggestion, type GateVerdict, type GateVerdictInput, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, type GithubReleaseCode, type GithubReleaseInput, type GithubReleaseVerdict, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, HIVELORE_ATTRIBUTION, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type IncidentHints, type InvalidMemoryFile, LEGACY_CONFIG_FILE, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, type NpmPublicationCode, type NpmPublicationInput, type NpmPublicationVerdict, PREVENTION_DEBOUNCE_MS, PREVENTION_RECEIPT_MARKER, PROCESS_GATE_CODES, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, type PreventionCommentFinding, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedEvalSpec, type ProposedSensorVerdict, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, SETUP_GATE_CODES, STACK_PACK_TAG, type ScaffoldLoopGap, type ScaffoldOptions, type ScaffoldStyle, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, WEAK_ANCHOR_CHURN_RATIO, adaptiveSemanticFloor, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, anchorMatchesComponent, anchorSpecificity, antiPatternGateParams, appendEvalHistory, appendFrictionReport, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, auditAnchorSpecificity, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildBaselineHealthFinding, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, changedPathsFromDiff, churnForAnchors, classifyGithubRelease, classifyMemoryPriority, classifyNpmPublication, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compareVersions, compileRegexSensor, componentOf, computeBaselineHealth, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, decideVerdict, dedupeRefusals, deriveConfidence, deriveMainAreas, describePosture, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, explainSensorRejection, extractActionsBriefBody, extractCorrectApproachExamples, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, formatFrictionIssue, frictionFingerprint, frictionLogPath, frictionStatePath, gatePassedShas, generateBridges, getUsage, globToRegExp, groupFriction, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isHarnessErrorOutput, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, isWeakAnchor, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadFrictionState, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, mineSensorSeedFromDiff, moduleNameOf, newMemoryId, normalizeChurnPath, normalizeFindingSeverity, normalizeFramework, normalizeFrictionSummary, normalizeKind, normalizeScaffoldStyle, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readFrictionReports, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recapBriefingExcerpt, recommendFeedbackAdjustment, recordApplied, recordGateReminder, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionComment, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveGatePolicy, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runPresenceSensors, runRegexSensor, runSensors, runTierContract, runValidationContract, runtimeJournalPath, saveCodeMap, saveConfig, saveFrictionState, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeCodeMap, serializeMemory, setFrictionStatus, shouldExpandGateReminder, snapshotContract, specificityScore, stripCommentsForScan, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
4195
+ export { ADAPTIVE_FLOOR_MIN_SAMPLES, AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, type AnchorAuditRow, type AnchorChurn, AnchorSchema, type AntiPatternGate, type AppendFrictionInput, type AppendFrictionResult, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BaselineHealth, type BehaviourCoverageInput, type BehaviourCoverageMetrics, type BehaviourOracleInfo, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, CONTENT_CATCH_CODES, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractCheck, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_POSTURE, DEFAULT_PRIORITY_SIGNALS, DEFAULT_SPECIFICITY, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DistilledFailureLesson, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, FRICTION_FIELD_MAX, FRICTION_LOG_FILE, FRICTION_STATE_FILE, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, type FrictionGroup, type FrictionKind, type FrictionReport, type FrictionState, type FrictionStateEntry, type FrictionStatus, GATE_REMINDER_WINDOW_MS, GUESSABLE_THRESHOLD, type GateFinding, type GateMissProposal, type GatePolicy, type GatePolicyInput, type GatePosture, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateSeverity, type GateStage, type GateTuningSuggestion, type GateVerdict, type GateVerdictInput, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, type GithubReleaseCode, type GithubReleaseInput, type GithubReleaseVerdict, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, HIVELORE_ATTRIBUTION, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type IncidentHints, type InvalidMemoryFile, LEGACY_CONFIG_FILE, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, type NpmPublicationCode, type NpmPublicationInput, type NpmPublicationVerdict, PREVENTION_DEBOUNCE_MS, PREVENTION_RECEIPT_MARKER, PROCESS_GATE_CODES, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, type PreventionCommentFinding, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedEvalSpec, type ProposedSensorVerdict, RECAP_HISTORY_HEADING, RECAP_HISTORY_MAX, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, SETUP_GATE_CODES, STACK_PACK_TAG, type ScaffoldLoopGap, type ScaffoldOptions, type ScaffoldStyle, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, WEAK_ANCHOR_CHURN_RATIO, adaptiveSemanticFloor, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, anchorMatchesComponent, anchorSpecificity, antiPatternGateParams, appendEvalHistory, appendFrictionReport, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, auditAnchorSpecificity, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildBaselineHealthFinding, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildRecapWithHistory, buildReport, bumpRead, changedPathsFromDiff, churnForAnchors, classifyGithubRelease, classifyMemoryPriority, classifyNpmPublication, codeMapContentHash, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compareVersions, compileRegexSensor, componentOf, computeBaselineHealth, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, decideVerdict, dedupeRefusals, deriveConfidence, deriveMainAreas, describePosture, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, explainSensorRejection, extractActionsBriefBody, extractCorrectApproachExamples, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, formatFrictionIssue, frictionFingerprint, frictionLogPath, frictionStatePath, gatePassedShas, generateBridges, getUsage, globToRegExp, groupFriction, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isHarnessErrorOutput, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, isWeakAnchor, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadFrictionState, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, mineSensorSeedFromDiff, moduleNameOf, newMemoryId, normalizeChurnPath, normalizeFindingSeverity, normalizeFramework, normalizeFrictionSummary, normalizeKind, normalizeScaffoldStyle, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readFrictionReports, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recapBriefingExcerpt, recommendFeedbackAdjustment, recordApplied, recordGateReminder, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionComment, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveConfigPath, resolveGatePolicy, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runPresenceSensors, runRegexSensor, runSensors, runTierContract, runValidationContract, runtimeJournalPath, saveCodeMap, saveConfig, saveFrictionState, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeCodeMap, serializeMemory, setFrictionStatus, shouldExpandGateReminder, snapshotContract, specificityScore, stripCommentsForScan, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
package/dist/index.js CHANGED
@@ -960,7 +960,7 @@ function applyFeedbackAdjustment(fm, adjustment, now = /* @__PURE__ */ new Date(
960
960
  }
961
961
 
962
962
  // src/prevention.ts
963
- import { appendFile, mkdir as mkdir2, readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
963
+ import { appendFile, mkdir as mkdir2, readFile as readFile4 } from "fs/promises";
964
964
  import { existsSync as existsSync4 } from "fs";
965
965
  import path6 from "path";
966
966
  function preventionLogPath(paths) {
@@ -988,22 +988,8 @@ async function recordPreventionHits(paths, firedIds, source, now = /* @__PURE__
988
988
  await appendPreventionEvent(paths, { at, id, source, ...details[id] }).catch(() => {
989
989
  });
990
990
  }
991
- await stampSensorLastFired(paths, recordedIds, at).catch(() => {
992
- });
993
991
  return recordedIds;
994
992
  }
995
- async function stampSensorLastFired(paths, ids, at) {
996
- if (ids.length === 0 || !existsSync4(paths.memoriesDir)) return;
997
- const wanted = new Set(ids);
998
- const loaded = await loadMemoriesFromDir(paths.memoriesDir);
999
- for (const { memory, filePath } of loaded) {
1000
- const fm = memory.frontmatter;
1001
- if (!wanted.has(fm.id) || !fm.sensor || fm.sensor.last_fired === at) continue;
1002
- const next = { ...memory, frontmatter: { ...fm, sensor: { ...fm.sensor, last_fired: at } } };
1003
- await writeFile2(filePath, serializeMemory(next), "utf8").catch(() => {
1004
- });
1005
- }
1006
- }
1007
993
  function buildPreventionReceipt(events, memories, usage, options) {
1008
994
  const now = options.now ?? /* @__PURE__ */ new Date();
1009
995
  const sinceMs = options.since.getTime();
@@ -1704,6 +1690,11 @@ function bridgeMemorySummary(body) {
1704
1690
  const oneLine2 = firstLine.replace(/\s+/g, " ");
1705
1691
  return oneLine2.length > 140 ? oneLine2.slice(0, 137) + "\u2026" : oneLine2;
1706
1692
  }
1693
+ function breadcrumbTypeRank(type) {
1694
+ if (type === "attempt") return 0;
1695
+ if (type === "architecture" || type === "decision") return 1;
1696
+ return 2;
1697
+ }
1707
1698
  function prepareBridgeData(memories, sensors, opts) {
1708
1699
  const max = opts?.maxMemories ?? 8;
1709
1700
  const topMemories = memories.filter((m) => {
@@ -1713,8 +1704,12 @@ function prepareBridgeData(memories, sensors, opts) {
1713
1704
  if (m.frontmatter.tags?.includes("stack-pack") || m.frontmatter.tags?.includes("seed")) return false;
1714
1705
  return s === "validated" || s === "proposed";
1715
1706
  }).sort((a, b) => {
1716
- const score = (m) => m.frontmatter.status === "validated" ? 2 : 1;
1717
- return score(b) - score(a);
1707
+ const statusScore = (m) => m.frontmatter.status === "validated" ? 0 : 1;
1708
+ const s = statusScore(a) - statusScore(b);
1709
+ if (s !== 0) return s;
1710
+ const r = breadcrumbTypeRank(a.frontmatter.type) - breadcrumbTypeRank(b.frontmatter.type);
1711
+ if (r !== 0) return r;
1712
+ return b.frontmatter.id.localeCompare(a.frontmatter.id);
1718
1713
  }).slice(0, max).map((m) => ({
1719
1714
  id: m.frontmatter.id,
1720
1715
  scope: m.frontmatter.scope,
@@ -1758,7 +1753,6 @@ function renderSensorsBlock(blockSensors) {
1758
1753
  for (const s of blockSensors) {
1759
1754
  const pathNote = s.paths.length > 0 ? ` _(applies to: ${s.paths.join(", ")})_` : "";
1760
1755
  lines.push(`- **${s.id}**${pathNote}: ${s.message}`);
1761
- if (s.pattern) lines.push(` - Pattern: \`${s.pattern}\``);
1762
1756
  }
1763
1757
  lines.push("", BRIDGE_MARKERS.sensorsEnd);
1764
1758
  return lines.join("\n");
@@ -1926,13 +1920,21 @@ function commentSyntaxForPath(path22) {
1926
1920
  if (dot < 0) return null;
1927
1921
  return COMMENT_SYNTAX_BY_EXT[base.slice(dot + 1).toLowerCase()] ?? null;
1928
1922
  }
1929
- function blankCommentsOnLine(line, syntax) {
1930
- if (syntax.starContinuation && /^\*(\s|\/|$)/.test(line.trimStart())) {
1931
- return " ".repeat(line.length);
1932
- }
1923
+ function blankCommentsOnLine(line, syntax, inBlock) {
1933
1924
  let out = "";
1934
1925
  let stringDelim = null;
1935
- for (let i = 0; i < line.length; i++) {
1926
+ let i = 0;
1927
+ if (inBlock) {
1928
+ if (!syntax.block) return { text: line, inBlock: false };
1929
+ const close = syntax.block[1];
1930
+ const closeIdx = line.indexOf(close);
1931
+ if (closeIdx === -1) return { text: " ".repeat(line.length), inBlock: true };
1932
+ out += " ".repeat(closeIdx + close.length);
1933
+ i = closeIdx + close.length;
1934
+ } else if (syntax.starContinuation && /^\*(\s|\/|$)/.test(line.trimStart())) {
1935
+ return { text: " ".repeat(line.length), inBlock: false };
1936
+ }
1937
+ for (; i < line.length; i++) {
1936
1938
  const ch = line[i];
1937
1939
  if (stringDelim) {
1938
1940
  out += ch;
@@ -1953,9 +1955,12 @@ function blankCommentsOnLine(line, syntax) {
1953
1955
  const [open, close] = syntax.block;
1954
1956
  if (line.startsWith(open, i)) {
1955
1957
  const closeIdx = line.indexOf(close, i + open.length);
1956
- const end = closeIdx === -1 ? line.length : closeIdx + close.length;
1958
+ if (closeIdx === -1) {
1959
+ out += " ".repeat(line.length - i);
1960
+ return { text: out, inBlock: true };
1961
+ }
1962
+ const end = closeIdx + close.length;
1957
1963
  out += " ".repeat(end - i);
1958
- if (closeIdx === -1) break;
1959
1964
  i = end - 1;
1960
1965
  continue;
1961
1966
  }
@@ -1971,12 +1976,19 @@ function blankCommentsOnLine(line, syntax) {
1971
1976
  if (hitLineComment) break;
1972
1977
  out += ch;
1973
1978
  }
1974
- return out;
1979
+ return { text: out, inBlock: false };
1975
1980
  }
1976
1981
  function stripCommentsForScan(content, path22) {
1977
1982
  const syntax = commentSyntaxForPath(path22);
1978
1983
  if (!syntax) return content;
1979
- return content.split("\n").map((l) => blankCommentsOnLine(l, syntax)).join("\n");
1984
+ let inBlock = false;
1985
+ const out = [];
1986
+ for (const line of content.split("\n")) {
1987
+ const res = blankCommentsOnLine(line, syntax, inBlock);
1988
+ out.push(res.text);
1989
+ inBlock = res.inBlock;
1990
+ }
1991
+ return out.join("\n");
1980
1992
  }
1981
1993
  function runRegexSensor(memoryId, sensor, target) {
1982
1994
  const re = compileRegexSensor(sensor);
@@ -7377,6 +7389,34 @@ ${next}` : "_No next steps recorded \u2014 `mem_get <id>` for the full recap._")
7377
7389
  if (out.length > maxChars) out = out.slice(0, maxChars).trimEnd() + "\u2026";
7378
7390
  return out;
7379
7391
  }
7392
+ var RECAP_HISTORY_HEADING = "## Session history";
7393
+ var RECAP_HISTORY_MAX = 6;
7394
+ function summarizeRecapForHistory(mainBody, dateISO) {
7395
+ const goal = mainBody.match(/##+\s*Goal[^\n]*\n+([^\n]+)/i)?.[1]?.trim() ?? "";
7396
+ const next = mainBody.match(/##+\s*Next steps?[^\n]*\n([\s\S]*?)(?=\n##+\s|$)/i)?.[1]?.trim() ?? "";
7397
+ const date = /^\d{4}-\d{2}-\d{2}/.test(dateISO) ? dateISO.slice(0, 10) : dateISO;
7398
+ const lines = [`### ${date}`];
7399
+ if (goal) lines.push(goal);
7400
+ if (next) lines.push(`**Next:** ${next.replace(/\s*\n+\s*/g, " ").slice(0, 300)}`);
7401
+ return lines.join("\n");
7402
+ }
7403
+ function buildRecapWithHistory(newMainBody, previousBody, previousDateISO, maxEntries = RECAP_HISTORY_MAX) {
7404
+ if (!previousBody?.trim()) return newMainBody;
7405
+ const marker = `
7406
+ ${RECAP_HISTORY_HEADING}`;
7407
+ const idx = previousBody.indexOf(marker);
7408
+ const prevMain = (idx >= 0 ? previousBody.slice(0, idx) : previousBody).trimEnd();
7409
+ const prevHistory = idx >= 0 ? previousBody.slice(idx + marker.length).replace(/^\s+/, "").trimEnd() : "";
7410
+ const archived = summarizeRecapForHistory(prevMain, previousDateISO ?? (/* @__PURE__ */ new Date()).toISOString());
7411
+ const combined = [archived, prevHistory].filter(Boolean).join("\n\n");
7412
+ const kept = combined.split(/\n(?=### )/).slice(0, maxEntries).join("\n");
7413
+ return `${newMainBody.trimEnd()}
7414
+
7415
+ ${RECAP_HISTORY_HEADING}
7416
+
7417
+ ${kept}
7418
+ `;
7419
+ }
7380
7420
 
7381
7421
  // src/handoff.ts
7382
7422
  import { writeFile as writeFile13, readFile as readFile18, stat as stat4 } from "fs/promises";
@@ -7605,6 +7645,8 @@ export {
7605
7645
  PROCESS_GATE_CODES,
7606
7646
  PROJECT_CONTEXT_FILE,
7607
7647
  PROJECT_CONTEXT_THROTTLE_MS,
7648
+ RECAP_HISTORY_HEADING,
7649
+ RECAP_HISTORY_MAX,
7608
7650
  REVIEW_LEARNING_MARKER,
7609
7651
  RUNTIME_JOURNAL_FILENAME,
7610
7652
  SCAFFOLD_MARKER_RE,
@@ -7658,6 +7700,7 @@ export {
7658
7700
  buildHandoffMarkdown,
7659
7701
  buildPreventionReceipt,
7660
7702
  buildProposeCommand,
7703
+ buildRecapWithHistory,
7661
7704
  buildReport,
7662
7705
  bumpRead,
7663
7706
  changedPathsFromDiff,