@hivelore/core 0.35.1 → 0.37.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 +107 -1
- package/dist/index.js +171 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -49,6 +49,13 @@ declare const SensorSchema: z.ZodObject<{
|
|
|
49
49
|
paths: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
50
50
|
/** LLM-facing self-correction message: what was done wrong and what to do instead. */
|
|
51
51
|
message: z.ZodString;
|
|
52
|
+
/**
|
|
53
|
+
* Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
|
|
54
|
+
* incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
|
|
55
|
+
* behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
|
|
56
|
+
* the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
|
|
57
|
+
*/
|
|
58
|
+
incident: z.ZodOptional<z.ZodString>;
|
|
52
59
|
/** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
|
|
53
60
|
severity: z.ZodDefault<z.ZodEnum<["warn", "block"]>>;
|
|
54
61
|
/** True when Hivelore generated this sensor automatically (vs. hand-authored). */
|
|
@@ -74,6 +81,7 @@ declare const SensorSchema: z.ZodObject<{
|
|
|
74
81
|
flags?: string | undefined;
|
|
75
82
|
command?: string | undefined;
|
|
76
83
|
timeout_ms?: number | undefined;
|
|
84
|
+
incident?: string | undefined;
|
|
77
85
|
promoted_at?: string | undefined;
|
|
78
86
|
}, {
|
|
79
87
|
message: string;
|
|
@@ -84,6 +92,7 @@ declare const SensorSchema: z.ZodObject<{
|
|
|
84
92
|
flags?: string | undefined;
|
|
85
93
|
command?: string | undefined;
|
|
86
94
|
timeout_ms?: number | undefined;
|
|
95
|
+
incident?: string | undefined;
|
|
87
96
|
severity?: "warn" | "block" | undefined;
|
|
88
97
|
autogen?: boolean | undefined;
|
|
89
98
|
last_fired?: string | null | undefined;
|
|
@@ -157,6 +166,13 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
157
166
|
paths: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
|
|
158
167
|
/** LLM-facing self-correction message: what was done wrong and what to do instead. */
|
|
159
168
|
message: z.ZodString;
|
|
169
|
+
/**
|
|
170
|
+
* Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
|
|
171
|
+
* incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
|
|
172
|
+
* behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
|
|
173
|
+
* the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
|
|
174
|
+
*/
|
|
175
|
+
incident: z.ZodOptional<z.ZodString>;
|
|
160
176
|
/** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
|
|
161
177
|
severity: z.ZodDefault<z.ZodEnum<["warn", "block"]>>;
|
|
162
178
|
/** True when Hivelore generated this sensor automatically (vs. hand-authored). */
|
|
@@ -182,6 +198,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
182
198
|
flags?: string | undefined;
|
|
183
199
|
command?: string | undefined;
|
|
184
200
|
timeout_ms?: number | undefined;
|
|
201
|
+
incident?: string | undefined;
|
|
185
202
|
promoted_at?: string | undefined;
|
|
186
203
|
}, {
|
|
187
204
|
message: string;
|
|
@@ -192,6 +209,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
192
209
|
flags?: string | undefined;
|
|
193
210
|
command?: string | undefined;
|
|
194
211
|
timeout_ms?: number | undefined;
|
|
212
|
+
incident?: string | undefined;
|
|
195
213
|
severity?: "warn" | "block" | undefined;
|
|
196
214
|
autogen?: boolean | undefined;
|
|
197
215
|
last_fired?: string | null | undefined;
|
|
@@ -275,6 +293,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
275
293
|
flags?: string | undefined;
|
|
276
294
|
command?: string | undefined;
|
|
277
295
|
timeout_ms?: number | undefined;
|
|
296
|
+
incident?: string | undefined;
|
|
278
297
|
promoted_at?: string | undefined;
|
|
279
298
|
} | undefined;
|
|
280
299
|
activation?: {
|
|
@@ -306,6 +325,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
306
325
|
flags?: string | undefined;
|
|
307
326
|
command?: string | undefined;
|
|
308
327
|
timeout_ms?: number | undefined;
|
|
328
|
+
incident?: string | undefined;
|
|
309
329
|
severity?: "warn" | "block" | undefined;
|
|
310
330
|
autogen?: boolean | undefined;
|
|
311
331
|
last_fired?: string | null | undefined;
|
|
@@ -361,6 +381,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
361
381
|
flags?: string | undefined;
|
|
362
382
|
command?: string | undefined;
|
|
363
383
|
timeout_ms?: number | undefined;
|
|
384
|
+
incident?: string | undefined;
|
|
364
385
|
promoted_at?: string | undefined;
|
|
365
386
|
} | undefined;
|
|
366
387
|
activation?: {
|
|
@@ -392,6 +413,7 @@ declare const MemoryFrontmatterSchema: z.ZodEffects<z.ZodObject<{
|
|
|
392
413
|
flags?: string | undefined;
|
|
393
414
|
command?: string | undefined;
|
|
394
415
|
timeout_ms?: number | undefined;
|
|
416
|
+
incident?: string | undefined;
|
|
395
417
|
severity?: "warn" | "block" | undefined;
|
|
396
418
|
autogen?: boolean | undefined;
|
|
397
419
|
last_fired?: string | null | undefined;
|
|
@@ -705,6 +727,8 @@ interface PreventionReceiptRow {
|
|
|
705
727
|
stage: "pre-commit" | "pre-push" | "ci" | "manual" | null;
|
|
706
728
|
exit_code: number | null;
|
|
707
729
|
message: string | null;
|
|
730
|
+
/** Incident provenance from the sensor frontmatter — the behaviour-harness link, when present. */
|
|
731
|
+
incident: string | null;
|
|
708
732
|
}
|
|
709
733
|
interface PreventionReceipt {
|
|
710
734
|
generated_at: string;
|
|
@@ -722,6 +746,19 @@ declare function buildPreventionReceipt(events: PreventionEvent[], memories: Loa
|
|
|
722
746
|
now?: Date;
|
|
723
747
|
}): PreventionReceipt;
|
|
724
748
|
declare function renderPreventionReceipt(receipt: PreventionReceipt): string;
|
|
749
|
+
/**
|
|
750
|
+
* Attribution footer for shared receipts — the growth loop. Every time a team pastes proof of
|
|
751
|
+
* prevented mistakes into Slack or a PR, the artifact names the tool that produced it. Kept as one
|
|
752
|
+
* constant so the CLI `--share` output and the CI PR comment carry identical wording.
|
|
753
|
+
*/
|
|
754
|
+
declare const HIVELORE_ATTRIBUTION = "\uD83D\uDEE1\uFE0F Generated by [Hivelore](https://github.com/Doucs91/hivelore) \u2014 the deterministic policy gate for agent-written code.";
|
|
755
|
+
/**
|
|
756
|
+
* Markdown rendering of the receipt for `hivelore stats receipt --share` and the CI PR comment —
|
|
757
|
+
* ready to paste into Slack or a review. Includes incident provenance and the attribution footer.
|
|
758
|
+
* An empty window is NOT a dead end: it renders a forward CTA (turn an incident into a guardrail),
|
|
759
|
+
* so the receipt is useful on day one, before any prevention has been recorded.
|
|
760
|
+
*/
|
|
761
|
+
declare function renderPreventionReceiptShare(receipt: PreventionReceipt): string;
|
|
725
762
|
/** Read all catch events (skips malformed lines). */
|
|
726
763
|
declare function loadPreventionEvents(paths: HaivePaths): Promise<PreventionEvent[]>;
|
|
727
764
|
interface PreventionTrend {
|
|
@@ -1929,11 +1966,19 @@ interface CommandSensorSpec {
|
|
|
1929
1966
|
severity: Sensor["severity"];
|
|
1930
1967
|
/** LLM-facing self-correction message carried from the sensor. */
|
|
1931
1968
|
message: string;
|
|
1969
|
+
/** Optional incident provenance carried from the sensor (ticket/prod ref this test guards). */
|
|
1970
|
+
incident?: string;
|
|
1932
1971
|
/** Anchor/scoped paths this sensor cares about (for reporting). */
|
|
1933
1972
|
paths: string[];
|
|
1934
1973
|
/** Max runtime in ms (executor default applies when unset). */
|
|
1935
1974
|
timeout_ms?: number;
|
|
1936
1975
|
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Render the incident-provenance suffix appended to a fired sensor's message. Empty when the sensor
|
|
1978
|
+
* carries no `incident` — so the behaviour-harness link ("guards the incident this test exists for")
|
|
1979
|
+
* shows up wherever a sensor speaks, without every call site re-deriving the copy.
|
|
1980
|
+
*/
|
|
1981
|
+
declare function incidentSuffix(incident?: string): string;
|
|
1937
1982
|
/**
|
|
1938
1983
|
* Select the shell/test sensors that apply to `changedPaths`. With no changed paths (or a sensor
|
|
1939
1984
|
* scoped to everywhere) the sensor is selected unconditionally. Pure: the caller executes commands.
|
|
@@ -2121,6 +2166,67 @@ declare function suggestSensorSeed(body: string, anchorPaths: string[], options?
|
|
|
2121
2166
|
*/
|
|
2122
2167
|
declare function suggestSensorFromMemory(body: string, anchorPaths: string[], options?: SensorSuggestionOptions): Sensor | null;
|
|
2123
2168
|
|
|
2169
|
+
/**
|
|
2170
|
+
* Post-incident test scaffolding — turn a captured lesson (`mem_tried` / attempt / gotcha) into a
|
|
2171
|
+
* PENDING test file the team fills in, then arms as a command-sensor oracle.
|
|
2172
|
+
*
|
|
2173
|
+
* This is the behaviour-harness bridge's on-ramp: `mem_tried` records *what* failed and *why*, but a
|
|
2174
|
+
* command sensor needs the team's own test as the oracle — and someone has to write it. This module
|
|
2175
|
+
* removes that friction by generating the test skeleton (header provenance + a pending test + a
|
|
2176
|
+
* commented example derived from the lesson) plus the exact `sensors propose --kind test` line.
|
|
2177
|
+
*
|
|
2178
|
+
* DOCTRINE: this NEVER arms a sensor. It only writes a stub and prints the wiring command. Arming
|
|
2179
|
+
* stays with `propose_sensor`, the sole validated writer of live sensors (silent-on-current /
|
|
2180
|
+
* fires-on-bad). The generated test is deliberately PENDING (todo/skip) so the suite stays green and
|
|
2181
|
+
* an empty stub can't masquerade as a passing oracle. Pure: no I/O — the caller writes the file.
|
|
2182
|
+
*/
|
|
2183
|
+
type TestFramework = "vitest" | "jest" | "pytest" | "gotest";
|
|
2184
|
+
declare const TEST_FRAMEWORKS: readonly TestFramework[];
|
|
2185
|
+
interface PostIncidentLesson {
|
|
2186
|
+
/** Memory id the scaffold is generated from. */
|
|
2187
|
+
memoryId: string;
|
|
2188
|
+
/** Short "what was tried / what failed" title (the lesson's heading). */
|
|
2189
|
+
title: string;
|
|
2190
|
+
/** Why it failed / must not be used. */
|
|
2191
|
+
whyFailed?: string;
|
|
2192
|
+
/** The correct approach / expected behaviour. */
|
|
2193
|
+
instead?: string;
|
|
2194
|
+
/** Incident provenance (ticket/prod ref) carried into the sensor when armed. */
|
|
2195
|
+
incident?: string;
|
|
2196
|
+
/** Anchor paths — used to scope the sensor and to place the test near the code. */
|
|
2197
|
+
paths?: string[];
|
|
2198
|
+
}
|
|
2199
|
+
interface TestScaffold {
|
|
2200
|
+
framework: TestFramework;
|
|
2201
|
+
/** Suggested project-relative path for the generated test file. */
|
|
2202
|
+
relPath: string;
|
|
2203
|
+
/** File contents (a pending test with provenance + a commented example). */
|
|
2204
|
+
content: string;
|
|
2205
|
+
/** Command that runs ONLY this test — becomes the sensor's oracle command once filled in. */
|
|
2206
|
+
runCommand: string;
|
|
2207
|
+
/** Ready-to-run wiring command: arms the test as a deterministic gate AFTER it is written. */
|
|
2208
|
+
proposeCommand: string;
|
|
2209
|
+
}
|
|
2210
|
+
interface ScaffoldOptions {
|
|
2211
|
+
framework: TestFramework;
|
|
2212
|
+
/** Override the generated file path (project-relative). */
|
|
2213
|
+
outPath?: string;
|
|
2214
|
+
}
|
|
2215
|
+
/** Strip the `YYYY-MM-DD-<type>-` id prefix to the descriptive slug (`importing-momentjs`). */
|
|
2216
|
+
declare function lessonShortName(memoryId: string): string;
|
|
2217
|
+
/**
|
|
2218
|
+
* Parse the "what / why / instead" fields out of an attempt/gotcha memory body — the shape written
|
|
2219
|
+
* by `mem_tried` (`# <what>`, `**Why it failed / do NOT use:** …`, `**Instead, use:** …`). Pure so
|
|
2220
|
+
* the CLI can hand it a loaded body without re-implementing the parse.
|
|
2221
|
+
*/
|
|
2222
|
+
declare function parseLessonFields(body: string): {
|
|
2223
|
+
title?: string;
|
|
2224
|
+
whyFailed?: string;
|
|
2225
|
+
instead?: string;
|
|
2226
|
+
};
|
|
2227
|
+
/** Build a scaffold for the given lesson + framework. Pure — the caller writes `content` to `relPath`. */
|
|
2228
|
+
declare function scaffoldPostIncidentTest(lesson: PostIncidentLesson, options: ScaffoldOptions): TestScaffold;
|
|
2229
|
+
|
|
2124
2230
|
/**
|
|
2125
2231
|
* First-agent bootstrap state — is the repo's knowledge layer filled enough for later agents to rely on?
|
|
2126
2232
|
*
|
|
@@ -2969,4 +3075,4 @@ interface AgentContext {
|
|
|
2969
3075
|
}
|
|
2970
3076
|
declare function detectAgentContext(env?: Record<string, string | undefined>): AgentContext;
|
|
2971
3077
|
|
|
2972
|
-
export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, AnchorSchema, type AntiPatternGate, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_PRIORITY_SIGNALS, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, GUESSABLE_THRESHOLD, type GateMissProposal, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateTuningSuggestion, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type InvalidMemoryFile, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, PREVENTION_DEBOUNCE_MS, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedSensorVerdict, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SessionHandoffData, type SkillActivation, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, assessBootstrapState, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, detectAgentContext, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractSensorExamples, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasRecentBriefingMarker, hashProjectContext, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeMemory, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
|
|
3078
|
+
export { AUTOPILOT_DEFAULTS, type Activation, type ActivationContext, ActivationSchema, type AgentContext, type Anchor, AnchorSchema, type AntiPatternGate, type AppliedConflictResolution, type AstExport, type AutoPromoteRule, BRIDGE_MARKERS, BRIDGE_TARGETS, BRIDGE_TARGET_PATH, BRIEFING_MARKER_TTL_MS, BRIEFING_PRESET_DEFAULTS, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, type CaughtForYouOptions, type CaughtForYouRow, type CaughtForYouSummary, type CodeExport, type CodeExportKind, type CodeFileEntry, type CodeMap, type CodeMapQueryOptions, type CollectTimelineOpts, type CommandSensorSpec, type ConfidenceLevel, type ConfidenceThresholds, type ConflictCandidatePair, type ConflictCandidatesOpts, type ConflictResolution, type ContractDiffResult, type ContractFile, type ContractSnapshot, type CoverageGap, type CoverageOptions, CrossRepoProvenanceSchema, type CrossRepoReport, type CrossRepoSource, DECAY_DAYS, DEFAULT_AUTO_PROMOTE_RULE, DEFAULT_BRIEFING_EXCLUDE_TAGS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CONFIG, DEFAULT_DORMANT_DAYS, DEFAULT_PRIORITY_SIGNALS, type DashboardOptions, type DashboardReport, type DepChange, type DepTrackResult, type DependencySnapshot, type DetectStacksInput, type DetectableStack, type DocFrequency, type DormantRow, type DraftOptions, type DraftsOptions, ENV_WORKAROUND_TAGS, type EvalDelta, type EvalHistoryEntry, type EvalReport, type EvalSpec, type EvalTrend, type FailureCoverageOptions, type FailureObservation, type FeedbackAdjustment, type FeedbackAdjustmentAction, type FeedbackAdjustmentOptions, type Finding, type FindingFormat, type FindingSeverity, GUESSABLE_THRESHOLD, type GateMissProposal, type GatePrecision, type GatePrecisionDelta, type GatePrecisionMetricDelta, type GateTuningSuggestion, type GenerateBridgesOptions, type GitCommit, type GitWatchPlan, type GitWatchState, HAIVE_DIR, HAIVE_OWNED_FILES, HANDOFF_FILENAME, HIVELORE_ATTRIBUTION, type HaiveConfig, type HaivePaths, type HotFile, type HotFileSource, type ImpactOptions, type ImpactRow, type ImpactScore, type ImpactSummary, type ImpactTier, type InvalidMemoryFile, type LexicalRankResult, type LoadedMemory, MEMORIES_DIR, MIN_WORD_LEN, type Memory, type MemoryDraft, type MemoryFrontmatter, MemoryFrontmatterSchema, type MemoryPriority, type MemoryScope, MemoryScopeSchema, type MemoryStatus, MemoryStatusSchema, type MemoryType, MemoryTypeSchema, type MemoryUsage, type MergeResult, type MetricDelta, PREVENTION_DEBOUNCE_MS, PROJECT_CONTEXT_FILE, PROJECT_CONTEXT_THROTTLE_MS, type PostIncidentLesson, type PreventionEvent, type PreventionEventDetail, type PreventionReceipt, type PreventionReceiptRow, type PreventionRow, type PreventionSource, type PreventionTrend, type PrioritySignals, type ProposedSensorVerdict, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type RuntimeJournalEntry, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type ScaffoldOptions, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, assessBootstrapState, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, detectAgentContext, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractSensorExamples, extractSnippet, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasRecentBriefingMarker, hashProjectContext, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isRetiredMemory, isSensorScannablePath, isSkill, isSkillSuppressed, isStackPackSeed, isStylisticRule, isTemplateProjectContext, judgeProposedSensor, lessonShortName, listMarkdownFilesRecursive, literalMatchesAllTokens, literalMatchesAnyToken, loadCodeMap, loadConfig, loadConfigSync, loadEvalHistory, loadMemoriesFromDir, loadMemoriesFromDirDetailed, loadMemory, loadPreventionEvents, loadSensorLedger, loadUsageIndex, looksLikeGenericAdvice, meetsSeedQualityFloor, memoryFilePath, memoryHasExcludedTag, memoryMatchesAnchorPaths, mergeHotFiles, mergeMemoryVersions, moduleNameOf, newMemoryId, normalizeFindingSeverity, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, runRegexSensor, runSensors, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, selectCommandSensors, sensorAppliesToPath, sensorLedgerPath, sensorPatternBrittleness, sensorPromotedAtMap, sensorSelfCheck, sensorTargetsFromDiff, serializeMemory, snapshotContract, specificityScore, stripPrivate, suggestGate, suggestSensorFromMemory, suggestSensorSeed, suggestTopicKey, summarizeCaughtForYou, summarizeImpact, synthesizeSelfEvalCases, tallyHotFiles, titleFromBody, tokenizeQuery, tokenizeWords, trackDependencies, trackReads, truncateToTokens, usageLogPath, usageLogSize, usagePath, verifyAnchor, watchContracts, withQuarantineNote, withoutQuarantineNote, writeBriefingMarker, writeSessionHandoff };
|
package/dist/index.js
CHANGED
|
@@ -49,6 +49,13 @@ var SensorSchema = z.object({
|
|
|
49
49
|
paths: z.array(z.string()).default([]),
|
|
50
50
|
/** LLM-facing self-correction message: what was done wrong and what to do instead. */
|
|
51
51
|
message: z.string().min(1),
|
|
52
|
+
/**
|
|
53
|
+
* Optional provenance: the real incident this sensor guards against — a ticket ref, a prod
|
|
54
|
+
* incident id, a date ("prod #442", "INC-1029", "2026-06 refund overcharge"). This is the
|
|
55
|
+
* behaviour-harness link a plain test can't carry: it turns "a test failed" into "this reproduces
|
|
56
|
+
* the incident the test exists to prevent". Surfaced in the block message and the prevention receipt.
|
|
57
|
+
*/
|
|
58
|
+
incident: z.string().optional(),
|
|
52
59
|
/** `warn` surfaces in review; `block` can hard-block the commit (only when the gate opts in). */
|
|
53
60
|
severity: z.enum(["warn", "block"]).default("warn"),
|
|
54
61
|
/** True when Hivelore generated this sensor automatically (vs. hand-authored). */
|
|
@@ -943,7 +950,8 @@ function buildPreventionReceipt(events, memories, usage, options) {
|
|
|
943
950
|
kind: event.kind ?? sensor?.kind ?? (event.source === "sensor" ? "regex" : null),
|
|
944
951
|
stage: event.stage ?? null,
|
|
945
952
|
exit_code: event.exit_code ?? null,
|
|
946
|
-
message: sensor?.message ?? null
|
|
953
|
+
message: sensor?.message ?? null,
|
|
954
|
+
incident: sensor?.incident ?? null
|
|
947
955
|
};
|
|
948
956
|
}).sort((a, b) => b.at.localeCompare(a.at));
|
|
949
957
|
const preventedCountTotal = Object.values(usage.by_id).reduce((sum, item) => sum + item.prevented_count, 0);
|
|
@@ -967,13 +975,44 @@ function renderPreventionReceipt(receipt) {
|
|
|
967
975
|
const kind = row.kind ? `${row.kind} sensor` : row.source;
|
|
968
976
|
const exit = row.exit_code === null ? "" : `, exit ${row.exit_code}`;
|
|
969
977
|
const stage = row.stage ? ` \u2014 caught at ${row.stage}` : "";
|
|
970
|
-
|
|
978
|
+
const incident = row.incident ? ` \u21A9 incident: ${row.incident}` : "";
|
|
979
|
+
lines.push(` \u2717\u2192\u2713 ${row.at.slice(0, 10)} ${row.id.padEnd(32)} (${kind}${exit}${stage})${incident}`);
|
|
971
980
|
}
|
|
972
981
|
lines.push(
|
|
973
982
|
` Trend: ${receipt.total} this window vs ${receipt.previous_total} previous window (${receipt.total <= receipt.previous_total ? "recurrences declining" : "recurrences rising"}).`
|
|
974
983
|
);
|
|
975
984
|
return lines.join("\n");
|
|
976
985
|
}
|
|
986
|
+
var HIVELORE_ATTRIBUTION = "\u{1F6E1}\uFE0F Generated by [Hivelore](https://github.com/Doucs91/hivelore) \u2014 the deterministic policy gate for agent-written code.";
|
|
987
|
+
function renderPreventionReceiptShare(receipt) {
|
|
988
|
+
const lines = [`### \u{1F6E1}\uFE0F Hivelore prevention receipt \u2014 last ${receipt.window_days} days`, ""];
|
|
989
|
+
if (receipt.total === 0) {
|
|
990
|
+
lines.push(
|
|
991
|
+
"No repeat mistakes reached review in this window.",
|
|
992
|
+
"",
|
|
993
|
+
"Turn a past incident into a guardrail so it can never come back:",
|
|
994
|
+
'`hivelore memory tried \u2026 --sensor-command "<your test>"` (add `--incident <ref>` to link the incident it guards).'
|
|
995
|
+
);
|
|
996
|
+
} else {
|
|
997
|
+
lines.push(
|
|
998
|
+
`**${receipt.total} repeat mistake${receipt.total === 1 ? "" : "s"} refused before ${receipt.total === 1 ? "it" : "they"} reached review.**`,
|
|
999
|
+
""
|
|
1000
|
+
);
|
|
1001
|
+
for (const row of receipt.events) {
|
|
1002
|
+
const kind = row.kind ? `${row.kind} sensor` : row.source;
|
|
1003
|
+
const exit = row.exit_code === null ? "" : `, exit ${row.exit_code}`;
|
|
1004
|
+
const stage = row.stage ? ` \u2014 caught at ${row.stage}` : "";
|
|
1005
|
+
const incident = row.incident ? ` \u21A9 incident: ${row.incident}` : "";
|
|
1006
|
+
lines.push(`- \u2717\u2192\u2713 \`${row.at.slice(0, 10)}\` **${row.title}** (${kind}${exit}${stage})${incident}`);
|
|
1007
|
+
}
|
|
1008
|
+
lines.push(
|
|
1009
|
+
"",
|
|
1010
|
+
`_Trend: ${receipt.total} this window vs ${receipt.previous_total} previous window (${receipt.total <= receipt.previous_total ? "recurrences declining" : "recurrences rising"})._`
|
|
1011
|
+
);
|
|
1012
|
+
}
|
|
1013
|
+
lines.push("", `<sub>${HIVELORE_ATTRIBUTION}</sub>`);
|
|
1014
|
+
return lines.join("\n");
|
|
1015
|
+
}
|
|
977
1016
|
async function loadPreventionEvents(paths) {
|
|
978
1017
|
const file = preventionLogPath(paths);
|
|
979
1018
|
if (!existsSync4(file)) return [];
|
|
@@ -3719,8 +3758,8 @@ var BRIDGE_MARKERS = {
|
|
|
3719
3758
|
};
|
|
3720
3759
|
function bridgeMemorySummary(body) {
|
|
3721
3760
|
const firstLine = body.split("\n").map((l) => l.replace(/^#+\s*/, "").trim()).find((l) => l.length > 0) ?? "";
|
|
3722
|
-
const
|
|
3723
|
-
return
|
|
3761
|
+
const oneLine2 = firstLine.replace(/\s+/g, " ");
|
|
3762
|
+
return oneLine2.length > 140 ? oneLine2.slice(0, 137) + "\u2026" : oneLine2;
|
|
3724
3763
|
}
|
|
3725
3764
|
function prepareBridgeData(memories, sensors, opts) {
|
|
3726
3765
|
const max = opts?.maxMemories ?? 8;
|
|
@@ -3919,6 +3958,10 @@ function runSensors(memories, targets) {
|
|
|
3919
3958
|
}
|
|
3920
3959
|
return hits;
|
|
3921
3960
|
}
|
|
3961
|
+
function incidentSuffix(incident) {
|
|
3962
|
+
const ref = incident?.trim();
|
|
3963
|
+
return ref ? ` \u21A9 guards incident: ${ref}` : "";
|
|
3964
|
+
}
|
|
3922
3965
|
function selectCommandSensors(memories, changedPaths) {
|
|
3923
3966
|
const specs = [];
|
|
3924
3967
|
for (const memory of memories) {
|
|
@@ -3936,6 +3979,7 @@ function selectCommandSensors(memories, changedPaths) {
|
|
|
3936
3979
|
kind: sensor.kind,
|
|
3937
3980
|
severity: sensor.severity,
|
|
3938
3981
|
message: sensor.message,
|
|
3982
|
+
...sensor.incident ? { incident: sensor.incident } : {},
|
|
3939
3983
|
paths: sensor.paths.length > 0 ? sensor.paths : anchorPaths,
|
|
3940
3984
|
...sensor.timeout_ms ? { timeout_ms: sensor.timeout_ms } : {}
|
|
3941
3985
|
});
|
|
@@ -4442,6 +4486,119 @@ function escapeRegExp(value) {
|
|
|
4442
4486
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4443
4487
|
}
|
|
4444
4488
|
|
|
4489
|
+
// src/test-scaffold.ts
|
|
4490
|
+
var TEST_FRAMEWORKS = ["vitest", "jest", "pytest", "gotest"];
|
|
4491
|
+
function lessonShortName(memoryId) {
|
|
4492
|
+
const stripped = memoryId.replace(
|
|
4493
|
+
/^\d{4}-\d{2}-\d{2}-(?:attempt|gotcha|decision|convention|architecture|glossary|skill|session_recap)-/,
|
|
4494
|
+
""
|
|
4495
|
+
);
|
|
4496
|
+
const slug = (stripped || memoryId).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
4497
|
+
return slug || "incident";
|
|
4498
|
+
}
|
|
4499
|
+
function snake(slug) {
|
|
4500
|
+
return slug.replace(/-/g, "_").replace(/[^a-z0-9_]/gi, "").replace(/^_+|_+$/g, "") || "incident";
|
|
4501
|
+
}
|
|
4502
|
+
function pascal(slug) {
|
|
4503
|
+
return slug.split(/[^a-z0-9]+/i).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("") || "Incident";
|
|
4504
|
+
}
|
|
4505
|
+
function oneLine(text) {
|
|
4506
|
+
return (text ?? "").replace(/\s+/g, " ").trim();
|
|
4507
|
+
}
|
|
4508
|
+
function parseLessonFields(body) {
|
|
4509
|
+
const title = body.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();
|
|
4510
|
+
const whyFailed = body.match(/\*\*Why it failed[^:]*:\*\*\s*([^\n]+)/i)?.[1]?.trim();
|
|
4511
|
+
const instead = body.match(/\*\*Instead,\s*use:\*\*\s*([^\n]+)/i)?.[1]?.trim();
|
|
4512
|
+
return { title, whyFailed, instead };
|
|
4513
|
+
}
|
|
4514
|
+
function proposeCommand(lesson, runCommand) {
|
|
4515
|
+
const parts = [
|
|
4516
|
+
`hivelore sensors propose ${lesson.memoryId}`,
|
|
4517
|
+
"--kind test",
|
|
4518
|
+
`--command ${JSON.stringify(runCommand)}`
|
|
4519
|
+
];
|
|
4520
|
+
if (lesson.incident) parts.push(`--incident ${JSON.stringify(lesson.incident)}`);
|
|
4521
|
+
const scope = (lesson.paths ?? []).filter(Boolean);
|
|
4522
|
+
if (scope.length > 0) parts.push(`--paths ${JSON.stringify(scope.join(","))}`);
|
|
4523
|
+
return parts.join(" ");
|
|
4524
|
+
}
|
|
4525
|
+
function header(lesson, comment) {
|
|
4526
|
+
const lines = [
|
|
4527
|
+
`Post-incident guard generated by Hivelore from ${lesson.memoryId}.`,
|
|
4528
|
+
...lesson.incident ? [`Incident: ${lesson.incident}`] : [],
|
|
4529
|
+
`What failed: ${oneLine(lesson.title)}`,
|
|
4530
|
+
...lesson.whyFailed ? [`Why: ${oneLine(lesson.whyFailed)}`] : [],
|
|
4531
|
+
...lesson.instead ? [`Expected / fix: ${oneLine(lesson.instead)}`] : [],
|
|
4532
|
+
"",
|
|
4533
|
+
"TODO: replace the pending test with a real check that FAILS on the incident and",
|
|
4534
|
+
"PASSES once the fix is in place. Then arm it as a deterministic gate:"
|
|
4535
|
+
];
|
|
4536
|
+
return lines.map(comment).join("\n");
|
|
4537
|
+
}
|
|
4538
|
+
function scaffoldPostIncidentTest(lesson, options) {
|
|
4539
|
+
const framework = options.framework;
|
|
4540
|
+
const short = lessonShortName(lesson.memoryId);
|
|
4541
|
+
const desc = oneLine(lesson.title) || short;
|
|
4542
|
+
let relPath;
|
|
4543
|
+
let runCommand;
|
|
4544
|
+
let content;
|
|
4545
|
+
if (framework === "vitest" || framework === "jest") {
|
|
4546
|
+
relPath = options.outPath ?? `tests/incidents/${short}.test.ts`;
|
|
4547
|
+
runCommand = framework === "vitest" ? `npx vitest run ${relPath}` : `npx jest ${relPath}`;
|
|
4548
|
+
const hc = (l) => l ? `// ${l}` : "//";
|
|
4549
|
+
const importLine = framework === "vitest" ? `import { describe, it, expect } from "vitest";
|
|
4550
|
+
|
|
4551
|
+
` : "";
|
|
4552
|
+
content = `${header(lesson, hc)}
|
|
4553
|
+
// ${proposeCommand(lesson, runCommand)}
|
|
4554
|
+
|
|
4555
|
+
` + importLine + `describe(${JSON.stringify(desc)}, () => {
|
|
4556
|
+
it.todo("reproduces ${lesson.memoryId} and stays fixed");
|
|
4557
|
+
|
|
4558
|
+
// it("guards the incident", () => {
|
|
4559
|
+
// // Arrange the state that caused the incident, then assert the fixed behaviour.
|
|
4560
|
+
// expect(subjectUnderTest()).toBe(/* expected */);
|
|
4561
|
+
// });
|
|
4562
|
+
});
|
|
4563
|
+
`;
|
|
4564
|
+
} else if (framework === "pytest") {
|
|
4565
|
+
const fn = snake(short);
|
|
4566
|
+
relPath = options.outPath ?? `tests/incidents/test_${fn}.py`;
|
|
4567
|
+
runCommand = `pytest ${relPath}`;
|
|
4568
|
+
const hc = (l) => l ? `# ${l}` : "#";
|
|
4569
|
+
content = `${header(lesson, hc)}
|
|
4570
|
+
# ${proposeCommand(lesson, runCommand)}
|
|
4571
|
+
|
|
4572
|
+
import pytest
|
|
4573
|
+
|
|
4574
|
+
|
|
4575
|
+
@pytest.mark.skip(reason="TODO: write the post-incident assertion, then arm the sensor")
|
|
4576
|
+
def test_${fn}():
|
|
4577
|
+
# Arrange the state that caused the incident, then assert the fixed behaviour.
|
|
4578
|
+
assert subject_under_test() == expected
|
|
4579
|
+
`;
|
|
4580
|
+
} else {
|
|
4581
|
+
const fn = pascal(short);
|
|
4582
|
+
const dir = options.outPath ? options.outPath.replace(/\/[^/]+$/, "") : "incidents";
|
|
4583
|
+
relPath = options.outPath ?? `incidents/incident_${snake(short)}_test.go`;
|
|
4584
|
+
runCommand = `go test ./${dir}/`;
|
|
4585
|
+
const hc = (l) => l ? `// ${l}` : "//";
|
|
4586
|
+
content = `${header(lesson, hc)}
|
|
4587
|
+
// ${proposeCommand(lesson, runCommand)}
|
|
4588
|
+
|
|
4589
|
+
package incidents
|
|
4590
|
+
|
|
4591
|
+
import "testing"
|
|
4592
|
+
|
|
4593
|
+
func Test${fn}(t *testing.T) {
|
|
4594
|
+
t.Skip("TODO: write the post-incident assertion, then arm the sensor")
|
|
4595
|
+
// Arrange the state that caused the incident, then assert the fixed behaviour.
|
|
4596
|
+
}
|
|
4597
|
+
`;
|
|
4598
|
+
}
|
|
4599
|
+
return { framework, relPath, content, runCommand, proposeCommand: proposeCommand(lesson, runCommand) };
|
|
4600
|
+
}
|
|
4601
|
+
|
|
4445
4602
|
// src/bootstrap-state.ts
|
|
4446
4603
|
var CONTAINER_DIRS = /* @__PURE__ */ new Set([
|
|
4447
4604
|
"packages",
|
|
@@ -5518,17 +5675,17 @@ function compactAutoRecapBody(body, maxChars = 600) {
|
|
|
5518
5675
|
if (!isAutoRecap(body)) return body;
|
|
5519
5676
|
const goalMatch = body.match(/##+\s*Goal[^\n]*\n+([^\n]+)/i);
|
|
5520
5677
|
const callsMatch = body.match(/Auto-captured session \(([^)]+)\)/i);
|
|
5521
|
-
const
|
|
5678
|
+
const header2 = goalMatch?.[1]?.trim() ? `_${goalMatch[1].trim()}_` : callsMatch ? `_Auto-captured session (${callsMatch[1]})._` : "_Auto-captured session._";
|
|
5522
5679
|
const discMatch = body.match(/##+\s*Discoveries[^\n]*\n([\s\S]*?)(?=\n##+\s|\n*$)/i);
|
|
5523
5680
|
const discovery = discMatch?.[1]?.trim() ?? "";
|
|
5524
5681
|
const trivialDiscovery = discovery === "" || /^no (new memories|surprising)/i.test(discovery) || /No new memories saved this session\.?$/i.test(discovery);
|
|
5525
5682
|
if (trivialDiscovery) {
|
|
5526
|
-
return `${
|
|
5683
|
+
return `${header2}
|
|
5527
5684
|
|
|
5528
5685
|
_No notable discoveries captured. Run post_task / \`mem_session_end\` for a richer recap._`;
|
|
5529
5686
|
}
|
|
5530
5687
|
const trimmed = discovery.length > maxChars ? discovery.slice(0, maxChars) + "\u2026" : discovery;
|
|
5531
|
-
return `${
|
|
5688
|
+
return `${header2}
|
|
5532
5689
|
|
|
5533
5690
|
**Discoveries:**
|
|
5534
5691
|
${trimmed}`;
|
|
@@ -5688,6 +5845,7 @@ export {
|
|
|
5688
5845
|
HAIVE_DIR,
|
|
5689
5846
|
HAIVE_OWNED_FILES,
|
|
5690
5847
|
HANDOFF_FILENAME,
|
|
5848
|
+
HIVELORE_ATTRIBUTION,
|
|
5691
5849
|
MEMORIES_DIR,
|
|
5692
5850
|
MIN_WORD_LEN,
|
|
5693
5851
|
MemoryFrontmatterSchema,
|
|
@@ -5704,6 +5862,7 @@ export {
|
|
|
5704
5862
|
SESSION_RECAP_TTL_MS,
|
|
5705
5863
|
STACK_PACK_TAG,
|
|
5706
5864
|
SensorSchema,
|
|
5865
|
+
TEST_FRAMEWORKS,
|
|
5707
5866
|
USAGE_FILE,
|
|
5708
5867
|
USAGE_LOG_DIR,
|
|
5709
5868
|
USAGE_LOG_FILE,
|
|
@@ -5788,6 +5947,7 @@ export {
|
|
|
5788
5947
|
handoffFilePath,
|
|
5789
5948
|
hasRecentBriefingMarker,
|
|
5790
5949
|
hashProjectContext,
|
|
5950
|
+
incidentSuffix,
|
|
5791
5951
|
inferModulesFromPaths,
|
|
5792
5952
|
isAutoPromoteEligible,
|
|
5793
5953
|
isAutoRecap,
|
|
@@ -5807,6 +5967,7 @@ export {
|
|
|
5807
5967
|
isStylisticRule,
|
|
5808
5968
|
isTemplateProjectContext,
|
|
5809
5969
|
judgeProposedSensor,
|
|
5970
|
+
lessonShortName,
|
|
5810
5971
|
listMarkdownFilesRecursive,
|
|
5811
5972
|
literalMatchesAllTokens,
|
|
5812
5973
|
literalMatchesAnyToken,
|
|
@@ -5835,6 +5996,7 @@ export {
|
|
|
5835
5996
|
parseEslintJson,
|
|
5836
5997
|
parseFileAst,
|
|
5837
5998
|
parseFindings,
|
|
5999
|
+
parseLessonFields,
|
|
5838
6000
|
parseMemory,
|
|
5839
6001
|
parseNpmAudit,
|
|
5840
6002
|
parseSarif,
|
|
@@ -5869,6 +6031,7 @@ export {
|
|
|
5869
6031
|
renderBootstrapChecklist,
|
|
5870
6032
|
renderCaughtForYou,
|
|
5871
6033
|
renderPreventionReceipt,
|
|
6034
|
+
renderPreventionReceiptShare,
|
|
5872
6035
|
resolveBriefingBudget,
|
|
5873
6036
|
resolveHaivePaths,
|
|
5874
6037
|
resolveManifestFiles,
|
|
@@ -5881,6 +6044,7 @@ export {
|
|
|
5881
6044
|
saveCodeMap,
|
|
5882
6045
|
saveConfig,
|
|
5883
6046
|
saveUsageIndex,
|
|
6047
|
+
scaffoldPostIncidentTest,
|
|
5884
6048
|
scannableSensorTargets,
|
|
5885
6049
|
scoreRetrievalCase,
|
|
5886
6050
|
scoreSensorCase,
|