@hiveai/core 0.15.0 → 0.17.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
@@ -795,6 +795,19 @@ declare const STACK_PACK_TAG = "stack-pack";
795
795
  declare function isStackPackSeed(fm: {
796
796
  tags?: string[];
797
797
  } | null | undefined): boolean;
798
+ /**
799
+ * Tags that mark a memory as a *local dev-environment workaround* (hot-swap, nested node_modules,
800
+ * global-install quirks) rather than repo-specific team policy. These are real, but they describe
801
+ * tooling debt, not unguessable team knowledge — and because they get read on almost every session
802
+ * their read_count inflates and they crowd the briefing. Ranking caps them at `background` UNLESS
803
+ * they directly anchor a file being edited, so they stop displacing actual policy. The fix for a
804
+ * recurring one is to repair the environment, not to keep surfacing the note.
805
+ */
806
+ declare const ENV_WORKAROUND_TAGS: Set<string>;
807
+ /** True when a memory is tagged as a local dev-environment workaround (see {@link ENV_WORKAROUND_TAGS}). */
808
+ declare function isEnvWorkaroundMemory(fm: {
809
+ tags?: string[];
810
+ } | null | undefined): boolean;
798
811
  /**
799
812
  * Best-effort inference: given a list of file paths, infer module names from
800
813
  * conventional layouts (packages/X/, apps/X/, modules/X/, src/X/).
@@ -1488,6 +1501,14 @@ declare function writeBriefingMarker(paths: HaivePaths, input: {
1488
1501
  source: string;
1489
1502
  memoryIds?: string[];
1490
1503
  files?: string[];
1504
+ /**
1505
+ * Accumulate memory_ids/files with the existing fresh marker for THIS session instead of
1506
+ * overwriting (default true). This is what lets decision-coverage build up as the agent works:
1507
+ * every get_briefing call, every pre-edit injection, every `haive briefing` ADDS to the
1508
+ * session's consulted set — so a broad commit no longer requires one giant briefing covering
1509
+ * every relevant decision at once. Pass false to replace (e.g. starting a brand-new session).
1510
+ */
1511
+ accumulate?: boolean;
1491
1512
  }): Promise<BriefingMarker>;
1492
1513
  declare function hasRecentBriefingMarker(paths: HaivePaths, sessionId?: string, ttlMs?: number): Promise<boolean>;
1493
1514
  declare function readRecentBriefingMarker(paths: HaivePaths, sessionId?: string, ttlMs?: number): Promise<BriefingMarker | null>;
