@hivelore/core 0.46.0 → 0.49.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
@@ -2393,8 +2393,21 @@ interface TestScaffold {
2393
2393
  /** Ready-to-run wiring command: arms the test as a deterministic gate AFTER it is written. */
2394
2394
  proposeCommand: string;
2395
2395
  }
2396
+ /**
2397
+ * The shape of the generated test — each lowers the cost of expressing the invariant differently:
2398
+ * - `example` one input → expected output (default; cheapest to grasp, narrowest coverage).
2399
+ * - `property` state the invariant ONCE and let fast-check / Hypothesis check it over many
2400
+ * generated inputs — a broader, partial oracle for a one-line-expressible invariant.
2401
+ * - `differential` state NO invariant: assert the subject AGREES with a reference implementation for
2402
+ * all generated inputs (when a second impl or legacy exists — the oracle is redundancy).
2403
+ */
2404
+ type ScaffoldStyle = "example" | "property" | "differential";
2396
2405
  interface ScaffoldOptions {
2397
2406
  framework: TestFramework;
2407
+ /** Test shape (default 'example'). See {@link ScaffoldStyle}. */
2408
+ style?: ScaffoldStyle;
2409
+ /** kind=differential only: import specifier of the reference implementation to compare against. */
2410
+ reference?: string;
2398
2411
  /** Override the generated file path (project-relative). Wins over baseDir. */
2399
2412
  outPath?: string;
2400
2413
  /**
@@ -2440,6 +2453,8 @@ declare function parseLessonFields(body: string): {
2440
2453
  * proposal (a memory carries a single sensor).
2441
2454
  */
2442
2455
  declare function buildProposeCommand(lesson: PostIncidentLesson, runCommand: string): string;
2456
+ /** Map a user string to a scaffold style, or null. */
2457
+ declare function normalizeScaffoldStyle(input: string): ScaffoldStyle | null;
2443
2458
  /** Build a scaffold for the given lesson + framework. Pure — the caller writes `content` to `relPath`. */
2444
2459
  declare function scaffoldPostIncidentTest(lesson: PostIncidentLesson, options: ScaffoldOptions): TestScaffold;
2445
2460
  /** First-line provenance marker every generated scaffold carries. */
@@ -3413,4 +3428,4 @@ interface ReviewDraftOptions {
3413
3428
  /** Template review learnings into proposed-memory drafts (reuses the scanner-ingest draft shape). */
3414
3429
  declare function reviewLearningsToDrafts(learnings: ReviewLearning[], options?: ReviewDraftOptions): MemoryDraft[];
3415
3430
 
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 };
3431
+ 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 ScaffoldStyle, type SeedProposal, type SelfEvalOptions, type Sensor, type SensorAggregate, type SensorCase, type SensorCaseResult, type SensorEvaluation, type SensorEvaluationOutcome, type SensorEvaluationStage, type SensorFlap, type SensorHealth, type SensorHit, type SensorRow, SensorSchema, type SensorSeed, type SensorSelfCheck, type SensorSuggestionOptions, type SensorTarget, type SensorWeakening, type SessionHandoffData, type SkillActivation, TEST_FRAMEWORKS, type TestFramework, type TestScaffold, type TierContractCheck, type TimelineEntry, type TopicStatusPair, type TruncateOptions, type TruncateResult, USAGE_FILE, USAGE_LOG_DIR, USAGE_LOG_FILE, type UncapturedFailure, type UncoveredAreaSuggestion, type UsageAggregate, type UsageEvent, type UsageIndex, type VerifyOptions, type VerifyResult, 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, normalizeScaffoldStyle, normalizeSessionId, overallScore, parseEslintJson, parseFileAst, parseFindings, parseLessonFields, parseMemory, parseNpmAudit, parseSarif, parseSince, parseSonar, pathsOverlap, pickSnippetNeedle, pickTestFramework, planConflictResolution, planGitWatch, prepareBridgeData, preventionLogPath, priorityRank, prioritySignals, projectContextRecentlyEmitted, proposeGateMissDrafts, proposeSeedsFromCommits, pullCrossRepoSources, quarantineNote, queryCodeMap, rankMemoriesLexical, 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
@@ -4863,7 +4863,21 @@ function buildProposeCommand(lesson, runCommand) {
4863
4863
  if (scope.length > 0) parts.push(`--paths ${JSON.stringify(scope.join(","))}`);
4864
4864
  return parts.join(" ");
4865
4865
  }
4866
- function header(lesson, comment) {
4866
+ function normalizeScaffoldStyle(input) {
4867
+ const v = input.trim().toLowerCase();
4868
+ if (v === "example" || v === "property" || v === "differential") return v;
4869
+ return null;
4870
+ }
4871
+ function styleNote(style, reference) {
4872
+ if (style === "property") {
4873
+ return "Style: property-based \u2014 state the invariant once; it is checked over many generated inputs.";
4874
+ }
4875
+ if (style === "differential") {
4876
+ return `Style: differential \u2014 assert the subject AGREES with the reference (${reference ?? "<reference>"}) for all inputs.`;
4877
+ }
4878
+ return void 0;
4879
+ }
4880
+ function header(lesson, comment, style) {
4867
4881
  const hints = lesson.incidentHints;
4868
4882
  const fixLines = [];
4869
4883
  if (hints && (hints.changedSymbols.length > 0 || hints.changedFiles.length > 0)) {
@@ -4881,6 +4895,7 @@ function header(lesson, comment) {
4881
4895
  ...lesson.whyFailed ? [`Why: ${oneLine(lesson.whyFailed)}`] : [],
4882
4896
  ...lesson.instead ? [`Expected / fix: ${oneLine(lesson.instead)}`] : [],
4883
4897
  ...fixLines,
4898
+ ...style ? [style] : [],
4884
4899
  "",
4885
4900
  "TODO: replace the pending test with a real check that FAILS on the incident and",
4886
4901
  "PASSES once the fix is in place. Then arm it as a deterministic gate:"
@@ -4921,8 +4936,73 @@ function exampleLines(lesson, lang) {
4921
4936
  function importSpecifier(file) {
4922
4937
  return file.replace(/\.[cm]?[jt]sx?$/, "");
4923
4938
  }
4939
+ function propertyLines(lesson, lang) {
4940
+ const symbol = lesson.incidentHints?.changedSymbols[0] ?? "subjectUnderTest";
4941
+ const file = lesson.incidentHints?.changedFiles[0];
4942
+ const invariant = lesson.instead ? oneLine(lesson.instead) : void 0;
4943
+ if (lang === "js") {
4944
+ return [
4945
+ `// Property-based guard \u2014 state the invariant ONCE; it is checked over many generated inputs.`,
4946
+ `// Add at the top: import fc from "fast-check"; (npm i -D fast-check)`,
4947
+ `// it("property: the invariant holds for all inputs", () => {`,
4948
+ ...file ? [`// import { ${symbol} } from "${importSpecifier(file)}"; // adjust the relative path`] : [],
4949
+ ...invariant ? [`// // Invariant (from the lesson): ${invariant}`] : [],
4950
+ `// fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) =>`,
4951
+ `// /* the boolean invariant over ${symbol}(a, b) */`,
4952
+ `// ));`,
4953
+ `// });`
4954
+ ];
4955
+ }
4956
+ if (lang === "py") {
4957
+ return [
4958
+ ` # Property-based guard \u2014 state the invariant once; checked over many generated inputs.`,
4959
+ ` # from hypothesis import given, strategies as st`,
4960
+ ` # @given(st.integers(), st.integers())`,
4961
+ ` # def test_property(a, b):`,
4962
+ ...invariant ? [` # # Invariant (from the lesson): ${invariant}`] : [],
4963
+ ` # assert (the boolean invariant over ${symbol}(a, b))`
4964
+ ];
4965
+ }
4966
+ return [` // Property-based guard: check the invariant over generated inputs (e.g. github.com/leanovate/gopter). Subject: ${symbol}.`];
4967
+ }
4968
+ function differentialLines(lesson, lang, reference) {
4969
+ const symbol = lesson.incidentHints?.changedSymbols[0] ?? "subjectUnderTest";
4970
+ const file = lesson.incidentHints?.changedFiles[0];
4971
+ const ref = reference ?? "<REFERENCE>";
4972
+ if (lang === "js") {
4973
+ return [
4974
+ `// Differential guard \u2014 no invariant to state: assert the subject AGREES with a reference for all inputs.`,
4975
+ `// Add at the top: import fc from "fast-check"; (npm i -D fast-check)`,
4976
+ `// it("differential: subject matches the reference for all inputs", () => {`,
4977
+ ...file ? [`// import { ${symbol} } from "${importSpecifier(file)}"; // subject`] : [],
4978
+ `// import { ${symbol} as reference } from "${ref}"; // reference implementation`,
4979
+ `// fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) =>`,
4980
+ `// ${symbol}(a, b) === reference(a, b)`,
4981
+ `// ));`,
4982
+ `// });`
4983
+ ];
4984
+ }
4985
+ if (lang === "py") {
4986
+ return [
4987
+ ` # Differential guard \u2014 assert the subject agrees with a reference for all generated inputs.`,
4988
+ ` # from hypothesis import given, strategies as st`,
4989
+ ` # from ${ref} import ${symbol} as reference`,
4990
+ ` # @given(st.integers(), st.integers())`,
4991
+ ` # def test_differential(a, b):`,
4992
+ ` # assert ${symbol}(a, b) == reference(a, b)`
4993
+ ];
4994
+ }
4995
+ return [` // Differential guard: assert ${symbol} agrees with the reference (${ref}) over generated inputs (e.g. gopter).`];
4996
+ }
4997
+ function bodyLines(lesson, lang, style, reference) {
4998
+ if (style === "property") return propertyLines(lesson, lang);
4999
+ if (style === "differential") return differentialLines(lesson, lang, reference);
5000
+ return exampleLines(lesson, lang);
5001
+ }
4924
5002
  function scaffoldPostIncidentTest(lesson, options) {
4925
5003
  const framework = options.framework;
5004
+ const style = options.style ?? "example";
5005
+ const note = styleNote(style, options.reference);
4926
5006
  const short = lessonShortName(lesson.memoryId);
4927
5007
  const desc = oneLine(lesson.title) || short;
4928
5008
  const propose = (run) => options.proposeCommandOverride ?? buildProposeCommand(lesson, run);
@@ -4936,13 +5016,13 @@ function scaffoldPostIncidentTest(lesson, options) {
4936
5016
  const importLine = framework === "vitest" ? `import { describe, it, expect } from "vitest";
4937
5017
 
4938
5018
  ` : "";
4939
- content = `${header(lesson, hc)}
5019
+ content = `${header(lesson, hc, note)}
4940
5020
  // ${propose(runCommand)}
4941
5021
 
4942
5022
  ` + importLine + `describe(${JSON.stringify(desc)}, () => {
4943
5023
  it.todo("reproduces ${lesson.memoryId} and stays fixed");
4944
5024
 
4945
- ` + exampleLines(lesson, "js").map((l) => ` ${l}`).join("\n") + `
5025
+ ` + bodyLines(lesson, "js", style, options.reference).map((l) => ` ${l}`).join("\n") + `
4946
5026
  });
4947
5027
  `;
4948
5028
  } else if (framework === "pytest") {
@@ -4950,7 +5030,7 @@ function scaffoldPostIncidentTest(lesson, options) {
4950
5030
  relPath = options.outPath ?? joinRel(options.baseDir, `tests/incidents/test_${fn}.py`);
4951
5031
  runCommand = `pytest ${relPath}`;
4952
5032
  const hc = (l) => l ? `# ${l}` : "#";
4953
- content = `${header(lesson, hc)}
5033
+ content = `${header(lesson, hc, note)}
4954
5034
  # ${propose(runCommand)}
4955
5035
 
4956
5036
  import pytest
@@ -4958,14 +5038,14 @@ import pytest
4958
5038
 
4959
5039
  @pytest.mark.skip(reason="TODO: write the post-incident assertion, then arm the sensor")
4960
5040
  def test_${fn}():
4961
- ` + exampleLines(lesson, "py").join("\n") + "\n";
5041
+ ` + bodyLines(lesson, "py", style, options.reference).join("\n") + "\n";
4962
5042
  } else {
4963
5043
  const fn = pascal(short);
4964
5044
  const dir = options.outPath ? options.outPath.replace(/\/[^/]+$/, "") : joinRel(options.baseDir, "incidents");
4965
5045
  relPath = options.outPath ?? joinRel(options.baseDir, `incidents/incident_${snake(short)}_test.go`);
4966
5046
  runCommand = `go test ./${dir}/`;
4967
5047
  const hc = (l) => l ? `// ${l}` : "//";
4968
- content = `${header(lesson, hc)}
5048
+ content = `${header(lesson, hc, note)}
4969
5049
  // ${propose(runCommand)}
4970
5050
 
4971
5051
  package incidents
@@ -4974,7 +5054,7 @@ import "testing"
4974
5054
 
4975
5055
  func Test${fn}(t *testing.T) {
4976
5056
  t.Skip("TODO: write the post-incident assertion, then arm the sensor")
4977
- ` + exampleLines(lesson, "go").join("\n") + `
5057
+ ` + bodyLines(lesson, "go", style, options.reference).join("\n") + `
4978
5058
  }
4979
5059
  `;
4980
5060
  }
@@ -5781,23 +5861,28 @@ function findUncapturedFailures(failures, captureTimes, options = {}) {
5781
5861
  out.sort((a, b) => a.ts.localeCompare(b.ts));
5782
5862
  return out;
5783
5863
  }
5784
- var EXPLORATORY_RE = /^(ls|find|grep|rg|cat|head|tail|which|stat)\b/i;
5864
+ var EXPLORATORY_RE = /^(ls|find|grep|rg|cat|head|tail|which|stat|cd|pushd|popd|pwd|mkdir|rmdir|echo|printf|touch|cp|mv|rm|export|set|unset|source|test|true|false|sleep|wc|sort|uniq|cut|env|\[|\.)\b/i;
5865
+ var SUBSTANTIVE_RE = /\b(vitest|jest|mocha|pytest|unittest|go\s+test|cargo|gradle|mvn|tsc|typecheck|eslint|biome|ruff|mypy|flake8|pnpm|npm|yarn|bun|make|docker|compose|terraform|prisma|migrate|migration|build|lint)\b/i;
5866
+ function commandText(summary) {
5867
+ return summary.replace(/^[A-Za-z_]+:\s*/, "").trim();
5868
+ }
5785
5869
  function distillFailureObservations(failures, options = {}) {
5786
5870
  const max = options.max ?? 3;
5787
5871
  const clusters = /* @__PURE__ */ new Map();
5788
5872
  for (const f of failures) {
5789
5873
  const summary = f.summary.trim();
5790
- if (!summary || EXPLORATORY_RE.test(summary.replace(/^Bash:\s*/i, ""))) continue;
5874
+ const cmd = commandText(summary);
5875
+ if (!summary || EXPLORATORY_RE.test(cmd)) continue;
5791
5876
  const key = normalizeSummary(summary);
5792
5877
  const existing = clusters.get(key);
5793
5878
  if (existing) {
5794
5879
  existing.count++;
5795
5880
  for (const file of f.files ?? []) existing.files.add(file);
5796
5881
  } else {
5797
- clusters.set(key, { first: f, count: 1, files: new Set(f.files ?? []) });
5882
+ clusters.set(key, { first: f, count: 1, files: new Set(f.files ?? []), substantive: SUBSTANTIVE_RE.test(cmd) });
5798
5883
  }
5799
5884
  }
5800
- return [...clusters.values()].sort((a, b) => b.count - a.count || b.first.ts.localeCompare(a.first.ts)).slice(0, max).map(({ first, count, files }) => {
5885
+ return [...clusters.values()].filter((c) => c.count >= 2 || c.substantive).sort((a, b) => b.count - a.count || b.first.ts.localeCompare(a.first.ts)).slice(0, max).map(({ first, count, files }) => {
5801
5886
  const summary = first.summary.trim();
5802
5887
  const firstLine = summary.split("\n")[0].slice(0, 120);
5803
5888
  return {
@@ -6602,6 +6687,7 @@ export {
6602
6687
  newMemoryId,
6603
6688
  normalizeFindingSeverity,
6604
6689
  normalizeFramework,
6690
+ normalizeScaffoldStyle,
6605
6691
  normalizeSessionId,
6606
6692
  overallScore,
6607
6693
  parseEslintJson,