@hiveai/core 0.14.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/).
@@ -1137,6 +1150,29 @@ interface HaiveConfig {
1137
1150
  * Default: "anchored" — makes "known bad approaches are blocked" true for the precise case.
1138
1151
  */
1139
1152
  antiPatternGate?: "off" | "review" | "anchored" | "strict";
1153
+ /**
1154
+ * Execute `kind: "shell" | "test"` memory sensors during `haive sensors check`.
1155
+ * These run arbitrary repo-authored commands, so they are OFF by default; turn on per repo
1156
+ * (or pass `--commands`) once the team trusts the sensors. Regex sensors always run. Default false.
1157
+ */
1158
+ runCommandSensors?: boolean;
1159
+ /**
1160
+ * How `haive enforce finish` reacts to hard failures observed this session that were never
1161
+ * captured as a lesson (`mem_tried`):
1162
+ * - off: ignore
1163
+ * - warn: surface them as an info finding (default — failure detection has false positives)
1164
+ * - block: hard-block finish until each is captured
1165
+ * Default: "warn".
1166
+ */
1167
+ failureCaptureGate?: "off" | "warn" | "block";
1168
+ /**
1169
+ * How `haive eval --ci` reacts to a harness-quality regression vs the recorded baseline:
1170
+ * - off: never block
1171
+ * - warn: report the drop (default)
1172
+ * - block: exit non-zero on any score drop
1173
+ * Default: "warn".
1174
+ */
1175
+ evalRegressionGate?: "off" | "warn" | "block";
1140
1176
  /**
1141
1177
  * Default unread-age window (in days) for `haive memory archive` corpus decay.
1142
1178
  * A noisy or stale corpus is actively harmful — it makes the agent follow outdated policy.
@@ -1465,6 +1501,14 @@ declare function writeBriefingMarker(paths: HaivePaths, input: {
1465
1501
  source: string;
1466
1502
  memoryIds?: string[];
1467
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;
1468
1512
  }): Promise<BriefingMarker>;
1469
1513
  declare function hasRecentBriefingMarker(paths: HaivePaths, sessionId?: string, ttlMs?: number): Promise<boolean>;
1470
1514
  declare function readRecentBriefingMarker(paths: HaivePaths, sessionId?: string, ttlMs?: number): Promise<BriefingMarker | null>;
@@ -1545,6 +1589,27 @@ declare function runRegexSensor(memoryId: string, sensor: Sensor, target: Sensor
1545
1589
  * are the CLI's responsibility). At most one hit per (memory, file) pair is returned.
1546
1590
  */
1547
1591
  declare function runSensors(memories: Memory[], targets: SensorTarget[]): SensorHit[];
1592
+ /**
1593
+ * A shell/test sensor selected for execution — the feedback *computational* layer that a regex
1594
+ * can't express. The schema reserves `kind: "shell" | "test"`; this picks the ones whose memory
1595
+ * applies to the changed paths so the CLI can run `command` (core stays pure — it never executes).
1596
+ */
1597
+ interface CommandSensorSpec {
1598
+ memory_id: string;
1599
+ /** Command to execute (shell or test runner invocation). */
1600
+ command: string;
1601
+ kind: "shell" | "test";
1602
+ severity: Sensor["severity"];
1603
+ /** LLM-facing self-correction message carried from the sensor. */
1604
+ message: string;
1605
+ /** Anchor/scoped paths this sensor cares about (for reporting). */
1606
+ paths: string[];
1607
+ }
1608
+ /**
1609
+ * Select the shell/test sensors that apply to `changedPaths`. With no changed paths (or a sensor
1610
+ * scoped to everywhere) the sensor is selected unconditionally. Pure: the caller executes commands.
1611
+ */
1612
+ declare function selectCommandSensors(memories: Memory[], changedPaths: string[]): CommandSensorSpec[];
1548
1613
  /** Split a unified diff into per-file targets containing only added lines. */
1549
1614
  declare function sensorTargetsFromDiff(diff: string): SensorTarget[];
1550
1615
  /**
@@ -1650,6 +1715,47 @@ declare function draftsFromFindings(findings: Finding[], options?: DraftsOptions
1650
1715
  /** Drop drafts whose topic already exists in the corpus (cross-run dedup). */
1651
1716
  declare function filterNewDrafts(drafts: MemoryDraft[], existingTopics: Iterable<string>): MemoryDraft[];
1652
1717
 
1718
+ /**
1719
+ * Gate signal-quality — is the inferential (anti-pattern) gate earning trust or crying wolf?
1720
+ *
1721
+ * hAIve's anti-pattern gate is probabilistic and warmup-sensitive, so it is deliberately calibrated
1722
+ * NOT to hard-block on weak matches. But a team needs to SEE whether the gate's signal is precise:
1723
+ * are its catches turning out to be real (prevented mistakes, applied lessons) or noise (rejected by
1724
+ * humans via `mem_feedback`)? This module turns the signals hAIve already records — prevention events
1725
+ * (by source) and per-memory rejection counts — into a precision indicator and an actionable tuning
1726
+ * suggestion for `enforcement.antiPatternGate`. Pure: no I/O.
1727
+ */
1728
+
1729
+ interface GatePrecision {
1730
+ /** Catches recorded by deterministic regex/command sensors. */
1731
+ sensor_catches: number;
1732
+ /** Catches recorded by the inferential anti-pattern gate. */
1733
+ anti_pattern_catches: number;
1734
+ /** Total "useful" outcomes (catches + human-applied lessons). */
1735
+ useful: number;
1736
+ /** Total human rejections (mem_feedback "not useful"). Proxy for false positives. */
1737
+ rejections: number;
1738
+ /** useful / (useful + rejections), 0..1. Null when there is no signal yet. */
1739
+ precision: number | null;
1740
+ /** A tuning recommendation for enforcement.antiPatternGate, or null when current looks right. */
1741
+ suggestion: GateTuningSuggestion | null;
1742
+ }
1743
+ interface GateTuningSuggestion {
1744
+ recommended: AntiPatternGate;
1745
+ reason: string;
1746
+ }
1747
+ /**
1748
+ * Compute the gate's signal quality from prevention events + usage.
1749
+ * @param currentGate the configured antiPatternGate, used to decide whether to suggest a change.
1750
+ */
1751
+ declare function computeGatePrecision(events: PreventionEvent[], usage: UsageIndex, currentGate?: AntiPatternGate): GatePrecision;
1752
+ /**
1753
+ * Suggest loosening the gate when it is noisy (low precision with real rejection volume), or
1754
+ * tightening it when it is precise but currently soft. Returns null when current looks right or
1755
+ * there isn't enough signal to act on.
1756
+ */
1757
+ declare function suggestGate(precision: number | null, rejections: number, currentGate: AntiPatternGate): GateTuningSuggestion | null;
1758
+
1653
1759
  interface DashboardOptions {
1654
1760
  /** How many rows to include in each "top" list. Default 10. */
1655
1761
  top?: number;
@@ -1658,6 +1764,8 @@ interface DashboardOptions {
1658
1764
  now?: Date;
1659
1765
  /** Prevention event log (from `loadPreventionEvents`) — powers the trend + recurrence rollups. */
1660
1766
  preventionEvents?: PreventionEvent[];
1767
+ /** Configured anti-pattern gate — lets the gate-precision rollup suggest tightening/loosening. */
1768
+ antiPatternGate?: AntiPatternGate;
1661
1769
  }
1662
1770
  interface ImpactRow {
1663
1771
  id: string;
@@ -1730,6 +1838,8 @@ interface DashboardReport {
1730
1838
  /** Lessons re-introduced after capture (caught on >= 2 distinct days). */
1731
1839
  recurrence: RecurrenceReport;
1732
1840
  };
1841
+ /** Inferential-gate signal quality: are catches real (useful) or noise (rejected)? + tuning hint. */
1842
+ gate_precision: GatePrecision;
1733
1843
  corpus: {
1734
1844
  /** Number of memory files (policy corpus, excludes session_recap). */
1735
1845
  memory_files: number;
@@ -1741,4 +1851,267 @@ interface DashboardReport {
1741
1851
  /** Build the full observability rollup from the loaded corpus + usage index. Pure. */
1742
1852
  declare function buildDashboard(memories: LoadedMemory[], usage: UsageIndex, options?: DashboardOptions): DashboardReport;
1743
1853
 
1744
- 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 ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ContractDiffResult, type ContractFile, type ContractSnapshot, 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 EvalReport, type EvalSpec, type Finding, type FindingSeverity, GUESSABLE_THRESHOLD, HAIVE_DIR, type HaiveConfig, type HaivePaths, 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 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 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 UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendPreventionEvent, appendRuntimeJournalEntry, appendUsageEvent, briefingMarkerPath, briefingMarkersDir, buildCodeMap, buildDashboard, buildDocFrequency, buildFrontmatter, buildReport, bumpRead, codeMapPath, collectTimelineEntries, compareEvalReports, compareImpact, compileRegexSensor, computeImpact, computePreventionTrend, computeRecurrence, configPath, contractLockPath, deriveConfidence, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evaluateSkillActivation, extractActionsBriefBody, extractSnippet, filterNewDrafts, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findingBody, findingToDraft, firstMemoryOneLine, getUsage, globToRegExp, hasRecentBriefingMarker, hashProjectContext, inferModulesFromPaths, isAutoPromoteEligible, isDecaying, isDistinctiveToken, isFreshIsoDate, isGlobPath, isLikelyGuessable, isRetiredMemory, isSkill, isSkillSuppressed, isStackPackSeed, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadMemoriesFromDir, loadMemory, loadPreventionEvents, loadUsageIndex, memoryFilePath, memoryMatchesAnchorPaths, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseFindings, parseMemory, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, preventionLogPath, projectContextRecentlyEmitted, pullCrossRepoSources, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readUsageEvents, recordApplied, recordPrevention, recordProjectContextEmission, recordRejection, relPathFrom, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scoreRetrievalCase, scoreSensorCase, sensorAppliesToPath, sensorTargetsFromDiff, serializeMemory, snapshotContract, specificityScore, stripPrivate, suggestSensorFromMemory, suggestTopicKey, summarizeImpact, synthesizeSelfEvalCases, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, writeBriefingMarker };
1854
+ /**
1855
+ * Failure-capture coverage — the gate behind hAIve's "never silently fix the same mistake" loop.
1856
+ *
1857
+ * `haive observe` (the PostToolUse hook) appends an observation per tool call to
1858
+ * `.ai/.cache/observations.jsonl`, tagging hard failures with `failure_hint: true`
1859
+ * (non-zero Bash exit, `error TSxxxx`, ENOENT, …). Those failures are exactly the
1860
+ * `mem_tried` candidates the harness wants captured — otherwise the next session repeats them.
1861
+ *
1862
+ * This module is the pure decision layer: given the failure observations and the corpus's
1863
+ * `attempt`/`gotcha` memories, which failures look UNCAPTURED (no lesson recorded after them)?
1864
+ * The CLI reads the files and turns the result into an `enforce finish` finding. No I/O here.
1865
+ */
1866
+ interface FailureObservation {
1867
+ /** ISO timestamp of the observation. */
1868
+ ts: string;
1869
+ /** Tool that failed (Bash / Edit / …). */
1870
+ tool: string;
1871
+ /** Short human-readable summary of what was attempted. */
1872
+ summary: string;
1873
+ }
1874
+ interface UncapturedFailure {
1875
+ ts: string;
1876
+ tool: string;
1877
+ summary: string;
1878
+ }
1879
+ interface FailureCoverageOptions {
1880
+ /** Only consider failures newer than this many hours (avoid stale observations blocking forever). Default 24. */
1881
+ windowHours?: number;
1882
+ /** Collapse near-identical failures (same normalized summary) to one row. Default true. */
1883
+ dedupe?: boolean;
1884
+ now?: Date;
1885
+ }
1886
+ /**
1887
+ * A failure is CAPTURED when an `attempt`/`gotcha` lesson was recorded at or after it
1888
+ * (within the window) — the agent stopped and wrote the lesson down. Failures that pre-date
1889
+ * every recent capture are uncaptured: the gate should nudge (or block) on those.
1890
+ *
1891
+ * @param failures failure-tagged observations (any order)
1892
+ * @param captureTimes ISO created_at of every attempt/gotcha memory in the corpus
1893
+ */
1894
+ declare function findUncapturedFailures(failures: FailureObservation[], captureTimes: string[], options?: FailureCoverageOptions): UncapturedFailure[];
1895
+
1896
+ /**
1897
+ * Harness coverage-gap detection — "which churny files have NO team knowledge on them?".
1898
+ *
1899
+ * hAIve's `eval` synthesizes cases from the memories that EXIST (does the corpus surface
1900
+ * correctly?). It cannot tell you what knowledge is MISSING. This module answers the inverse,
1901
+ * proactive question Fowler frames as an open challenge: of the files the team edits most, which
1902
+ * carry no covering decision/convention/gotcha/architecture memory? Those are the blind spots
1903
+ * where a confident agent is most likely to violate an unwritten rule.
1904
+ *
1905
+ * Pure: the caller supplies hot files (from git history / briefing-radar) and the loaded corpus.
1906
+ */
1907
+
1908
+ interface HotFile {
1909
+ path: string;
1910
+ /** Number of times the file changed in the lookback window (the "heat"). */
1911
+ changes: number;
1912
+ }
1913
+ interface CoverageGap {
1914
+ path: string;
1915
+ changes: number;
1916
+ }
1917
+ interface CoverageOptions {
1918
+ /** Only flag files with at least this many changes. Default 3. */
1919
+ minChanges?: number;
1920
+ /** Memory types that count as "covering" a file. Default decision/convention/gotcha/architecture. */
1921
+ coveringTypes?: string[];
1922
+ /** Cap on returned gaps. Default 20. */
1923
+ limit?: number;
1924
+ }
1925
+ /**
1926
+ * Build the set of path prefixes the corpus covers: every anchor path of a non-dead,
1927
+ * non-recap covering memory. A file is covered if it equals, or sits under, one of them.
1928
+ */
1929
+ declare function buildCoverageIndex(memories: LoadedMemory[], coveringTypes?: string[]): Set<string>;
1930
+ /** True when `file` equals or is nested under any covered path prefix. */
1931
+ declare function isCovered(file: string, coverage: Set<string>): boolean;
1932
+ /**
1933
+ * Cross hot files with the coverage index → the uncovered, frequently-edited files.
1934
+ * Highest heat first. These are the highest-value places to add a memory or sensor.
1935
+ */
1936
+ declare function findCoverageGaps(hotFiles: HotFile[], memories: LoadedMemory[], options?: CoverageOptions): CoverageGap[];
1937
+
1938
+ interface EvalHistoryEntry {
1939
+ /** ISO timestamp of the eval run. */
1940
+ at: string;
1941
+ /** Overall 0..100 score. */
1942
+ score: number;
1943
+ /** Optional component metrics for richer trend views. */
1944
+ mean_recall?: number;
1945
+ mrr?: number;
1946
+ catch_rate?: number;
1947
+ /** Optional version/commit the run was taken at. */
1948
+ ref?: string;
1949
+ }
1950
+ declare function evalHistoryPath(paths: HaivePaths): string;
1951
+ /** Append one eval run to the history. Best-effort, creates the dir on demand. */
1952
+ declare function appendEvalHistory(paths: HaivePaths, entry: EvalHistoryEntry): Promise<void>;
1953
+ /** Read all eval runs (skips malformed lines). */
1954
+ declare function loadEvalHistory(paths: HaivePaths): Promise<EvalHistoryEntry[]>;
1955
+ interface EvalTrend {
1956
+ /** Most recent score, or null when there is no history. */
1957
+ latest: number | null;
1958
+ /** Score before the latest, or null. */
1959
+ previous: number | null;
1960
+ /** latest − previous (positive = improving). */
1961
+ delta: number | null;
1962
+ /** Best score ever recorded. */
1963
+ best: number | null;
1964
+ /** Number of runs recorded. */
1965
+ runs: number;
1966
+ /** Last N scores oldest → newest for a sparkline. */
1967
+ recent: number[];
1968
+ /** True when the latest run dropped vs the previous one. */
1969
+ regressed: boolean;
1970
+ }
1971
+ /** Pure trend over the history (chronological order is enforced internally). */
1972
+ declare function computeEvalTrend(entries: EvalHistoryEntry[], recentN?: number): EvalTrend;
1973
+
1974
+ /**
1975
+ * Contradiction resolution planning — turns "two memories conflict" into "do THIS".
1976
+ *
1977
+ * `conflict-candidates.ts` surfaces pairs (same topic with opposed status, or lexically near-
1978
+ * duplicate). That's detection, not resolution — and Fowler lists incoherence-at-scale (a harness
1979
+ * full of contradictory guides) as a core open challenge. This module decides, deterministically,
1980
+ * which memory of a pair should WIN and which should be superseded (deprecated), so the CLI can
1981
+ * apply it. Pure: no I/O, unit-tested.
1982
+ *
1983
+ * Decision order (strongest signal first):
1984
+ * 1. status — a `validated` memory beats a `rejected`/`deprecated`/`stale` one.
1985
+ * 2. revision — higher `revision_count` (more refined via topic-upsert) wins.
1986
+ * 3. recency — newer `created_at` wins (the team's latest word).
1987
+ */
1988
+
1989
+ interface ConflictResolution {
1990
+ /** Memory id to keep authoritative. */
1991
+ keep_id: string;
1992
+ /** Memory id to deprecate (superseded). */
1993
+ supersede_id: string;
1994
+ /** Human-readable reason the winner was chosen. */
1995
+ reason: string;
1996
+ /** stale_reason to stamp on the superseded memory. */
1997
+ stale_reason: string;
1998
+ }
1999
+ /** Compare two memories; returns the one that should WIN plus the reason. Pure. */
2000
+ declare function planConflictResolution(a: LoadedMemory, b: LoadedMemory): ConflictResolution;
2001
+
2002
+ /**
2003
+ * Cold-start seeding from git history — the harness has value only once the corpus is populated,
2004
+ * and a fresh repo starts empty (Fowler's "harnessability": greenfield is easy, legacy is hard).
2005
+ *
2006
+ * Reverts and fixups are the cheapest signal of a real, repo-specific mistake: a commit that had to
2007
+ * be undone or hot-fixed encodes a lesson the team already paid for. This module parses a list of
2008
+ * commits (the CLI runs `git log`) and proposes DRAFT `attempt` seeds — never validated, always
2009
+ * human-reviewed. Pure: the caller does the git I/O and the memory writes.
2010
+ */
2011
+ interface GitCommit {
2012
+ sha: string;
2013
+ subject: string;
2014
+ /** Files touched by the commit (optional — improves anchoring). */
2015
+ files?: string[];
2016
+ }
2017
+ interface SeedProposal {
2018
+ /** Kebab-ish slug derived from the reverted subject. */
2019
+ slug: string;
2020
+ /** What was tried (the thing that had to be reverted/fixed). */
2021
+ what: string;
2022
+ /** Why it failed (inferred from the revert/fixup). */
2023
+ why_failed: string;
2024
+ /** Suggested anchor paths (from the commit's files). */
2025
+ paths: string[];
2026
+ /** The source commit, for provenance. */
2027
+ source_sha: string;
2028
+ /** Detected signal kind. */
2029
+ kind: "revert" | "fixup";
2030
+ }
2031
+ /**
2032
+ * Turn commits into seed proposals. A `Revert "X"` commit proposes an attempt about X; an obvious
2033
+ * hotfix/fixup commit proposes an attempt about the fixed area. Deduped by slug. Pure.
2034
+ */
2035
+ declare function proposeSeedsFromCommits(commits: GitCommit[], limit?: number): SeedProposal[];
2036
+
2037
+ interface MergeResult {
2038
+ /** The chosen file content. */
2039
+ content: string;
2040
+ /** Which side won. */
2041
+ winner: "ours" | "theirs";
2042
+ /** Why (for logging). */
2043
+ reason: string;
2044
+ }
2045
+ /**
2046
+ * Resolve two versions of the same memory file. Returns the winning content and the rationale.
2047
+ * Falls back to "ours" when either side can't be parsed (never throws — a merge driver must not).
2048
+ */
2049
+ declare function mergeMemoryVersions(ours: string, theirs: string): MergeResult;
2050
+
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 };