@@ -2027,4 +2048,70 @@ interface MergeResult {
2027
2048
  */
2028
2049
  declare function mergeMemoryVersions(ours: string, theirs: string): MergeResult;
2029
2050
 
2030
- export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type Anchor, AnchorSchema, type AntiPatternGate, type AutoPromoteRule, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BreakingChange, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, 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_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, type FailureCoverageOptions, type FailureObservation, type Finding, type FindingSeverity, GUESSABLE_THRESHOLD, type GatePrecision, type GateTuningSuggestion, type GitCommit, HAIVE_DIR, type HaiveConfig, type HaivePaths, type HotFile, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, 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 PreventionRow, type PreventionSource, type PreventionTrend, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorHit, type SensorRow, SensorSchema, type SensorSuggestionOptions, type SensorTarget, 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, appendUsageEvent, briefingMarkerPath, briefingMarkersDir, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildReport, bumpRead, codeMapPath, collectTimelineEntries, compareEvalReports, compareImpact, compileRegexSensor, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, configPath, contractLockPath, deriveConfidence, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, extractActionsBriefBody, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, getUsage, globToRegExp, hasRecentBriefingMarker, hashProjectContext, inferModulesFromPaths, isAutoPromoteEligible, isCovered, isDecaying, isDistinctiveToken, isFreshIsoDate, isGlobPath, isLikelyGuessable, isRetiredMemory, isSkill, isSkillSuppressed, isStackPackSeed, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemory, loadPreventionEvents, loadUsageIndex, memoryFilePath, memoryMatchesAnchorPaths, mergeMemoryVersions, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseFindings, parseMemory, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, preventionLogPath, projectContextRecentlyEmitted, proposeSeedsFromCommits, pullCrossRepoSources, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readUsageEvents, recordApplied, recordPrevention, recordProjectContextEmission, recordRejection, relPathFrom, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scoreRetrievalCase, scoreSensorCase, selectCommandSensors, sensorAppliesToPath, sensorTargetsFromDiff, serializeMemory, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestTopicKey, summarizeImpact, synthesizeSelfEvalCases, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, writeBriefingMarker };
2051
+ /**
2052
+ * Recap compaction — keep the auto-generated session recap from dominating the briefing head.
2053
+ *
2054
+ * The MCP server auto-saves a minimal recap on exit (goal = "Auto-captured session (N tool calls)",
2055
+ * body = a raw tool-call/file dump). It's low signal, yet get_briefing shows the freshest recap's
2056
+ * full body at the very top of every briefing. A human/post_task recap (with a real Discoveries
2057
+ * section) is far richer. This module detects an auto recap and compresses it to its useful core
2058
+ * (the Discoveries, if any) so it informs without crowding. Pure, unit-tested.
2059
+ */
2060
+ /**
2061
+ * True when a recap body looks auto-generated (vs. a human/post_task recap). Auto recaps come in a
2062
+ * couple of shapes, all low-signal: the session-tracker's "Auto-captured session (N tool calls)" and
2063
+ * the run-wrapper's "Edited N files across M tool calls". The common tell is a raw tool-call count.
2064
+ */
2065
+ declare function isAutoRecap(body: string): boolean;
2066
+ /**
2067
+ * Return a compact version of an auto recap body: a one-line header (the Goal line) plus the
2068
+ * Discoveries section when it carries real content (e.g. detected failures). Non-auto recaps are
2069
+ * returned unchanged.
2070
+ */
2071
+ declare function compactAutoRecapBody(body: string, maxChars?: number): string;
2072
+
2073
+ type MemoryPriority = "must_read" | "useful" | "background";
2074
+ /**
2075
+ * Normalized priority evidence. A caller fills only the signals it can compute; unknown ones default
2076
+ * to false (see {@link DEFAULT_PRIORITY_SIGNALS}). The MCP path has semantic scores; the CLI path has
2077
+ * lexical scores — both reduce to these booleans.
2078
+ */
2079
+ interface PrioritySignals {
2080
+ /** Memory type (attempt, gotcha, skill, decision, …). */
2081
+ type: string;
2082
+ /** Memory tags — used for the stack-pack / env-workaround down-rank. */
2083
+ tags: string[];
2084
+ /** The memory demands explicit human approval — always surface first. */
2085
+ requiresHumanApproval: boolean;
2086
+ /** Anchored to a file the agent is editing. */
2087
+ directAnchor: boolean;
2088
+ /** Anchored to a symbol the agent requested. */
2089
+ directSymbol: boolean;
2090
+ /** Exact/literal task match (semantic match_quality "exact", or an exact lexical task hit). */
2091
+ exactTaskMatch: boolean;
2092
+ /** Strong semantic relevance (cosine ≥ 0.65). CLI has no embeddings → passes false. */
2093
+ strongSemantic: boolean;
2094
+ /** Useful-level relevance: semantic ≥ 0.35, a partial task hit, or a high lexical score. */
2095
+ usefulSemantic: boolean;
2096
+ /** Matched an inferred module or domain from the touched files. */
2097
+ moduleOrDomainMatch: boolean;
2098
+ /** A memory tag matched a task token. */
2099
+ tagTaskMatch: boolean;
2100
+ }
2101
+ declare const DEFAULT_PRIORITY_SIGNALS: PrioritySignals;
2102
+ /** Convenience: build a full signal set from a partial one. */
2103
+ declare function prioritySignals(partial: Partial<PrioritySignals>): PrioritySignals;
2104
+ /**
2105
+ * Classify a memory's briefing priority from its signals. Order matters:
2106
+ * 1. must_read — human-approval gates, direct anchor/symbol matches, and exact/strong hits on
2107
+ * negative (attempt) or skill memories: the things an agent must not miss.
2108
+ * 2. background (down-rank) — generic stack-pack seeds and local dev-environment workarounds never
2109
+ * claim `useful` on a semantic/tag match alone; they'd crowd out repo-specific knowledge. (A
2110
+ * direct anchor already promoted them to must_read above, so genuinely-relevant ones still rank.)
2111
+ * 3. useful — skills, module/domain matches, exact hits, and useful-level relevance.
2112
+ * 4. background — everything else.
2113
+ */
2114
+ declare function classifyMemoryPriority(signals: PrioritySignals): MemoryPriority;
2115
+ declare function priorityRank(priority: MemoryPriority): number;
2116
+
2117
+ export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type Anchor, AnchorSchema, type AntiPatternGate, type AutoPromoteRule, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BreakingChange, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, 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_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_PRIORITY_SIGNALS, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, 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 Finding, type FindingSeverity, GUESSABLE_THRESHOLD, type GatePrecision, type GateTuningSuggestion, type GitCommit, HAIVE_DIR, type HaiveConfig, type HaivePaths, type HotFile, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, 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 PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorHit, type SensorRow, SensorSchema, type SensorSuggestionOptions, type SensorTarget, 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, appendUsageEvent, briefingMarkerPath, briefingMarkersDir, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareImpact, compileRegexSensor, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, configPath, contractLockPath, deriveConfidence, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, extractActionsBriefBody, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, getUsage, globToRegExp, hasRecentBriefingMarker, hashProjectContext, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isRetiredMemory, isSkill, isSkillSuppressed, isStackPackSeed, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemory, loadPreventionEvents, loadUsageIndex, memoryFilePath, memoryMatchesAnchorPaths, mergeMemoryVersions, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseFindings, parseMemory, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeSeedsFromCommits, pullCrossRepoSources, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readUsageEvents, recordApplied, recordPrevention, recordProjectContextEmission, recordRejection, relPathFrom, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scoreRetrievalCase, scoreSensorCase, selectCommandSensors, sensorAppliesToPath, sensorTargetsFromDiff, serializeMemory, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestTopicKey, summarizeImpact, synthesizeSelfEvalCases, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, writeBriefingMarker };
package/dist/index.js CHANGED
@@ -318,6 +318,16 @@ var STACK_PACK_TAG = "stack-pack";
318
318
  function isStackPackSeed(fm) {
319
319
  return Boolean(fm?.tags?.includes(STACK_PACK_TAG));
320
320
  }
