@davenportsociety/clear-thought-patterns
Version:
A Model Context Protocol (MCP) server providing systematic thinking tools, mental models, and debugging approaches for enhanced problem-solving capabilities
1,555 lines (1,544 loc) • 229 kB
JavaScript
#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/index.ts
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
// src/state/stores/base-store.ts
var _BaseStore = class _BaseStore {
constructor(storeName) {
/** Internal storage map */
__publicField(this, "data");
/** Store name for logging and debugging */
__publicField(this, "storeName");
this.storeName = storeName;
this.data = /* @__PURE__ */ new Map();
}
/**
* Get a specific item by ID
* @param id - The item's unique identifier
* @returns The item if found, undefined otherwise
*/
get(id) {
return this.data.get(id);
}
/**
* Check if an item exists
* @param id - The item's unique identifier
* @returns True if the item exists
*/
has(id) {
return this.data.has(id);
}
/**
* Delete a specific item
* @param id - The item's unique identifier
* @returns True if the item was deleted
*/
delete(id) {
return this.data.delete(id);
}
/**
* Get the number of items in the store
* @returns The count of items
*/
size() {
return this.data.size;
}
/**
* Export all data for persistence
* @returns Serializable representation of the store
*/
export() {
const result = {};
this.data.forEach((value, key) => {
result[key] = value;
});
return result;
}
/**
* Import data from a serialized representation
* @param data - The data to import
*/
import(data) {
this.clear();
Object.entries(data).forEach(([key, value]) => {
this.add(key, value);
});
}
/**
* Get all keys in the store
* @returns Array of all keys
*/
keys() {
return Array.from(this.data.keys());
}
/**
* Get all values in the store
* @returns Array of all values
*/
values() {
return Array.from(this.data.values());
}
/**
* Iterate over all entries
* @param callback - Function to call for each entry
*/
forEach(callback) {
this.data.forEach(callback);
}
/**
* Filter items based on a predicate
* @param predicate - Function to test each item
* @returns Array of items that match the predicate
*/
filter(predicate) {
return this.values().filter(predicate);
}
/**
* Find the first item matching a predicate
* @param predicate - Function to test each item
* @returns The first matching item or undefined
*/
find(predicate) {
return this.values().find(predicate);
}
/**
* Update an existing item
* @param id - The item's unique identifier
* @param updater - Function to update the item
* @returns True if the item was updated
*/
update(id, updater) {
const item = this.get(id);
if (item) {
this.add(id, updater(item));
return true;
}
return false;
}
};
__name(_BaseStore, "BaseStore");
var BaseStore = _BaseStore;
// src/state/stores/thought-store.ts
var _ThoughtStore = class _ThoughtStore extends BaseStore {
constructor() {
super("ThoughtStore");
/** Map of branch IDs to their thoughts */
__publicField(this, "branches");
/** Map of thought numbers to their revision history */
__publicField(this, "revisions");
this.branches = /* @__PURE__ */ new Map();
this.revisions = /* @__PURE__ */ new Map();
}
/**
* Add a new thought to the store
* @param id - Unique identifier for the thought
* @param thought - The thought data to store
*/
add(id, thought) {
this.data.set(id, thought);
if (thought.branchId) {
const branchThoughts = this.branches.get(thought.branchId) || [];
branchThoughts.push(thought);
this.branches.set(thought.branchId, branchThoughts);
}
if (thought.isRevision && thought.revisesThought !== void 0) {
const revisionHistory = this.revisions.get(thought.revisesThought) || [];
revisionHistory.push(thought);
this.revisions.set(thought.revisesThought, revisionHistory);
}
}
/**
* Get all thoughts in chronological order
* @returns Array of all thoughts
*/
getAll() {
return Array.from(this.data.values()).sort((a, b) => a.thoughtNumber - b.thoughtNumber);
}
/**
* Clear all thoughts and associated data
*/
clear() {
this.data.clear();
this.branches.clear();
this.revisions.clear();
}
/**
* Get thoughts for a specific branch
* @param branchId - The branch identifier
* @returns Array of thoughts in the branch
*/
getBranch(branchId) {
return this.branches.get(branchId) || [];
}
/**
* Get all branches
* @returns Map of branch IDs to their thoughts
*/
getAllBranches() {
return new Map(this.branches);
}
/**
* Get revision history for a thought
* @param thoughtNumber - The original thought number
* @returns Array of revisions for the thought
*/
getRevisions(thoughtNumber) {
return this.revisions.get(thoughtNumber) || [];
}
/**
* Get the latest thought (highest thought number)
* @returns The most recent thought or undefined
*/
getLatest() {
const thoughts = this.getAll();
return thoughts[thoughts.length - 1];
}
/**
* Get thoughts in a specific range
* @param start - Starting thought number (inclusive)
* @param end - Ending thought number (inclusive)
* @returns Array of thoughts in the range
*/
getRange(start, end) {
return this.getAll().filter(
(thought) => thought.thoughtNumber >= start && thought.thoughtNumber <= end
);
}
/**
* Get thoughts that need continuation
* @returns Array of thoughts where nextThoughtNeeded is true
*/
getPendingThoughts() {
return this.filter((thought) => thought.nextThoughtNeeded);
}
/**
* Count thoughts by type
* @returns Object with counts for regular, revision, and branched thoughts
*/
getStatistics() {
const thoughts = this.getAll();
return {
total: thoughts.length,
regular: thoughts.filter((t) => !t.isRevision && !t.branchId).length,
revisions: thoughts.filter((t) => t.isRevision).length,
branched: thoughts.filter((t) => t.branchId).length,
branches: this.branches.size
};
}
/**
* Export store data including branch and revision metadata
*/
export() {
return {
thoughts: super.export(),
branches: Object.fromEntries(this.branches),
revisions: Object.fromEntries(Array.from(this.revisions).map(([k, v]) => [k.toString(), v]))
};
}
/**
* Import store data including branch and revision metadata
*/
import(data) {
if (data.thoughts) {
super.import(data.thoughts);
}
this.branches.clear();
this.revisions.clear();
this.data.forEach((thought) => {
if (thought.branchId) {
const branchThoughts = this.branches.get(thought.branchId) || [];
branchThoughts.push(thought);
this.branches.set(thought.branchId, branchThoughts);
}
if (thought.isRevision && thought.revisesThought !== void 0) {
const revisionHistory = this.revisions.get(thought.revisesThought) || [];
revisionHistory.push(thought);
this.revisions.set(thought.revisesThought, revisionHistory);
}
});
}
};
__name(_ThoughtStore, "ThoughtStore");
var ThoughtStore = _ThoughtStore;
// src/state/stores/mental-model-store.ts
var _MentalModelStore = class _MentalModelStore extends BaseStore {
constructor() {
super("MentalModelStore");
/** Map of model names to their applications */
__publicField(this, "modelApplications");
this.modelApplications = /* @__PURE__ */ new Map();
}
/**
* Add a new mental model application
* @param id - Unique identifier
* @param model - The mental model data
*/
add(id, model) {
this.data.set(id, model);
const applications = this.modelApplications.get(model.modelName) || [];
applications.push(model);
this.modelApplications.set(model.modelName, applications);
}
/**
* Get all mental model applications
* @returns Array of all applications
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.modelApplications.clear();
}
/**
* Get applications of a specific model
* @param modelName - The name of the mental model
* @returns Array of applications for that model
*/
getByModel(modelName) {
return this.modelApplications.get(modelName) || [];
}
/**
* Get all unique problems analyzed
* @returns Array of unique problem statements
*/
getUniqueProblems() {
const problems = /* @__PURE__ */ new Set();
this.data.forEach((model) => problems.add(model.problem));
return Array.from(problems);
}
/**
* Get statistics about model usage
* @returns Object with comprehensive statistics
*/
getStatistics() {
const models = this.getAll();
const modelUsage = {};
this.modelApplications.forEach((applications, modelName) => {
modelUsage[modelName] = applications.length;
});
return {
count: models.length,
totalApplications: models.length,
uniqueModels: this.modelApplications.size,
uniqueProblems: this.getUniqueProblems().length,
modelUsage,
mostUsed: this.getMostUsedModel()
};
}
/**
* Find models applied to similar problems
* @param problem - The problem to search for
* @returns Array of models applied to similar problems
*/
findSimilarApplications(problem) {
const problemLower = problem.toLowerCase();
return this.filter(
(model) => model.problem.toLowerCase().includes(problemLower) || problemLower.includes(model.problem.toLowerCase())
);
}
/**
* Get the most frequently used model
* @returns The model name and count, or undefined
*/
getMostUsedModel() {
let maxCount = 0;
let mostUsed;
this.modelApplications.forEach((applications, modelName) => {
if (applications.length > maxCount) {
maxCount = applications.length;
mostUsed = modelName;
}
});
return mostUsed ? { modelName: mostUsed, count: maxCount } : void 0;
}
};
__name(_MentalModelStore, "MentalModelStore");
var MentalModelStore = _MentalModelStore;
// src/state/stores/debugging-store.ts
var _DebuggingStore = class _DebuggingStore extends BaseStore {
constructor() {
super("DebuggingStore");
/** Map of approach names to their sessions */
__publicField(this, "approachSessions");
/** Map of issue keywords to related sessions */
__publicField(this, "issueIndex");
this.approachSessions = /* @__PURE__ */ new Map();
this.issueIndex = /* @__PURE__ */ new Map();
}
/**
* Add a new debugging session
* @param id - Unique identifier
* @param session - The debugging session data
*/
add(id, session) {
this.data.set(id, session);
const sessions = this.approachSessions.get(session.approachName) || [];
sessions.push(session);
this.approachSessions.set(session.approachName, sessions);
this.indexIssue(id, session.issue);
}
/**
* Index issue keywords for search
* @param sessionId - Session identifier
* @param issue - Issue description
*/
indexIssue(sessionId, issue) {
const keywords = issue.toLowerCase().split(/\s+/).filter((word) => word.length > 3);
keywords.forEach((keyword) => {
const sessions = this.issueIndex.get(keyword) || /* @__PURE__ */ new Set();
sessions.add(sessionId);
this.issueIndex.set(keyword, sessions);
});
}
/**
* Get all debugging sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.approachSessions.clear();
this.issueIndex.clear();
}
/**
* Get sessions by approach
* @param approachName - The debugging approach name
* @returns Array of sessions using that approach
*/
getByApproach(approachName) {
return this.approachSessions.get(approachName) || [];
}
/**
* Search sessions by issue keywords
* @param keywords - Keywords to search for
* @returns Array of matching sessions
*/
searchByIssue(keywords) {
const searchTerms = keywords.toLowerCase().split(/\s+/);
const matchingIds = /* @__PURE__ */ new Set();
searchTerms.forEach((term) => {
const sessions = this.issueIndex.get(term);
if (sessions) {
sessions.forEach((id) => matchingIds.add(id));
}
});
return Array.from(matchingIds).map((id) => this.get(id)).filter((session) => session !== void 0);
}
/**
* Get successfully resolved sessions
* @returns Array of sessions with resolutions
*/
getResolvedSessions() {
return this.filter((session) => session.resolution.trim().length > 0);
}
/**
* Get statistics about debugging approaches
* @returns Statistics object
*/
getStatistics() {
const resolved = this.getResolvedSessions();
const stats = {};
this.approachSessions.forEach((sessions, approach) => {
stats[approach] = sessions.length;
});
return {
totalSessions: this.size(),
resolvedSessions: resolved.length,
approachUsage: stats,
successRate: this.size() > 0 ? resolved.length / this.size() : 0
};
}
/**
* Get the most effective approach based on resolution rate
* @returns Approach with highest success rate
*/
getMostEffectiveApproach() {
let bestApproach;
let bestRate = 0;
this.approachSessions.forEach((sessions, approach) => {
const resolved = sessions.filter((s) => s.resolution && s.resolution.trim().length > 0);
const rate = sessions.length > 0 ? resolved.length / sessions.length : 0;
if (rate > bestRate) {
bestRate = rate;
bestApproach = approach;
}
});
return bestApproach ? { approach: bestApproach, successRate: bestRate } : void 0;
}
};
__name(_DebuggingStore, "DebuggingStore");
var DebuggingStore = _DebuggingStore;
// src/state/stores/collaborative-store.ts
var _CollaborativeStore = class _CollaborativeStore extends BaseStore {
constructor() {
super("CollaborativeStore");
/** Map of topics to their sessions */
__publicField(this, "topicSessions");
/** Map of persona IDs to their participation sessions */
__publicField(this, "personaParticipation");
this.topicSessions = /* @__PURE__ */ new Map();
this.personaParticipation = /* @__PURE__ */ new Map();
}
/**
* Add a new collaborative session
* @param id - Unique identifier
* @param session - The collaborative session data
*/
add(id, session) {
this.data.set(id, session);
const sessions = this.topicSessions.get(session.topic) || [];
sessions.push(session);
this.topicSessions.set(session.topic, sessions);
session.personas.forEach((persona) => {
const participation = this.personaParticipation.get(persona.id) || /* @__PURE__ */ new Set();
participation.add(id);
this.personaParticipation.set(persona.id, participation);
});
}
/**
* Get all collaborative sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.topicSessions.clear();
this.personaParticipation.clear();
}
/**
* Get sessions by topic
* @param topic - The topic to search for
* @returns Array of sessions on that topic
*/
getByTopic(topic) {
const exact = this.topicSessions.get(topic) || [];
const partial = this.filter(
(session) => session.topic.toLowerCase().includes(topic.toLowerCase()) && !exact.includes(session)
);
return [...exact, ...partial];
}
/**
* Get sessions where a specific persona participated
* @param personaId - The persona identifier
* @returns Array of sessions with that persona
*/
getByPersona(personaId) {
const sessionIds = this.personaParticipation.get(personaId);
if (!sessionIds) return [];
return Array.from(sessionIds).map((id) => this.get(id)).filter((session) => session !== void 0);
}
/**
* Get active sessions (those needing next contribution)
* @returns Array of active sessions
*/
getActiveSessions() {
return this.filter((session) => session.nextContributionNeeded);
}
/**
* Get sessions with consensus
* @returns Array of sessions that reached consensus
*/
getConsensusSession() {
return this.filter(
(session) => !!(session.consensusPoints && session.consensusPoints.length > 0)
);
}
/**
* Get sessions with unresolved disagreements
* @returns Array of sessions with active disagreements
*/
getDisagreementSessions() {
return this.filter(
(session) => !!(session.disagreements && session.disagreements.some((d) => !d.resolution))
);
}
/**
* Get contribution statistics for a session
* @param sessionId - The session identifier
* @returns Statistics about contributions
*/
getContributionStats(sessionId) {
const session = this.get(sessionId);
if (!session) return void 0;
const stats = {
totalContributions: session.contributions.length,
byType: {},
byPersona: {},
averageConfidence: 0
};
let totalConfidence = 0;
session.contributions.forEach((contrib) => {
var _a;
stats.byType[contrib.type] = (stats.byType[contrib.type] || 0) + 1;
const personaName = ((_a = session.personas.find((p) => p.id === contrib.personaId)) == null ? void 0 : _a.name) || "Unknown";
stats.byPersona[personaName] = (stats.byPersona[personaName] || 0) + 1;
totalConfidence += contrib.confidence;
});
stats.averageConfidence = session.contributions.length > 0 ? totalConfidence / session.contributions.length : 0;
return stats;
}
/**
* Get overall statistics
* @returns Comprehensive statistics
*/
getStatistics() {
const sessions = this.getAll();
return {
totalSessions: sessions.length,
activeSessions: this.getActiveSessions().length,
sessionsWithConsensus: this.getConsensusSession().length,
sessionsWithDisagreements: this.getDisagreementSessions().length,
averageContributions: sessions.length > 0 ? sessions.reduce((sum, s) => sum + s.contributions.length, 0) / sessions.length : 0,
averagePersonas: sessions.length > 0 ? sessions.reduce((sum, s) => sum + s.personas.length, 0) / sessions.length : 0,
stageDistribution: this.getStageDistribution()
};
}
/**
* Get distribution of sessions by stage
* @returns Count of sessions in each stage
*/
getStageDistribution() {
const distribution = {};
this.forEach((session) => {
distribution[session.stage] = (distribution[session.stage] || 0) + 1;
});
return distribution;
}
};
__name(_CollaborativeStore, "CollaborativeStore");
var CollaborativeStore = _CollaborativeStore;
// src/state/stores/decision-store.ts
var _DecisionStore = class _DecisionStore extends BaseStore {
constructor() {
super("DecisionStore");
/** Map of decision statements to their sessions */
__publicField(this, "decisionIndex");
/** Map of analysis types to their sessions */
__publicField(this, "analysisSessions");
this.decisionIndex = /* @__PURE__ */ new Map();
this.analysisSessions = /* @__PURE__ */ new Map();
}
/**
* Add a new decision session
* @param id - Unique identifier
* @param decision - The decision data
*/
add(id, decision) {
this.data.set(id, decision);
this.indexDecision(id, decision.decisionStatement);
const sessions = this.analysisSessions.get(decision.analysisType) || [];
sessions.push(decision);
this.analysisSessions.set(decision.analysisType, sessions);
}
/**
* Index decision keywords for search
* @param decisionId - Decision identifier
* @param statement - Decision statement
*/
indexDecision(decisionId, statement) {
const keywords = statement.toLowerCase().split(/\s+/).filter((word) => word.length > 3);
keywords.forEach((keyword) => {
const decisions = this.decisionIndex.get(keyword) || /* @__PURE__ */ new Set();
decisions.add(decisionId);
this.decisionIndex.set(keyword, decisions);
});
}
/**
* Get all decision sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.decisionIndex.clear();
this.analysisSessions.clear();
}
/**
* Search decisions by keywords
* @param keywords - Keywords to search for
* @returns Array of matching decisions
*/
searchDecisions(keywords) {
const searchTerms = keywords.toLowerCase().split(/\s+/);
const matchingIds = /* @__PURE__ */ new Set();
searchTerms.forEach((term) => {
const decisions = this.decisionIndex.get(term);
if (decisions) {
decisions.forEach((id) => matchingIds.add(id));
}
});
return Array.from(matchingIds).map((id) => this.get(id)).filter((decision) => decision !== void 0);
}
/**
* Get decisions by analysis type
* @param analysisType - The type of analysis
* @returns Array of decisions using that analysis
*/
getByAnalysisType(analysisType) {
return this.analysisSessions.get(analysisType) || [];
}
/**
* Get decisions by stage
* @param stage - The decision stage
* @returns Array of decisions in that stage
*/
getByStage(stage) {
return this.filter((decision) => decision.stage === stage);
}
/**
* Get completed decisions (with recommendations)
* @returns Array of completed decisions
*/
getCompletedDecisions() {
return this.filter(
(decision) => !!(decision.recommendation && decision.recommendation.trim().length > 0)
);
}
/**
* Get active decisions (needing next stage)
* @returns Array of active decisions
*/
getActiveDecisions() {
return this.filter((decision) => decision.nextStageNeeded);
}
/**
* Calculate decision quality score
* @param decisionId - The decision identifier
* @returns Quality score and breakdown
*/
getDecisionQuality(decisionId) {
var _a, _b, _c, _d, _e, _f, _g;
const decision = this.get(decisionId);
if (!decision) return void 0;
const quality = {
hasMultipleOptions: decision.options.length > 1,
hasCriteria: (((_a = decision.criteria) == null ? void 0 : _a.length) || 0) > 0,
hasEvaluations: (((_b = decision.criteriaEvaluations) == null ? void 0 : _b.length) || 0) > 0,
hasStakeholders: (((_c = decision.stakeholders) == null ? void 0 : _c.length) || 0) > 0,
hasConstraints: (((_d = decision.constraints) == null ? void 0 : _d.length) || 0) > 0,
hasOutcomes: (((_e = decision.possibleOutcomes) == null ? void 0 : _e.length) || 0) > 0,
hasInformationGaps: (((_f = decision.informationGaps) == null ? void 0 : _f.length) || 0) > 0,
hasSensitivityAnalysis: (((_g = decision.sensitivityInsights) == null ? void 0 : _g.length) || 0) > 0,
hasRecommendation: !!decision.recommendation
};
const score = Object.values(quality).filter((v) => v).length / Object.keys(quality).length;
return {
score,
breakdown: quality,
completeness: `${Math.round(score * 100)}%`
};
}
/**
* Get the best option based on scores
* @param decisionId - The decision identifier
* @returns The best option or undefined
*/
getBestOption(decisionId) {
const decision = this.get(decisionId);
if (!decision) return void 0;
if (decision.expectedValues) {
const expectedValues = decision.expectedValues;
const bestId = Object.entries(expectedValues).reduce(
(best, [id, value]) => value > (expectedValues[best] || -Infinity) ? id : best,
""
);
return decision.options.find((opt) => opt.id === bestId);
}
if (decision.multiCriteriaScores) {
const multiCriteriaScores = decision.multiCriteriaScores;
const bestId = Object.entries(multiCriteriaScores).reduce(
(best, [id, score]) => score > (multiCriteriaScores[best] || -Infinity) ? id : best,
""
);
return decision.options.find((opt) => opt.id === bestId);
}
return void 0;
}
/**
* Get overall statistics
* @returns Comprehensive statistics
*/
getStatistics() {
const decisions = this.getAll();
const completed = this.getCompletedDecisions();
return {
totalDecisions: decisions.length,
completedDecisions: completed.length,
activeDecisions: this.getActiveDecisions().length,
completionRate: decisions.length > 0 ? completed.length / decisions.length : 0,
averageOptions: decisions.length > 0 ? decisions.reduce((sum, d) => sum + d.options.length, 0) / decisions.length : 0,
averageCriteria: decisions.length > 0 ? decisions.reduce((sum, d) => {
var _a;
return sum + (((_a = d.criteria) == null ? void 0 : _a.length) || 0);
}, 0) / decisions.length : 0,
analysisTypeDistribution: this.getAnalysisTypeDistribution(),
stageDistribution: this.getStageDistribution()
};
}
/**
* Get distribution by analysis type
*/
getAnalysisTypeDistribution() {
const distribution = {};
this.analysisSessions.forEach((sessions, type) => {
distribution[type] = sessions.length;
});
return distribution;
}
/**
* Get distribution by stage
*/
getStageDistribution() {
const distribution = {};
this.forEach((decision) => {
distribution[decision.stage] = (distribution[decision.stage] || 0) + 1;
});
return distribution;
}
};
__name(_DecisionStore, "DecisionStore");
var DecisionStore = _DecisionStore;
// src/state/stores/metacognitive-store.ts
var _MetacognitiveStore = class _MetacognitiveStore extends BaseStore {
constructor() {
super("MetacognitiveStore");
/** Map of tasks to their monitoring sessions */
__publicField(this, "taskSessions");
/** Map of domains to knowledge assessments */
__publicField(this, "domainKnowledge");
this.taskSessions = /* @__PURE__ */ new Map();
this.domainKnowledge = /* @__PURE__ */ new Map();
}
/**
* Add a new metacognitive monitoring session
* @param id - Unique identifier
* @param session - The metacognitive data
*/
add(id, session) {
this.data.set(id, session);
const sessions = this.taskSessions.get(session.task) || [];
sessions.push(session);
this.taskSessions.set(session.task, sessions);
if (session.knowledgeAssessment) {
const assessments = this.domainKnowledge.get(session.knowledgeAssessment.domain) || [];
assessments.push(session.knowledgeAssessment);
this.domainKnowledge.set(session.knowledgeAssessment.domain, assessments);
}
}
/**
* Get all metacognitive sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.taskSessions.clear();
this.domainKnowledge.clear();
}
/**
* Get sessions by task
* @param task - The task being monitored
* @returns Array of monitoring sessions for that task
*/
getByTask(task) {
const taskLower = task.toLowerCase();
return this.filter((session) => session.task.toLowerCase().includes(taskLower));
}
/**
* Get sessions by stage
* @param stage - The monitoring stage
* @returns Array of sessions in that stage
*/
getByStage(stage) {
return this.filter((session) => session.stage === stage);
}
/**
* Get knowledge assessments for a domain
* @param domain - The knowledge domain
* @returns Array of assessments for that domain
*/
getKnowledgeByDomain(domain) {
return this.domainKnowledge.get(domain) || [];
}
/**
* Get all unique domains assessed
* @returns Array of domain names
*/
getAssessedDomains() {
return Array.from(this.domainKnowledge.keys());
}
/**
* Get sessions with low confidence
* @param threshold - Confidence threshold (default: 0.5)
* @returns Array of low-confidence sessions
*/
getLowConfidenceSessions(threshold = 0.5) {
return this.filter((session) => session.overallConfidence < threshold);
}
/**
* Get sessions with high uncertainty
* @param minAreas - Minimum number of uncertainty areas (default: 3)
* @returns Array of high-uncertainty sessions
*/
getHighUncertaintySessions(minAreas = 3) {
return this.filter((session) => session.uncertaintyAreas.length >= minAreas);
}
/**
* Get active sessions needing assessment
* @returns Array of active sessions
*/
getActiveSessions() {
return this.filter((session) => session.nextAssessmentNeeded);
}
/**
* Analyze confidence trends across iterations
* @param monitoringId - The monitoring session ID
* @returns Confidence trend data
*/
getConfidenceTrend(monitoringId) {
const sessions = this.filter((session) => session.monitoringId === monitoringId);
if (sessions.length === 0) return void 0;
return sessions.sort((a, b) => a.iteration - b.iteration).map((session) => ({
iteration: session.iteration,
confidence: session.overallConfidence
}));
}
/**
* Get claim assessment statistics
* @returns Statistics about claims
*/
getClaimStatistics() {
const allClaims = [];
this.forEach((session) => {
if (session.claims) {
allClaims.push(...session.claims);
}
});
const stats = {
totalClaims: allClaims.length,
byStatus: {},
averageConfidence: 0,
withAlternatives: 0
};
let totalConfidence = 0;
allClaims.forEach((claim) => {
stats.byStatus[claim.status] = (stats.byStatus[claim.status] || 0) + 1;
totalConfidence += claim.confidenceScore;
if (claim.alternativeInterpretations && claim.alternativeInterpretations.length > 0) {
stats.withAlternatives++;
}
});
stats.averageConfidence = allClaims.length > 0 ? totalConfidence / allClaims.length : 0;
return stats;
}
/**
* Get overall statistics
* @returns Comprehensive statistics
*/
getStatistics() {
const sessions = this.getAll();
return {
totalSessions: sessions.length,
activeSessions: this.getActiveSessions().length,
averageConfidence: sessions.length > 0 ? sessions.reduce((sum, s) => sum + s.overallConfidence, 0) / sessions.length : 0,
averageUncertaintyAreas: sessions.length > 0 ? sessions.reduce((sum, s) => sum + s.uncertaintyAreas.length, 0) / sessions.length : 0,
assessedDomains: this.getAssessedDomains().length,
stageDistribution: this.getStageDistribution(),
claimStats: this.getClaimStatistics()
};
}
/**
* Get distribution by stage
*/
getStageDistribution() {
const distribution = {};
this.forEach((session) => {
distribution[session.stage] = (distribution[session.stage] || 0) + 1;
});
return distribution;
}
};
__name(_MetacognitiveStore, "MetacognitiveStore");
var MetacognitiveStore = _MetacognitiveStore;
// src/state/stores/scientific-store.ts
var _ScientificStore = class _ScientificStore extends BaseStore {
constructor() {
super("ScientificStore");
/** Map of inquiry IDs to their sessions */
__publicField(this, "inquirySessions");
/** Map of hypothesis IDs to their data */
__publicField(this, "hypotheses");
/** Map of experiment IDs to their data */
__publicField(this, "experiments");
this.inquirySessions = /* @__PURE__ */ new Map();
this.hypotheses = /* @__PURE__ */ new Map();
this.experiments = /* @__PURE__ */ new Map();
}
/**
* Add a new scientific inquiry session
* @param id - Unique identifier
* @param inquiry - The scientific inquiry data
*/
add(id, inquiry) {
this.data.set(id, inquiry);
const sessions = this.inquirySessions.get(inquiry.inquiryId) || [];
sessions.push(inquiry);
this.inquirySessions.set(inquiry.inquiryId, sessions);
if (inquiry.hypothesis) {
this.hypotheses.set(inquiry.hypothesis.hypothesisId, inquiry.hypothesis);
}
if (inquiry.experiment) {
this.experiments.set(inquiry.experiment.experimentId, inquiry.experiment);
}
}
/**
* Get all scientific inquiry sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.inquirySessions.clear();
this.hypotheses.clear();
this.experiments.clear();
}
/**
* Get sessions by inquiry ID
* @param inquiryId - The inquiry identifier
* @returns Array of sessions for that inquiry
*/
getByInquiry(inquiryId) {
return this.inquirySessions.get(inquiryId) || [];
}
/**
* Get sessions by stage
* @param stage - The inquiry stage
* @returns Array of sessions in that stage
*/
getByStage(stage) {
return this.filter((inquiry) => inquiry.stage === stage);
}
/**
* Get hypothesis by ID
* @param hypothesisId - The hypothesis identifier
* @returns The hypothesis data or undefined
*/
getHypothesis(hypothesisId) {
return this.hypotheses.get(hypothesisId);
}
/**
* Get experiment by ID
* @param experimentId - The experiment identifier
* @returns The experiment data or undefined
*/
getExperiment(experimentId) {
return this.experiments.get(experimentId);
}
/**
* Get all hypotheses
* @returns Array of all hypotheses
*/
getAllHypotheses() {
return Array.from(this.hypotheses.values());
}
/**
* Get all experiments
* @returns Array of all experiments
*/
getAllExperiments() {
return Array.from(this.experiments.values());
}
/**
* Get hypotheses by status
* @param status - The hypothesis status
* @returns Array of hypotheses with that status
*/
getHypothesesByStatus(status) {
return this.getAllHypotheses().filter((h) => h.status === status);
}
/**
* Get experiments with matched outcomes
* @returns Array of experiments where predictions matched
*/
getSuccessfulExperiments() {
return this.getAllExperiments().filter((e) => e.outcomeMatched === true);
}
/**
* Get experiments with unexpected observations
* @returns Array of experiments with unexpected results
*/
getExperimentsWithSurprises() {
return this.getAllExperiments().filter(
(e) => e.unexpectedObservations && e.unexpectedObservations.length > 0
);
}
/**
* Get active inquiries needing next stage
* @returns Array of active inquiries
*/
getActiveInquiries() {
return this.filter((inquiry) => inquiry.nextStageNeeded);
}
/**
* Get completed inquiries (reached conclusion)
* @returns Array of completed inquiries
*/
getCompletedInquiries() {
return this.filter((inquiry) => !!(inquiry.conclusion && inquiry.conclusion.trim().length > 0));
}
/**
* Track the evolution of a hypothesis
* @param hypothesisId - The hypothesis identifier
* @returns Evolution history
*/
getHypothesisEvolution(hypothesisId) {
const evolution = [];
const hypothesis = this.hypotheses.get(hypothesisId);
if (!hypothesis) return evolution;
evolution.push(hypothesis);
this.getAllHypotheses().forEach((h) => {
if (h.refinementOf === hypothesisId) {
evolution.push(h);
}
});
return evolution.sort((a, b) => a.iteration - b.iteration);
}
/**
* Get hypothesis-experiment pairs
* @returns Array of paired hypotheses and experiments
*/
getHypothesisExperimentPairs() {
const pairs = [];
this.experiments.forEach((experiment) => {
const hypothesis = this.hypotheses.get(experiment.hypothesisId);
if (hypothesis) {
pairs.push({ hypothesis, experiment });
}
});
return pairs;
}
/**
* Get overall statistics
* @returns Comprehensive statistics
*/
getStatistics() {
const inquiries = this.getAll();
const hypotheses = this.getAllHypotheses();
const experiments = this.getAllExperiments();
return {
totalInquiries: inquiries.length,
activeInquiries: this.getActiveInquiries().length,
completedInquiries: this.getCompletedInquiries().length,
totalHypotheses: hypotheses.length,
supportedHypotheses: this.getHypothesesByStatus("supported").length,
refutedHypotheses: this.getHypothesesByStatus("refuted").length,
totalExperiments: experiments.length,
successfulExperiments: this.getSuccessfulExperiments().length,
experimentsWithSurprises: this.getExperimentsWithSurprises().length,
stageDistribution: this.getStageDistribution(),
hypothesisStatusDistribution: this.getHypothesisStatusDistribution(),
averageConfidence: hypotheses.length > 0 ? hypotheses.reduce((sum, h) => sum + h.confidence, 0) / hypotheses.length : 0
};
}
/**
* Get distribution by stage
*/
getStageDistribution() {
const distribution = {};
this.forEach((inquiry) => {
distribution[inquiry.stage] = (distribution[inquiry.stage] || 0) + 1;
});
return distribution;
}
/**
* Get hypothesis status distribution
*/
getHypothesisStatusDistribution() {
const distribution = {};
this.getAllHypotheses().forEach((hypothesis) => {
distribution[hypothesis.status] = (distribution[hypothesis.status] || 0) + 1;
});
return distribution;
}
};
__name(_ScientificStore, "ScientificStore");
var ScientificStore = _ScientificStore;
// src/state/stores/creative-store.ts
var _CreativeStore = class _CreativeStore extends BaseStore {
constructor() {
super("CreativeStore");
/** Map of prompts to their sessions */
__publicField(this, "promptSessions");
/** Map of techniques to sessions using them */
__publicField(this, "techniqueSessions");
this.promptSessions = /* @__PURE__ */ new Map();
this.techniqueSessions = /* @__PURE__ */ new Map();
}
/**
* Add a new creative thinking session
* @param id - Unique identifier
* @param session - The creative data
*/
add(id, session) {
this.data.set(id, session);
const promptKey = session.prompt.substring(0, 50);
const sessions = this.promptSessions.get(promptKey) || [];
sessions.push(session);
this.promptSessions.set(promptKey, sessions);
session.techniques.forEach((technique) => {
const sessionIds = this.techniqueSessions.get(technique) || /* @__PURE__ */ new Set();
sessionIds.add(id);
this.techniqueSessions.set(technique, sessionIds);
});
}
/**
* Get all creative sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.promptSessions.clear();
this.techniqueSessions.clear();
}
/**
* Get sessions by prompt similarity
* @param prompt - The prompt to search for
* @returns Array of sessions with similar prompts
*/
getSimilarPrompts(prompt) {
const promptLower = prompt.toLowerCase();
return this.filter(
(session) => session.prompt.toLowerCase().includes(promptLower) || promptLower.includes(session.prompt.toLowerCase())
);
}
/**
* Get sessions using a specific technique
* @param technique - The creative technique
* @returns Array of sessions using that technique
*/
getByTechnique(technique) {
const sessionIds = this.techniqueSessions.get(technique);
if (!sessionIds) return [];
return Array.from(sessionIds).map((id) => this.get(id)).filter((session) => session !== void 0);
}
/**
* Get all unique techniques used
* @returns Array of technique names
*/
getAllTechniques() {
return Array.from(this.techniqueSessions.keys());
}
/**
* Get active sessions needing more ideas
* @returns Array of active sessions
*/
getActiveSessions() {
return this.filter((session) => session.nextIdeaNeeded);
}
/**
* Get sessions with the most ideas
* @param limit - Number of top sessions to return
* @returns Array of most productive sessions
*/
getMostProductiveSessions(limit = 5) {
return this.getAll().sort((a, b) => b.ideas.length - a.ideas.length).slice(0, limit);
}
/**
* Get sessions with the most insights
* @param limit - Number of top sessions to return
* @returns Array of most insightful sessions
*/
getMostInsightfulSessions(limit = 5) {
return this.getAll().sort((a, b) => b.insights.length - a.insights.length).slice(0, limit);
}
/**
* Calculate creativity metrics for a session
* @param sessionId - The session identifier
* @returns Creativity metrics
*/
getCreativityMetrics(sessionId) {
const session = this.get(sessionId);
if (!session) return void 0;
const baseMetrics = {
ideaCount: session.ideas.length,
techniqueCount: session.techniques.length,
connectionCount: session.connections.length,
insightCount: session.insights.length,
ideaDiversity: this.calculateIdeaDiversity(session.ideas),
connectionDensity: session.ideas.length > 0 ? session.connections.length / session.ideas.length : 0,
insightRatio: session.ideas.length > 0 ? session.insights.length / session.ideas.length : 0
};
if (session.redTeamAnalysis) {
return {
...baseMetrics,
redTeamMetrics: {
threatCount: session.redTeamAnalysis.threats.length,
vulnerabilityCount: session.redTeamAnalysis.vulnerabilities.length,
failureModeCount: session.redTeamAnalysis.failureModes.length,
attackVectorCount: session.redTeamAnalysis.attackVectors.length,
mitigationCount: session.redTeamAnalysis.mitigationIdeas.length,
riskScenarioCount: session.redTeamAnalysis.riskScenarios.length,
overallConfidence: session.redTeamAnalysis.confidenceAssessment.overallConfidence,
analysisCompleteness: this.calculateRedTeamCompleteness(session.redTeamAnalysis)
}
};
}
return baseMetrics;
}
/**
* Calculate idea diversity (unique words ratio)
* @param ideas - Array of ideas
* @returns Diversity score
*/
calculateIdeaDiversity(ideas) {
if (ideas.length === 0) return 0;
const allWords = /* @__PURE__ */ new Set();
let totalWords = 0;
ideas.forEach((idea) => {
const words = idea.toLowerCase().split(/\s+/);
words.forEach((word) => {
allWords.add(word);
totalWords++;
});
});
return totalWords > 0 ? allWords.size / totalWords : 0;
}
/**
* Find cross-pollination opportunities
* @param sessionId - The session identifier
* @returns Sessions with overlapping techniques or themes
*/
findCrossPollination(sessionId) {
const session = this.get(sessionId);
if (!session) return [];
const related = /* @__PURE__ */ new Set();
session.techniques.forEach((technique) => {
const sessionIds = this.techniqueSessions.get(technique);
if (sessionIds) {
sessionIds.forEach((id) => {
if (id !== sessionId) related.add(id);
});
}
});
return Array.from(related).map((id) => this.get(id)).filter((s) => s !== void 0);
}
/**
* Get overall statistics
* @returns Comprehensive statistics
*/
getStatistics() {
const sessions = this.getAll();
return {
count: sessions.length,
totalSessions: sessions.length,
activeSessions: this.getActiveSessions().length,
totalIdeas: sessions.reduce((sum, s) => sum + s.ideas.length, 0),
totalInsights: sessions.reduce((sum, s) => sum + s.insights.length, 0),
totalConnections: sessions.reduce((sum, s) => sum + s.connections.length, 0),
averageIdeasPerSession: sessions.length > 0 ? sessions.reduce((sum, s) => sum + s.ideas.length, 0) / sessions.length : 0,
uniqueTechniques: this.getAllTechniques().length,
techniqueUsage: this.getTechniqueUsage(),
topTechniques: this.getTopTechniques(5)
};
}
/**
* Get technique usage counts
*/
getTechniqueUsage() {
const usage = {};
this.techniqueSessions.forEach((sessions, technique) => {
usage[technique] = sessions.size;
});
return usage;
}
/**
* Get most used techniques
* @param limit - Number of top techniques
* @returns Array of technique names and counts
*/
getTopTechniques(limit) {
const usage = this.getTechniqueUsage();
return Object.entries(usage).map(([technique, count]) => ({ technique, count })).sort((a, b) => b.count - a.count).slice(0, limit);
}
/**
* Calculate red team analysis completeness
* @param redTeamAnalysis - The red team analysis data
* @returns Completeness score (0-1)
*/
calculateRedTeamCompleteness(redTeamAnalysis) {
const components = [
redTeamAnalysis.threats.length > 0,
redTeamAnalysis.vulnerabilities.length > 0,
redTeamAnalysis.failureModes.length > 0,
redTeamAnalysis.attackVectors.length > 0,
redTeamAnalysis.mitigationIdeas.length > 0,
redTeamAnalysis.riskScenarios.length > 0
];
const completedComponents = components.filter(Boolean).length;
return completedComponents / components.length;
}
/**
* Get sessions with red team analysis
* @returns Array of sessions that include red team analysis
*/
getRedTeamSessions() {
return this.filter((session) => session.redTeamAnalysis !== void 0);
}
/**
* Get red team analysis statistics
* @returns Statistics about red team analysis usage
*/
getRedTeamStatistics() {
const redTeamSessions = this.getRedTeamSessions();
if (redTeamSessions.length === 0) {
return {
totalRedTeamSessions: 0,
averageThreats: 0,
averageVulnerabilities: 0,
averageFailureModes: 0,
averageAttackVectors: 0,
averageMitigations: 0,
averageRiskScenarios: 0,
averageConfidence: 0
};
}
return {
totalRedTeamSessions: redTeamSessions.length,
averageThreats: redTeamSessions.reduce((sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.threats.length) || 0);
}, 0) / redTeamSessions.length,
averageVulnerabilities: redTeamSessions.reduce(
(sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.vulnerabilities.length) || 0);
},
0
) / redTeamSessions.length,
averageFailureModes: redTeamSessions.reduce((sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.failureModes.length) || 0);
}, 0) / redTeamSessions.length,
averageAttackVectors: redTeamSessions.reduce(
(sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.attackVectors.length) || 0);
},
0
) / redTeamSessions.length,
averageMitigations: redTeamSessions.reduce(
(sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.mitigationIdeas.length) || 0);
},
0
) / redTeamSessions.length,
averageRiskScenarios: redTeamSessions.reduce(
(sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.riskScenarios.length) || 0);
},
0
) / redTeamSessions.length,
averageConfidence: redTeamSessions.reduce(
(sum, s) => {
var _a;
return sum + (((_a = s.redTeamAnalysis) == null ? void 0 : _a.confidenceAssessment.overallConfidence) || 0);
},
0
) / redTeamSessions.length
};
}
};
__name(_CreativeStore, "CreativeStore");
var CreativeStore = _CreativeStore;
// src/state/stores/systems-store.ts
var _SystemsStore = class _SystemsStore extends BaseStore {
constructor() {
super("SystemsStore");
/** Map of system names to their analysis sessions */
__publicField(this, "systemAnalyses");
/** Map of components to systems containing them */
__publicField(this, "componentIndex");
this.systemAnalyses = /* @__PURE__ */ new Map();
this.componentIndex = /* @__PURE__ */ new Map();
}
/**
* Add a new systems thinking session
* @param id - Unique identifier
* @param system - The systems data
*/
add(id, system) {
this.data.set(id, system);
const analyses = this.systemAnalyses.get(system.system) || [];
analyses.push(system);
this.systemAnalyses.set(system.system, analyses);
system.components.forEach((component) => {
const systems = this.componentIndex.get(component) || /* @__PURE__ */ new Set();
systems.add(id);
this.componentIndex.set(component, systems);
});
}
/**
* Get all systems thinking sessions
* @returns Array of all sessions
*/
getAll() {
return Array.from(this.data.values());
}
/**
* Clear all data
*/
clear() {
this.data.clear();
this.systemAnalyses.clear();
this.componentIndex.clear();
}
/**
* Get analyses for a specific system
* @param systemName - The system name
* @returns Array of analyses for that system
*/
getBySystem(systemName) {
const exact = this.systemAnalyses.get(systemName) || [];
const partial = this.filter(
(system) => system.system.toLowerCase().includes(systemName.