@hivelore/core 0.43.2 → 0.46.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 +103 -2
- package/dist/index.js +213 -16
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
package/dist/index.d.ts
CHANGED
|
@@ -2356,7 +2356,32 @@ interface PostIncidentLesson {
|
|
|
2356
2356
|
incident?: string;
|
|
2357
2357
|
/** Anchor paths — used to scope the sensor and to place the test near the code. */
|
|
2358
2358
|
paths?: string[];
|
|
2359
|
-
|
|
2359
|
+
/**
|
|
2360
|
+
* Optional facts derived from the incident's fix diff (red_ref..HEAD). When present, the scaffold
|
|
2361
|
+
* names the actual symbols the fix touched and pre-fills the commented example around them, so the
|
|
2362
|
+
* human's "fill the assertion" step is a targeted edit rather than a blank page. Deterministic and
|
|
2363
|
+
* green-preserving: the enriched example stays commented (no live imports that might not resolve).
|
|
2364
|
+
*/
|
|
2365
|
+
incidentHints?: IncidentHints;
|
|
2366
|
+
}
|
|
2367
|
+
/** Facts extracted from an incident's fix diff to make a scaffold concrete rather than generic. */
|
|
2368
|
+
interface IncidentHints {
|
|
2369
|
+
/** The pre-fix ref the hints were derived against (for provenance in the header). */
|
|
2370
|
+
redRef?: string;
|
|
2371
|
+
/** Files the fix changed (within the lesson's anchor scope). */
|
|
2372
|
+
changedFiles: string[];
|
|
2373
|
+
/** Symbols the fix added/changed (exported functions/consts/classes; def/func for py/go). */
|
|
2374
|
+
changedSymbols: string[];
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Extract the symbols and files a fix touched from its unified diff (`git diff red_ref..HEAD`).
|
|
2378
|
+
* Pure: the caller produces the diff (I/O). Scans ADDED lines for definitions across JS/TS, Python,
|
|
2379
|
+
* and Go — the frameworks the scaffolder targets — so the generated test can name the real subject.
|
|
2380
|
+
*/
|
|
2381
|
+
declare function incidentHintsFromDiff(diff: string, opts?: {
|
|
2382
|
+
redRef?: string;
|
|
2383
|
+
limitSymbols?: number;
|
|
2384
|
+
}): IncidentHints;
|
|
2360
2385
|
interface TestScaffold {
|
|
2361
2386
|
framework: TestFramework;
|
|
2362
2387
|
/** Suggested project-relative path for the generated test file. */
|
|
@@ -2510,10 +2535,19 @@ interface BootstrapStateInput {
|
|
|
2510
2535
|
* mentions "auto-generated by `hivelore init`" in prose (e.g. a glossary line) is NOT a template.
|
|
2511
2536
|
*/
|
|
2512
2537
|
declare function isTemplateProjectContext(raw: string): boolean;
|
|
2538
|
+
declare function isProductionCodeFile(file: string): boolean;
|
|
2539
|
+
/**
|
|
2540
|
+
* The canonical set of "main code areas" for a repo, derived from the code-map's production files.
|
|
2541
|
+
* A container-based component (packages/x, apps/x) is a DECLARED component and always counts; a bare
|
|
2542
|
+
* top-level dir needs {@link MIN_COMPONENT_FILES} files so trivial folders aren't treated as areas.
|
|
2543
|
+
* Shared so bootstrap, behaviour-coverage, and doctor all report the SAME area set and count.
|
|
2544
|
+
*/
|
|
2545
|
+
declare function deriveMainAreas(codeFiles: string[]): string[];
|
|
2513
2546
|
/** Derive the component (main code area) a file belongs to. */
|
|
2514
2547
|
declare function componentOf(file: string): string;
|
|
2515
2548
|
/** The module-context directory name for a component (its last path segment). */
|
|
2516
2549
|
declare function moduleNameOf(component: string): string;
|
|
2550
|
+
declare function anchorMatchesComponent(anchorPath: string, component: string): boolean;
|
|
2517
2551
|
/**
|
|
2518
2552
|
* Assess whether the repo knowledge layer is filled enough (the EXHAUSTIVE bar):
|
|
2519
2553
|
* 1. project-context.md is filled (not the template, and substantial)
|
|
@@ -2525,6 +2559,73 @@ declare function assessBootstrapState(input: BootstrapStateInput): BootstrapAsse
|
|
|
2525
2559
|
/** Render the assessment's gaps as a numbered checklist for an agent (action_required / gate message). */
|
|
2526
2560
|
declare function renderBootstrapChecklist(assessment: BootstrapAssessment): string;
|
|
2527
2561
|
|
|
2562
|
+
/**
|
|
2563
|
+
* Behaviour-harness coverage — the missing MEASURE for the branch Hivelore leads.
|
|
2564
|
+
*
|
|
2565
|
+
* The maintainability harness has a visible metric (anchor coverage in `doctor`), and the bootstrap
|
|
2566
|
+
* gate reports memory/sensor coverage per area. But the *behaviour* harness — command/test sensors
|
|
2567
|
+
* that route a real oracle to a lesson, optionally proven RED on the incident — had no coverage
|
|
2568
|
+
* number, so its progress was invisible. This module answers three questions per main code area:
|
|
2569
|
+
* 1. Is there ANY behavioural oracle (a `kind: shell|test` sensor) guarding it?
|
|
2570
|
+
* 2. Is that oracle ARMED (severity `block`, so it actually refuses the repeat)?
|
|
2571
|
+
* 3. Is it PROVEN (red_proven — the oracle demonstrably fails on the incident state)?
|
|
2572
|
+
*
|
|
2573
|
+
* Pure domain logic: no I/O. The caller loads memories + the code-map and passes them in. Area
|
|
2574
|
+
* derivation is shared with the bootstrap gate ({@link deriveMainAreas}) so the "N main areas" count
|
|
2575
|
+
* is identical everywhere it is reported.
|
|
2576
|
+
*/
|
|
2577
|
+
|
|
2578
|
+
/** One behavioural oracle sensor (kind shell|test) and the main areas it reaches. */
|
|
2579
|
+
interface BehaviourOracleInfo {
|
|
2580
|
+
memory_id: string;
|
|
2581
|
+
kind: "shell" | "test";
|
|
2582
|
+
/** `block` = armed (refuses the repeat); `warn` = advisory only. */
|
|
2583
|
+
severity: "block" | "warn";
|
|
2584
|
+
/** The oracle demonstrably failed on the recorded incident state at arming time. */
|
|
2585
|
+
red_proven: boolean;
|
|
2586
|
+
/** Main code areas this oracle guards (by anchor or by sensor scope). */
|
|
2587
|
+
areas: string[];
|
|
2588
|
+
}
|
|
2589
|
+
/** A concrete "how to guard this area" pointer — closes the loop from measure to action. */
|
|
2590
|
+
interface UncoveredAreaSuggestion {
|
|
2591
|
+
area: string;
|
|
2592
|
+
/**
|
|
2593
|
+
* An existing lesson (attempt/gotcha anchored into the area, not yet a behavioural oracle) that a
|
|
2594
|
+
* test can be scaffolded from. Absent → no lesson exists there yet; capture the incident first.
|
|
2595
|
+
*/
|
|
2596
|
+
candidateLessonId?: string;
|
|
2597
|
+
}
|
|
2598
|
+
interface BehaviourCoverageMetrics {
|
|
2599
|
+
/** Canonical main code areas (same set the bootstrap gate uses). */
|
|
2600
|
+
mainAreas: string[];
|
|
2601
|
+
/** Areas guarded by at least one behavioural oracle of any severity. */
|
|
2602
|
+
areasWithOracle: string[];
|
|
2603
|
+
/** Areas guarded by at least one ARMED (block) behavioural oracle. */
|
|
2604
|
+
areasWithArmedOracle: string[];
|
|
2605
|
+
/** Areas guarded by at least one red-proven behavioural oracle. */
|
|
2606
|
+
areasWithRedProven: string[];
|
|
2607
|
+
/** Main areas with NO behavioural oracle at all. */
|
|
2608
|
+
uncoveredAreas: string[];
|
|
2609
|
+
/** Per uncovered area: the concrete lesson to scaffold a behavioural oracle from (when one exists). */
|
|
2610
|
+
uncoveredAreaSuggestions: UncoveredAreaSuggestion[];
|
|
2611
|
+
/** Every behavioural oracle sensor found, with the areas it reaches. */
|
|
2612
|
+
oracles: BehaviourOracleInfo[];
|
|
2613
|
+
totalOracles: number;
|
|
2614
|
+
/** Oracles at `block` severity. */
|
|
2615
|
+
armedOracles: number;
|
|
2616
|
+
/** Oracles with red_proven === true. */
|
|
2617
|
+
redProvenOracles: number;
|
|
2618
|
+
}
|
|
2619
|
+
interface BehaviourCoverageInput {
|
|
2620
|
+
memories: LoadedMemory[];
|
|
2621
|
+
/** Raw code file paths from the code-map (this module filters to production files). */
|
|
2622
|
+
codeFiles: string[];
|
|
2623
|
+
}
|
|
2624
|
+
/** Assess how much of the repo's behaviour surface is guarded by armed, proven oracles. */
|
|
2625
|
+
declare function assessBehaviourCoverage(input: BehaviourCoverageInput): BehaviourCoverageMetrics;
|
|
2626
|
+
/** One-line human summary for a receipt / status line (no leading label). */
|
|
2627
|
+
declare function renderBehaviourCoverageLine(m: BehaviourCoverageMetrics): string;
|
|
2628
|
+
|
|
2528
2629
|
/**
|
|
2529
2630
|
* Findings ingestion — the self-feeding half of the sensors story (feature B).
|
|
2530
2631
|
*
|
|
@@ -3312,4 +3413,4 @@ interface ReviewDraftOptions {
|
|
|
3312
3413
|
/** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
|
|
3313
3414
|
declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
|
|
3314
3415
|
|
|
3315
|
-
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 DistilledFailureLesson, 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 ProposedEvalSpec, type ProposedSensorVerdict, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type ScaffoldLoopGap, 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 SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasPendingTestMarker, 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, normalizeFramework, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, 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 };
|
|
3416
|
+
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 BehaviourCoverageInput, type BehaviourCoverageMetrics, type BehaviourOracleInfo, type BootstrapAssessment, type BootstrapGap, type BootstrapGate, type BootstrapMetrics, type BootstrapState, type BootstrapStateInput, type BreakingChange, type BridgeFileOutput, type BridgeMemoryEntry, type BridgeSensor, type BridgeTarget, type BriefingBudgetNumbers, type BriefingBudgetPreset, type BriefingMarker, type BriefingProofLineOptions, type BudgetPart, type BudgetSlice, type BuildCodeMapOptions, CHARS_PER_TOKEN, CODE_MAP_DEFAULT_EXCLUDE, CODE_MAP_DEFAULT_INCLUDE, CODE_MAP_FILE, CODE_STOPWORDS, CONFIG_FILE, 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 DistilledFailureLesson, 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 IncidentHints, 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 ProposedEvalSpec, type ProposedSensorVerdict, REVIEW_LEARNING_MARKER, RUNTIME_JOURNAL_FILENAME, type RecurrenceReport, type RecurrenceRow, type ResolveProjectInfo, type RetirementSignal, type RetrievalAggregate, type RetrievalCase, type RetrievalCaseResult, type ReviewDraftOptions, type ReviewLearning, type RuntimeJournalEntry, SCAFFOLD_MARKER_RE, SEED_QUALITY_FLOOR, SENSOR_ABSENT_LOOKBACK, SENSOR_ABSENT_WINDOW, SESSION_RECAP_TTL_MS, STACK_PACK_TAG, type ScaffoldLoopGap, 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 SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, addedLineNumbersFromDiff, addedLinesFromDiff, aggregateRetrieval, aggregateSensors, aggregateUsage, allocateBudget, anchorMatchesComponent, antiPatternGateParams, appendEvalHistory, appendPreventionEvent, appendProposedRetrievalCases, appendRuntimeJournalEntry, appendSensorEvaluations, appendUsageEvent, applyConflictResolution, applyFeedbackAdjustment, approveProposedCases, assessBehaviourCoverage, assessBootstrapState, assessScaffoldLoop, assessSensorHealth, bridgeMemorySummary, briefingMarkerPath, briefingMarkersDir, briefingProofLine, buildCodeMap, buildCoverageIndex, buildDashboard, buildDocFrequency, buildFrontmatter, buildHandoffMarkdown, buildPreventionReceipt, buildProposeCommand, buildReport, bumpRead, classifyMemoryPriority, codeMapPath, collectTimelineEntries, compactAutoRecapBody, compareEvalReports, compareGatePrecision, compareImpact, compileRegexSensor, componentOf, computeEvalTrend, computeGatePrecision, computeImpact, computePreventionTrend, computeRecurrence, computeScopeHash, configPath, contractLockPath, countSourceFilesOnDisk, deriveConfidence, deriveMainAreas, detectAgentContext, detectSensorWeakening, detectStacksFromManifests, diffContract, diffHasDistinctiveOverlap, distillFailureObservations, distinctiveCap, draftsFromFindings, emptyUsage, emptyUsageIndex, enforcementDir, estimateTokens, evalHistoryPath, evaluateSkillActivation, existingGateMissShas, extractActionsBriefBody, extractReferencedPaths, extractReviewLearnings, extractSensorExamples, extractSnippet, extractTestFilePathsFromCommand, filterNewDrafts, findCoverageGaps, findLexicalConflictPairs, findProjectRoot, findTopicStatusConflictPairs, findUncapturedFailures, findingBody, findingToDraft, firstMemoryOneLine, gatePassedShas, generateBridges, getUsage, globToRegExp, handoffAgeMs, handoffFilePath, hasPendingTestMarker, hasRecentBriefingMarker, hashProjectContext, incidentHintsFromDiff, incidentSuffix, inferModulesFromPaths, isAutoPromoteEligible, isAutoRecap, isCovered, isDecaying, isDistinctiveToken, isEnvWorkaroundMemory, isFreshIsoDate, isGlobPath, isLikelyGuessable, isNoiseSubject, isProductionCodeFile, 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, normalizeFramework, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, readRecentBriefingMarker, readRuntimeJournalTail, readSessionHandoff, readUsageEvents, recommendFeedbackAdjustment, recordApplied, recordPrevention, recordPreventionHits, recordProjectContextEmission, recordRejection, relPathFrom, renderBehaviourCoverageLine, renderBootstrapChecklist, renderCaughtForYou, renderPreventionReceipt, renderPreventionReceiptShare, resolveBriefingBudget, resolveHaivePaths, resolveManifestFiles, resolveProjectInfo, retirementSignal, revertedShaFromCommit, reviewLearningsToDrafts, runRegexSensor, runSensors, runTierContract, runtimeJournalPath, saveCodeMap, saveConfig, saveUsageIndex, scaffoldPostIncidentTest, scannableSensorTargets, scoreRetrievalCase, scoreSensorCase, scrubbedCommandEnv, 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
|
@@ -1151,7 +1151,7 @@ function summarizeCaughtForYou(events, memories, usage, options = {}) {
|
|
|
1151
1151
|
function renderCaughtForYou(summary) {
|
|
1152
1152
|
if (summary.total_catches === 0 || summary.rows.length === 0) return null;
|
|
1153
1153
|
const lines = [
|
|
1154
|
-
`Caught for you: ${summary.total_catches} prevented repeat${summary.total_catches === 1 ? "" : "s"} this session.`
|
|
1154
|
+
`Caught for you: ${summary.total_catches} prevented repeat${summary.total_catches === 1 ? "" : "s"} ${summary.since ? "this session" : "in recorded history"}.`
|
|
1155
1155
|
];
|
|
1156
1156
|
for (const row of summary.rows) {
|
|
1157
1157
|
const gate = row.source === "anti-pattern" ? "Blocked" : "Caught";
|
|
@@ -4744,6 +4744,71 @@ function escapeRegExp(value) {
|
|
|
4744
4744
|
|
|
4745
4745
|
// src/test-scaffold.ts
|
|
4746
4746
|
var TEST_FRAMEWORKS = ["vitest", "jest", "pytest", "gotest"];
|
|
4747
|
+
function incidentHintsFromDiff(diff, opts = {}) {
|
|
4748
|
+
const changedFiles = [];
|
|
4749
|
+
const touched = [];
|
|
4750
|
+
const valueAdded = [];
|
|
4751
|
+
const CONTAINER_PATTERNS = [
|
|
4752
|
+
/(?:^|\s)export\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,
|
|
4753
|
+
/(?:^|\s)export\s+(?:default\s+)?class\s+([A-Za-z_$][\w$]*)/,
|
|
4754
|
+
/(?:^|\s)(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,
|
|
4755
|
+
/(?:^|\s)class\s+([A-Za-z_$][\w$]*)/,
|
|
4756
|
+
/(?:^|\s)def\s+([A-Za-z_][\w]*)\s*\(/,
|
|
4757
|
+
// python
|
|
4758
|
+
/(?:^|\s)func\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w]*)\s*\(/
|
|
4759
|
+
// go (incl. methods)
|
|
4760
|
+
];
|
|
4761
|
+
const VALUE_PATTERN = /(?:^|\s)export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/;
|
|
4762
|
+
const containerOf = (text) => {
|
|
4763
|
+
for (const re of CONTAINER_PATTERNS) {
|
|
4764
|
+
const m = re.exec(text);
|
|
4765
|
+
if (m?.[1]) return m[1];
|
|
4766
|
+
}
|
|
4767
|
+
return null;
|
|
4768
|
+
};
|
|
4769
|
+
let enclosing = null;
|
|
4770
|
+
const markTouched = (sym) => {
|
|
4771
|
+
if (sym && !touched.includes(sym)) touched.push(sym);
|
|
4772
|
+
};
|
|
4773
|
+
for (const raw of diff.split("\n")) {
|
|
4774
|
+
if (raw.startsWith("+++ ")) {
|
|
4775
|
+
const p = raw.slice(4).trim().replace(/^b\//, "");
|
|
4776
|
+
if (p && p !== "/dev/null") changedFiles.push(p);
|
|
4777
|
+
enclosing = null;
|
|
4778
|
+
continue;
|
|
4779
|
+
}
|
|
4780
|
+
if (raw.startsWith("@@")) {
|
|
4781
|
+
enclosing = containerOf(raw.replace(/^@@[^@]*@@/, ""));
|
|
4782
|
+
continue;
|
|
4783
|
+
}
|
|
4784
|
+
if (raw.startsWith("---")) continue;
|
|
4785
|
+
const isAdded = raw.startsWith("+");
|
|
4786
|
+
const isRemoved = raw.startsWith("-");
|
|
4787
|
+
const body = isAdded || isRemoved ? raw.slice(1) : raw.replace(/^ /, "");
|
|
4788
|
+
const container = containerOf(body);
|
|
4789
|
+
if (container) enclosing = container;
|
|
4790
|
+
if (isAdded || isRemoved) {
|
|
4791
|
+
markTouched(enclosing);
|
|
4792
|
+
if (isAdded) {
|
|
4793
|
+
const value = VALUE_PATTERN.exec(body);
|
|
4794
|
+
if (value?.[1]) valueAdded.push(value[1]);
|
|
4795
|
+
}
|
|
4796
|
+
}
|
|
4797
|
+
}
|
|
4798
|
+
const limit = opts.limitSymbols ?? 6;
|
|
4799
|
+
const changedSymbols = [];
|
|
4800
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4801
|
+
for (const sym of [...touched, ...valueAdded]) {
|
|
4802
|
+
if (seen.has(sym)) continue;
|
|
4803
|
+
seen.add(sym);
|
|
4804
|
+
changedSymbols.push(sym);
|
|
4805
|
+
}
|
|
4806
|
+
return {
|
|
4807
|
+
...opts.redRef ? { redRef: opts.redRef } : {},
|
|
4808
|
+
changedFiles: [...new Set(changedFiles)],
|
|
4809
|
+
changedSymbols: changedSymbols.slice(0, limit)
|
|
4810
|
+
};
|
|
4811
|
+
}
|
|
4747
4812
|
function normalizeFramework(input) {
|
|
4748
4813
|
const v = input.trim().toLowerCase();
|
|
4749
4814
|
if (v === "vitest") return "vitest";
|
|
@@ -4799,18 +4864,63 @@ function buildProposeCommand(lesson, runCommand) {
|
|
|
4799
4864
|
return parts.join(" ");
|
|
4800
4865
|
}
|
|
4801
4866
|
function header(lesson, comment) {
|
|
4867
|
+
const hints = lesson.incidentHints;
|
|
4868
|
+
const fixLines = [];
|
|
4869
|
+
if (hints && (hints.changedSymbols.length > 0 || hints.changedFiles.length > 0)) {
|
|
4870
|
+
const ref = hints.redRef ? ` (${hints.redRef}..HEAD)` : "";
|
|
4871
|
+
if (hints.changedSymbols.length > 0) {
|
|
4872
|
+
fixLines.push(`Fix${ref} touched: ${hints.changedSymbols.join(", ")}` + (hints.changedFiles.length > 0 ? ` in ${hints.changedFiles.slice(0, 3).join(", ")}` : "") + ".");
|
|
4873
|
+
} else {
|
|
4874
|
+
fixLines.push(`Fix${ref} touched: ${hints.changedFiles.slice(0, 3).join(", ")}.`);
|
|
4875
|
+
}
|
|
4876
|
+
}
|
|
4802
4877
|
const lines = [
|
|
4803
4878
|
`Post-incident guard generated by Hivelore from ${lesson.memoryId}.`,
|
|
4804
4879
|
...lesson.incident ? [`Incident: ${lesson.incident}`] : [],
|
|
4805
4880
|
`What failed: ${oneLine(lesson.title)}`,
|
|
4806
4881
|
...lesson.whyFailed ? [`Why: ${oneLine(lesson.whyFailed)}`] : [],
|
|
4807
4882
|
...lesson.instead ? [`Expected / fix: ${oneLine(lesson.instead)}`] : [],
|
|
4883
|
+
...fixLines,
|
|
4808
4884
|
"",
|
|
4809
4885
|
"TODO: replace the pending test with a real check that FAILS on the incident and",
|
|
4810
4886
|
"PASSES once the fix is in place. Then arm it as a deterministic gate:"
|
|
4811
4887
|
];
|
|
4812
4888
|
return lines.map(comment).join("\n");
|
|
4813
4889
|
}
|
|
4890
|
+
function exampleLines(lesson, lang) {
|
|
4891
|
+
const symbol = lesson.incidentHints?.changedSymbols[0];
|
|
4892
|
+
const file = lesson.incidentHints?.changedFiles[0];
|
|
4893
|
+
if (lang === "js") {
|
|
4894
|
+
if (symbol) {
|
|
4895
|
+
return [
|
|
4896
|
+
`// it("guards the incident", () => {`,
|
|
4897
|
+
...file ? [`// import { ${symbol} } from "${importSpecifier(file)}"; // adjust the relative path`] : [],
|
|
4898
|
+
`// // Reproduce the incident input, then assert the behaviour the fix guarantees:`,
|
|
4899
|
+
`// expect(${symbol}(/* incident input */)).toBe(/* post-fix expected */);`,
|
|
4900
|
+
`// });`
|
|
4901
|
+
];
|
|
4902
|
+
}
|
|
4903
|
+
return [
|
|
4904
|
+
`// it("guards the incident", () => {`,
|
|
4905
|
+
`// // Arrange the state that caused the incident, then assert the fixed behaviour.`,
|
|
4906
|
+
`// expect(subjectUnderTest()).toBe(/* expected */);`,
|
|
4907
|
+
`// });`
|
|
4908
|
+
];
|
|
4909
|
+
}
|
|
4910
|
+
if (lang === "py") {
|
|
4911
|
+
return symbol ? [
|
|
4912
|
+
` # Reproduce the incident input, then assert what the fix guarantees:`,
|
|
4913
|
+
` assert ${symbol}(...) == expected # ${symbol} was changed by the fix`
|
|
4914
|
+
] : [
|
|
4915
|
+
` # Arrange the state that caused the incident, then assert the fixed behaviour.`,
|
|
4916
|
+
` assert subject_under_test() == expected`
|
|
4917
|
+
];
|
|
4918
|
+
}
|
|
4919
|
+
return symbol ? [` // Reproduce the incident input, then assert what the fix guarantees (subject: ${symbol}).`] : [` // Arrange the state that caused the incident, then assert the fixed behaviour.`];
|
|
4920
|
+
}
|
|
4921
|
+
function importSpecifier(file) {
|
|
4922
|
+
return file.replace(/\.[cm]?[jt]sx?$/, "");
|
|
4923
|
+
}
|
|
4814
4924
|
function scaffoldPostIncidentTest(lesson, options) {
|
|
4815
4925
|
const framework = options.framework;
|
|
4816
4926
|
const short = lessonShortName(lesson.memoryId);
|
|
@@ -4832,10 +4942,7 @@ function scaffoldPostIncidentTest(lesson, options) {
|
|
|
4832
4942
|
` + importLine + `describe(${JSON.stringify(desc)}, () => {
|
|
4833
4943
|
it.todo("reproduces ${lesson.memoryId} and stays fixed");
|
|
4834
4944
|
|
|
4835
|
-
|
|
4836
|
-
// // Arrange the state that caused the incident, then assert the fixed behaviour.
|
|
4837
|
-
// expect(subjectUnderTest()).toBe(/* expected */);
|
|
4838
|
-
// });
|
|
4945
|
+
` + exampleLines(lesson, "js").map((l) => ` ${l}`).join("\n") + `
|
|
4839
4946
|
});
|
|
4840
4947
|
`;
|
|
4841
4948
|
} else if (framework === "pytest") {
|
|
@@ -4851,9 +4958,7 @@ import pytest
|
|
|
4851
4958
|
|
|
4852
4959
|
@pytest.mark.skip(reason="TODO: write the post-incident assertion, then arm the sensor")
|
|
4853
4960
|
def test_${fn}():
|
|
4854
|
-
|
|
4855
|
-
assert subject_under_test() == expected
|
|
4856
|
-
`;
|
|
4961
|
+
` + exampleLines(lesson, "py").join("\n") + "\n";
|
|
4857
4962
|
} else {
|
|
4858
4963
|
const fn = pascal(short);
|
|
4859
4964
|
const dir = options.outPath ? options.outPath.replace(/\/[^/]+$/, "") : joinRel(options.baseDir, "incidents");
|
|
@@ -4869,7 +4974,7 @@ import "testing"
|
|
|
4869
4974
|
|
|
4870
4975
|
func Test${fn}(t *testing.T) {
|
|
4871
4976
|
t.Skip("TODO: write the post-incident assertion, then arm the sensor")
|
|
4872
|
-
|
|
4977
|
+
` + exampleLines(lesson, "go").join("\n") + `
|
|
4873
4978
|
}
|
|
4874
4979
|
`;
|
|
4875
4980
|
}
|
|
@@ -4931,6 +5036,16 @@ function isProductionCodeFile(file) {
|
|
|
4931
5036
|
if (base.endsWith(".config.ts") || base.endsWith(".config.js") || base.endsWith(".config.mjs")) return false;
|
|
4932
5037
|
return true;
|
|
4933
5038
|
}
|
|
5039
|
+
function deriveMainAreas(codeFiles) {
|
|
5040
|
+
const production = codeFiles.filter(isProductionCodeFile);
|
|
5041
|
+
const fileCounts = /* @__PURE__ */ new Map();
|
|
5042
|
+
for (const f of production) {
|
|
5043
|
+
const c = componentOf(f);
|
|
5044
|
+
if (!c) continue;
|
|
5045
|
+
fileCounts.set(c, (fileCounts.get(c) ?? 0) + 1);
|
|
5046
|
+
}
|
|
5047
|
+
return [...fileCounts.entries()].filter(([c, n]) => c.includes("/") || n >= MIN_COMPONENT_FILES).map(([c]) => c).sort();
|
|
5048
|
+
}
|
|
4934
5049
|
function componentOf(file) {
|
|
4935
5050
|
const parts = file.replace(/^\/+/, "").split("/").filter(Boolean);
|
|
4936
5051
|
if (parts.length >= 2 && CONTAINER_DIRS.has(parts[0])) return `${parts[0]}/${parts[1]}`;
|
|
@@ -4948,13 +5063,7 @@ function anchorMatchesComponent(anchorPath, component) {
|
|
|
4948
5063
|
function assessBootstrapState(input) {
|
|
4949
5064
|
const projectContextFilled = !isTemplateProjectContext(input.projectContextRaw) && input.projectContextRaw.trim().length >= MIN_CONTEXT_CHARS;
|
|
4950
5065
|
const codeFiles = input.codeFiles.filter(isProductionCodeFile);
|
|
4951
|
-
const
|
|
4952
|
-
for (const f of codeFiles) {
|
|
4953
|
-
const c = componentOf(f);
|
|
4954
|
-
if (!c) continue;
|
|
4955
|
-
fileCounts.set(c, (fileCounts.get(c) ?? 0) + 1);
|
|
4956
|
-
}
|
|
4957
|
-
const components = [...fileCounts.entries()].filter(([c, n]) => c.includes("/") || n >= MIN_COMPONENT_FILES).map(([c]) => c).sort();
|
|
5066
|
+
const components = deriveMainAreas(input.codeFiles);
|
|
4958
5067
|
const anchoredMemories = input.memories.filter(
|
|
4959
5068
|
(m) => (m.memory.frontmatter.status === "validated" || m.memory.frontmatter.status === "proposed") && m.memory.frontmatter.anchor.paths.length > 0
|
|
4960
5069
|
);
|
|
@@ -5054,6 +5163,88 @@ function renderBootstrapChecklist(assessment) {
|
|
|
5054
5163
|
return lines.join("\n");
|
|
5055
5164
|
}
|
|
5056
5165
|
|
|
5166
|
+
// src/behaviour-coverage.ts
|
|
5167
|
+
function oracleReachesArea(m, area, productionInArea) {
|
|
5168
|
+
const fm = m.memory.frontmatter;
|
|
5169
|
+
if (fm.anchor.paths.some((p) => anchorMatchesComponent(p, area))) return true;
|
|
5170
|
+
const scopes = fm.sensor?.paths ?? [];
|
|
5171
|
+
return scopes.some((raw) => {
|
|
5172
|
+
const scope = raw.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
5173
|
+
if (!scope) return false;
|
|
5174
|
+
if (isGlobPath(scope)) {
|
|
5175
|
+
const re = globToRegExp(scope);
|
|
5176
|
+
return productionInArea.some((f) => re.test(f));
|
|
5177
|
+
}
|
|
5178
|
+
return anchorMatchesComponent(scope, area);
|
|
5179
|
+
});
|
|
5180
|
+
}
|
|
5181
|
+
function assessBehaviourCoverage(input) {
|
|
5182
|
+
const mainAreas = deriveMainAreas(input.codeFiles);
|
|
5183
|
+
const production = input.codeFiles.filter(isProductionCodeFile);
|
|
5184
|
+
const filesByArea = /* @__PURE__ */ new Map();
|
|
5185
|
+
for (const area of mainAreas) {
|
|
5186
|
+
filesByArea.set(area, production.filter((f) => componentOf(f) === area));
|
|
5187
|
+
}
|
|
5188
|
+
const oracleMemories = input.memories.filter((m) => {
|
|
5189
|
+
const s = m.memory.frontmatter.sensor;
|
|
5190
|
+
if (!s || s.kind !== "shell" && s.kind !== "test") return false;
|
|
5191
|
+
const status = m.memory.frontmatter.status;
|
|
5192
|
+
return status === "validated" || status === "proposed";
|
|
5193
|
+
});
|
|
5194
|
+
const oracles = oracleMemories.map((m) => {
|
|
5195
|
+
const s = m.memory.frontmatter.sensor;
|
|
5196
|
+
const areas = mainAreas.filter((area) => oracleReachesArea(m, area, filesByArea.get(area) ?? []));
|
|
5197
|
+
return {
|
|
5198
|
+
memory_id: m.memory.frontmatter.id,
|
|
5199
|
+
kind: s.kind === "shell" ? "shell" : "test",
|
|
5200
|
+
severity: s.severity === "block" ? "block" : "warn",
|
|
5201
|
+
red_proven: s.red_proven === true,
|
|
5202
|
+
areas
|
|
5203
|
+
};
|
|
5204
|
+
});
|
|
5205
|
+
const areasWith = (predicate) => mainAreas.filter((area) => oracles.some((o) => o.areas.includes(area) && predicate(o)));
|
|
5206
|
+
const areasWithOracle = areasWith(() => true);
|
|
5207
|
+
const areasWithArmedOracle = areasWith((o) => o.severity === "block");
|
|
5208
|
+
const areasWithRedProven = areasWith((o) => o.red_proven);
|
|
5209
|
+
const uncoveredAreas = mainAreas.filter((area) => !areasWithOracle.includes(area));
|
|
5210
|
+
const scaffoldableLessons = input.memories.filter((m) => {
|
|
5211
|
+
const fm = m.memory.frontmatter;
|
|
5212
|
+
if (fm.type !== "attempt" && fm.type !== "gotcha") return false;
|
|
5213
|
+
if (fm.status !== "validated" && fm.status !== "proposed") return false;
|
|
5214
|
+
const kind = fm.sensor?.kind;
|
|
5215
|
+
return kind !== "shell" && kind !== "test";
|
|
5216
|
+
});
|
|
5217
|
+
const uncoveredAreaSuggestions = uncoveredAreas.map((area) => {
|
|
5218
|
+
const candidates = scaffoldableLessons.filter((m) => m.memory.frontmatter.anchor.paths.some((p) => anchorMatchesComponent(p, area))).sort((a, b) => {
|
|
5219
|
+
const rank = (m) => m.memory.frontmatter.type === "attempt" ? 0 : 1;
|
|
5220
|
+
const byType = rank(a) - rank(b);
|
|
5221
|
+
if (byType !== 0) return byType;
|
|
5222
|
+
return String(b.memory.frontmatter.created_at ?? "").localeCompare(String(a.memory.frontmatter.created_at ?? ""));
|
|
5223
|
+
});
|
|
5224
|
+
const id = candidates[0]?.memory.frontmatter.id;
|
|
5225
|
+
return id ? { area, candidateLessonId: id } : { area };
|
|
5226
|
+
});
|
|
5227
|
+
return {
|
|
5228
|
+
mainAreas,
|
|
5229
|
+
areasWithOracle,
|
|
5230
|
+
areasWithArmedOracle,
|
|
5231
|
+
areasWithRedProven,
|
|
5232
|
+
uncoveredAreas,
|
|
5233
|
+
uncoveredAreaSuggestions,
|
|
5234
|
+
oracles,
|
|
5235
|
+
totalOracles: oracles.length,
|
|
5236
|
+
armedOracles: oracles.filter((o) => o.severity === "block").length,
|
|
5237
|
+
redProvenOracles: oracles.filter((o) => o.red_proven).length
|
|
5238
|
+
};
|
|
5239
|
+
}
|
|
5240
|
+
function renderBehaviourCoverageLine(m) {
|
|
5241
|
+
if (m.mainAreas.length === 0) return "no main code areas detected";
|
|
5242
|
+
if (m.totalOracles === 0) {
|
|
5243
|
+
return `0/${m.mainAreas.length} area(s) guarded by a behavioural oracle (no test/shell sensors yet)`;
|
|
5244
|
+
}
|
|
5245
|
+
return `${m.areasWithOracle.length}/${m.mainAreas.length} area(s) guarded by a behavioural oracle (${m.areasWithArmedOracle.length} armed, ${m.areasWithRedProven.length} red-proven)`;
|
|
5246
|
+
}
|
|
5247
|
+
|
|
5057
5248
|
// src/findings.ts
|
|
5058
5249
|
var STYLISTIC_RULE_RE = /(?:^|[/:])(?:prettier|semi|semi-spacing|no-extra-semi|quotes|jsx-quotes|quote-props|indent|comma-dangle|comma-spacing|comma-style|eol-last|linebreak-style|no-trailing-spaces|no-multiple-empty-lines|no-multi-spaces|object-curly-spacing|array-bracket-spacing|block-spacing|space-before-blocks|space-before-function-paren|space-infix-ops|space-in-parens|keyword-spacing|arrow-spacing|key-spacing|func-call-spacing|padded-blocks|padding-line-between-statements|brace-style|spaced-comment|max-len|prefer-const|no-var)(?:$|[/:])/i;
|
|
5059
5250
|
var SONAR_STYLISTIC_KEYS = /* @__PURE__ */ new Set([
|
|
@@ -6276,6 +6467,7 @@ export {
|
|
|
6276
6467
|
aggregateSensors,
|
|
6277
6468
|
aggregateUsage,
|
|
6278
6469
|
allocateBudget,
|
|
6470
|
+
anchorMatchesComponent,
|
|
6279
6471
|
antiPatternGateParams,
|
|
6280
6472
|
appendEvalHistory,
|
|
6281
6473
|
appendPreventionEvent,
|
|
@@ -6286,6 +6478,7 @@ export {
|
|
|
6286
6478
|
applyConflictResolution,
|
|
6287
6479
|
applyFeedbackAdjustment,
|
|
6288
6480
|
approveProposedCases,
|
|
6481
|
+
assessBehaviourCoverage,
|
|
6289
6482
|
assessBootstrapState,
|
|
6290
6483
|
assessScaffoldLoop,
|
|
6291
6484
|
assessSensorHealth,
|
|
@@ -6322,6 +6515,7 @@ export {
|
|
|
6322
6515
|
contractLockPath,
|
|
6323
6516
|
countSourceFilesOnDisk,
|
|
6324
6517
|
deriveConfidence,
|
|
6518
|
+
deriveMainAreas,
|
|
6325
6519
|
detectAgentContext,
|
|
6326
6520
|
detectSensorWeakening,
|
|
6327
6521
|
detectStacksFromManifests,
|
|
@@ -6361,6 +6555,7 @@ export {
|
|
|
6361
6555
|
hasPendingTestMarker,
|
|
6362
6556
|
hasRecentBriefingMarker,
|
|
6363
6557
|
hashProjectContext,
|
|
6558
|
+
incidentHintsFromDiff,
|
|
6364
6559
|
incidentSuffix,
|
|
6365
6560
|
inferModulesFromPaths,
|
|
6366
6561
|
isAutoPromoteEligible,
|
|
@@ -6373,6 +6568,7 @@ export {
|
|
|
6373
6568
|
isGlobPath,
|
|
6374
6569
|
isLikelyGuessable,
|
|
6375
6570
|
isNoiseSubject,
|
|
6571
|
+
isProductionCodeFile,
|
|
6376
6572
|
isRetiredMemory,
|
|
6377
6573
|
isSensorScannablePath,
|
|
6378
6574
|
isSkill,
|
|
@@ -6444,6 +6640,7 @@ export {
|
|
|
6444
6640
|
recordProjectContextEmission,
|
|
6445
6641
|
recordRejection,
|
|
6446
6642
|
relPathFrom,
|
|
6643
|
+
renderBehaviourCoverageLine,
|
|
6447
6644
|
renderBootstrapChecklist,
|
|
6448
6645
|
renderCaughtForYou,
|
|
6449
6646
|
renderPreventionReceipt,
|