321
+ var ENV_WORKAROUND_TAGS = /* @__PURE__ */ new Set([
322
+ "dev-workflow",
323
+ "dev-env",
324
+ "hotswap",
325
+ "local-setup",
326
+ "tooling-debt"
327
+ ]);
328
+ function isEnvWorkaroundMemory(fm) {
329
+ return Boolean(fm?.tags?.some((t) => ENV_WORKAROUND_TAGS.has(t)));
330
+ }
321
331
  var MODULE_PATTERNS = [
322
332
  /^packages\/([^/]+)\//,
323
333
  /^apps\/([^/]+)\//,
@@ -2833,11 +2843,24 @@ function briefingMarkerPath(paths, sessionId) {
2833
2843
  return path16.join(briefingMarkersDir(paths), `${normalizeSessionId(sessionId)}.json`);
2834
2844
  }
2835
2845
  async function writeBriefingMarker(paths, input) {
2846
+ const sessionId = normalizeSessionId(input.sessionId);
2847
+ const accumulate = input.accumulate ?? true;
2848
+ let priorIds = [];
2849
+ let priorFiles = [];
2850
+ if (accumulate) {
2851
+ const existing = await readSessionBriefingMarker(paths, sessionId);
2852
+ if (existing) {
2853
+ priorIds = existing.memory_ids ?? [];
2854
+ priorFiles = existing.files ?? [];
2855
+ }
2856
+ }
2857
+ const mergedIds = [.../* @__PURE__ */ new Set([...priorIds, ...input.memoryIds ?? []])];
2858
+ const mergedFiles = [.../* @__PURE__ */ new Set([...priorFiles, ...input.files ?? []])];
2836
2859
  const marker = {
2837
- session_id: normalizeSessionId(input.sessionId),
2860
+ session_id: sessionId,
2838
2861
  ...input.task?.trim() ? { task: input.task.trim() } : {},
2839
- ...input.memoryIds && input.memoryIds.length > 0 ? { memory_ids: [...new Set(input.memoryIds)] } : {},
2840
- ...input.files && input.files.length > 0 ? { files: [...new Set(input.files)] } : {},
2862
+ ...mergedIds.length > 0 ? { memory_ids: mergedIds } : {},
2863
+ ...mergedFiles.length > 0 ? { files: mergedFiles } : {},
2841
2864
  source: input.source,
2842
2865
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
2843
2866
  root: paths.root
@@ -2850,6 +2873,18 @@ async function writeBriefingMarker(paths, input) {
2850
2873
  );
2851
2874
  return marker;
2852
2875
  }
2876
+ async function readSessionBriefingMarker(paths, sessionId, ttlMs = BRIEFING_MARKER_TTL_MS) {
2877
+ const file = briefingMarkerPath(paths, sessionId);
2878
+ if (!existsSync14(file)) return null;
2879
+ try {
2880
+ const marker = JSON.parse(await readFile13(file, "utf8"));
2881
+ const created = Date.parse(marker.created_at);
2882
+ if (!Number.isFinite(created) || Date.now() - created > ttlMs) return null;
2883
+ return marker;
2884
+ } catch {
2885
+ return null;
2886
+ }
2887
+ }
2853
2888
  async function hasRecentBriefingMarker(paths, sessionId, ttlMs = BRIEFING_MARKER_TTL_MS) {
2854
2889
  const now = Date.now();
2855
2890
  const candidates = [];
@@ -3823,6 +3858,64 @@ function mergeMemoryVersions(ours, theirs) {
3823
3858
  if (cmp < 0) return { content: ours, winner: "ours", reason: `newer created_at (${ca})` };
3824
3859
  return { content: ours, winner: "ours", reason: "tie \u2014 kept ours" };
3825
3860
  }
3861
+
3862
+ // src/recap.ts
3863
+ function isAutoRecap(body) {
3864
+ return /Auto-captured session/i.test(body) || /\bEdited \d+ files? across \d+ tool calls?/i.test(body) || /\b\d+ tool calls?\b/i.test(body);
3865
+ }
3866
+ function compactAutoRecapBody(body, maxChars = 600) {
3867
+ if (!isAutoRecap(body)) return body;
3868
+ const goalMatch = body.match(/##+\s*Goal[^\n]*\n+([^\n]+)/i);
3869
+ const callsMatch = body.match(/Auto-captured session \(([^)]+)\)/i);
3870
+ const header = goalMatch?.[1]?.trim() ? `_${goalMatch[1].trim()}_` : callsMatch ? `_Auto-captured session (${callsMatch[1]})._` : "_Auto-captured session._";
3871
+ const discMatch = body.match(/##+\s*Discoveries[^\n]*\n([\s\S]*?)(?=\n##+\s|\n*$)/i);
3872
+ const discovery = discMatch?.[1]?.trim() ?? "";
3873
+ const trivialDiscovery = discovery === "" || /^no (new memories|surprising)/i.test(discovery) || /No new memories saved this session\.?$/i.test(discovery);
3874
+ if (trivialDiscovery) {
3875
+ return `${header}
3876
+
3877
+ _No notable discoveries captured. Run post_task / \`mem_session_end\` for a richer recap._`;
3878
+ }
3879
+ const trimmed = discovery.length > maxChars ? discovery.slice(0, maxChars) + "\u2026" : discovery;
3880
+ return `${header}
3881
+
3882
+ **Discoveries:**
3883
+ ${trimmed}`;
3884
+ }
3885
+
3886
+ // src/priority.ts
3887
+ var DEFAULT_PRIORITY_SIGNALS = {
3888
+ type: "",
3889
+ tags: [],
3890
+ requiresHumanApproval: false,
3891
+ directAnchor: false,
3892
+ directSymbol: false,
3893
+ exactTaskMatch: false,
3894
+ strongSemantic: false,
3895
+ usefulSemantic: false,
3896
+ moduleOrDomainMatch: false,
3897
+ tagTaskMatch: false
3898
+ };
3899
+ function prioritySignals(partial) {
3900
+ return { ...DEFAULT_PRIORITY_SIGNALS, ...partial };
3901
+ }
3902
+ function classifyMemoryPriority(signals) {
3903
+ const isNegative = signals.type === "attempt";
3904
+ const isSkill2 = signals.type === "skill";
3905
+ if (signals.requiresHumanApproval || signals.directAnchor || signals.directSymbol || isNegative && (signals.exactTaskMatch || signals.strongSemantic) || isSkill2 && (signals.exactTaskMatch || signals.strongSemantic)) {
3906
+ return "must_read";
3907
+ }
3908
+ if (isStackPackSeed({ tags: signals.tags }) || isEnvWorkaroundMemory({ tags: signals.tags })) {
3909
+ return "background";
3910
+ }
3911
+ if (isSkill2 || signals.moduleOrDomainMatch || signals.exactTaskMatch || signals.usefulSemantic || signals.tagTaskMatch) {
3912
+ return "useful";
3913
+ }
3914
+ return "background";
3915
+ }
3916
+ function priorityRank(priority) {
3917
+ return priority === "must_read" ? 3 : priority === "useful" ? 2 : 1;
3918
+ }
3826
3919
  export {
3827
3920
  AUTOPILOT_DEFAULTS,
3828
3921
  ActivationSchema,
@@ -3839,6 +3932,8 @@ export {
3839
3932
  DEFAULT_CONFIDENCE_THRESHOLDS,
3840
3933
  DEFAULT_CONFIG,
3841
3934
  DEFAULT_DORMANT_DAYS,
3935
+ DEFAULT_PRIORITY_SIGNALS,
3936
+ ENV_WORKAROUND_TAGS,
3842
3937
  GUESSABLE_THRESHOLD,
3843
3938
  HAIVE_DIR,
3844
3939
  MEMORIES_DIR,
@@ -3876,8 +3971,10 @@ export {
3876
3971
  buildFrontmatter,
3877
3972
  buildReport,
3878
3973
  bumpRead,
3974
+ classifyMemoryPriority,
3879
3975
  codeMapPath,
3880
3976
  collectTimelineEntries,
3977
+ compactAutoRecapBody,
3881
3978
  compareEvalReports,
3882
3979
  compareImpact,
3883
3980
  compileRegexSensor,
@@ -3916,9 +4013,11 @@ export {
3916
4013
  hashProjectContext,
3917
4014
  inferModulesFromPaths,
3918
4015
  isAutoPromoteEligible,
4016
+ isAutoRecap,
3919
4017
  isCovered,
3920
4018
  isDecaying,
3921
4019
  isDistinctiveToken,
4020
+ isEnvWorkaroundMemory,
3922
4021
  isFreshIsoDate,
3923
4022
  isGlobPath,
3924
4023
  isLikelyGuessable,
@@ -3953,6 +4052,8 @@ export {
3953
4052
  pickSnippetNeedle,
3954
4053
  planConflictResolution,
3955
4054
  preventionLogPath,
4055
+ priorityRank,
4056
+ prioritySignals,
3956
4057
  projectContextRecentlyEmitted,
3957
4058
  proposeSeedsFromCommits,
3958
4059
  pullCrossRepoSources,