Spaces:
Paused
Paused
File size: 25,622 Bytes
529090e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 | /**
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* β PREFRONTAL CORTEX SERVICE β
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* β The system's executive function - strategic planning, goal management, β
* β decision making, and coordinating other cognitive modules β
* β β’ Goal Management: Define and track objectives β
* β β’ Strategic Planning: Break goals into actionable plans β
* β β’ Decision Making: Evaluate options with trade-off analysis β
* β β’ Executive Control: Coordinate actions across modules β
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*/
import { neo4jAdapter } from '../adapters/Neo4jAdapter.js';
import { v4 as uuidv4 } from 'uuid';
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Types
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type GoalStatus = 'DRAFT' | 'ACTIVE' | 'IN_PROGRESS' | 'BLOCKED' | 'COMPLETED' | 'ABANDONED';
export type GoalPriority = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
export type GoalTimeframe = 'IMMEDIATE' | 'SHORT_TERM' | 'MEDIUM_TERM' | 'LONG_TERM';
export interface Goal {
id: string;
title: string;
description: string;
status: GoalStatus;
priority: GoalPriority;
timeframe: GoalTimeframe;
parentGoalId?: string; // For sub-goals
successCriteria: string[];
progress: number; // 0-100
blockers: string[];
dependencies: string[]; // Other goal IDs
tags: string[];
createdAt: string;
updatedAt: string;
targetDate?: string;
completedAt?: string;
}
export interface Plan {
id: string;
goalId: string;
title: string;
steps: PlanStep[];
status: 'DRAFT' | 'APPROVED' | 'EXECUTING' | 'COMPLETED' | 'FAILED';
estimatedEffort: string; // e.g., "2 hours", "3 days"
risks: PlanRisk[];
createdAt: string;
approvedAt?: string;
approvedBy?: string;
}
export interface PlanStep {
id: string;
order: number;
description: string;
actionType?: string;
status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'SKIPPED' | 'FAILED';
dependencies: string[]; // Other step IDs
output?: string;
completedAt?: string;
}
export interface PlanRisk {
id: string;
description: string;
probability: 'LOW' | 'MEDIUM' | 'HIGH';
impact: 'LOW' | 'MEDIUM' | 'HIGH';
mitigation: string;
}
export interface Decision {
id: string;
question: string;
context: string;
options: DecisionOption[];
selectedOption?: string;
rationale?: string;
status: 'PENDING' | 'DECIDED' | 'IMPLEMENTED';
decidedAt?: string;
decidedBy?: string;
createdAt: string;
}
export interface DecisionOption {
id: string;
name: string;
description: string;
pros: string[];
cons: string[];
risks: string[];
score?: number; // Calculated score
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Prefrontal Cortex Service
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class PrefrontalCortexService {
private static instance: PrefrontalCortexService;
private goals: Map<string, Goal> = new Map();
private plans: Map<string, Plan> = new Map();
private decisions: Map<string, Decision> = new Map();
// Focus tracking
private currentFocus: string | null = null;
private focusHistory: { goalId: string; startedAt: string; endedAt?: string }[] = [];
private constructor() {
this.loadFromNeo4j();
}
public static getInstance(): PrefrontalCortexService {
if (!PrefrontalCortexService.instance) {
PrefrontalCortexService.instance = new PrefrontalCortexService();
}
return PrefrontalCortexService.instance;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Goal Management
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Create a new goal
*/
public async createGoal(params: {
title: string;
description: string;
priority?: GoalPriority;
timeframe?: GoalTimeframe;
parentGoalId?: string;
successCriteria?: string[];
targetDate?: string;
tags?: string[];
}): Promise<Goal> {
const goal: Goal = {
id: `goal-${uuidv4()}`,
title: params.title,
description: params.description,
status: 'DRAFT',
priority: params.priority || 'MEDIUM',
timeframe: params.timeframe || 'MEDIUM_TERM',
parentGoalId: params.parentGoalId,
successCriteria: params.successCriteria || [],
progress: 0,
blockers: [],
dependencies: [],
tags: params.tags || [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
targetDate: params.targetDate
};
this.goals.set(goal.id, goal);
await this.persistGoal(goal);
console.error(`[PrefrontalCortex] π― Created goal: ${goal.title}`);
return goal;
}
/**
* Activate a goal (move from DRAFT to ACTIVE)
*/
public async activateGoal(goalId: string): Promise<Goal | null> {
const goal = this.goals.get(goalId);
if (!goal) return null;
goal.status = 'ACTIVE';
goal.updatedAt = new Date().toISOString();
await this.persistGoal(goal);
return goal;
}
/**
* Update goal progress
*/
public async updateGoalProgress(goalId: string, progress: number, status?: GoalStatus): Promise<Goal | null> {
const goal = this.goals.get(goalId);
if (!goal) return null;
goal.progress = Math.min(100, Math.max(0, progress));
goal.updatedAt = new Date().toISOString();
if (status) {
goal.status = status;
} else if (progress >= 100) {
goal.status = 'COMPLETED';
goal.completedAt = new Date().toISOString();
} else if (progress > 0 && goal.status === 'ACTIVE') {
goal.status = 'IN_PROGRESS';
}
await this.persistGoal(goal);
return goal;
}
/**
* Add blocker to goal
*/
public async addBlocker(goalId: string, blocker: string): Promise<Goal | null> {
const goal = this.goals.get(goalId);
if (!goal) return null;
goal.blockers.push(blocker);
goal.status = 'BLOCKED';
goal.updatedAt = new Date().toISOString();
await this.persistGoal(goal);
console.error(`[PrefrontalCortex] π§ Goal blocked: ${goal.title} - ${blocker}`);
return goal;
}
/**
* Remove blocker from goal
*/
public async removeBlocker(goalId: string, blockerIndex: number): Promise<Goal | null> {
const goal = this.goals.get(goalId);
if (!goal) return null;
goal.blockers.splice(blockerIndex, 1);
if (goal.blockers.length === 0 && goal.status === 'BLOCKED') {
goal.status = goal.progress > 0 ? 'IN_PROGRESS' : 'ACTIVE';
}
goal.updatedAt = new Date().toISOString();
await this.persistGoal(goal);
return goal;
}
/**
* Get goals by status or priority
*/
public getGoals(filter?: {
status?: GoalStatus;
priority?: GoalPriority;
timeframe?: GoalTimeframe;
parentGoalId?: string;
}): Goal[] {
let results = Array.from(this.goals.values());
if (filter?.status) {
results = results.filter(g => g.status === filter.status);
}
if (filter?.priority) {
results = results.filter(g => g.priority === filter.priority);
}
if (filter?.timeframe) {
results = results.filter(g => g.timeframe === filter.timeframe);
}
if (filter?.parentGoalId !== undefined) {
results = results.filter(g => g.parentGoalId === filter.parentGoalId);
}
// Sort by priority
const priorityOrder = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 };
return results.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);
}
/**
* Get sub-goals for a goal
*/
public getSubGoals(parentGoalId: string): Goal[] {
return this.getGoals({ parentGoalId });
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Strategic Planning
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Create a plan for a goal
*/
public async createPlan(params: {
goalId: string;
title: string;
steps: Omit<PlanStep, 'id' | 'status' | 'completedAt'>[];
estimatedEffort: string;
risks?: Omit<PlanRisk, 'id'>[];
}): Promise<Plan> {
const plan: Plan = {
id: `plan-${uuidv4()}`,
goalId: params.goalId,
title: params.title,
steps: params.steps.map((s, i) => ({
...s,
id: `step-${uuidv4()}`,
order: i + 1,
status: 'PENDING' as const
})),
status: 'DRAFT',
estimatedEffort: params.estimatedEffort,
risks: (params.risks || []).map(r => ({ ...r, id: `risk-${uuidv4()}` })),
createdAt: new Date().toISOString()
};
this.plans.set(plan.id, plan);
await this.persistPlan(plan);
console.error(`[PrefrontalCortex] π Created plan: ${plan.title} (${plan.steps.length} steps)`);
return plan;
}
/**
* Approve a plan
*/
public async approvePlan(planId: string, approvedBy: string): Promise<Plan | null> {
const plan = this.plans.get(planId);
if (!plan) return null;
plan.status = 'APPROVED';
plan.approvedAt = new Date().toISOString();
plan.approvedBy = approvedBy;
await this.persistPlan(plan);
return plan;
}
/**
* Update plan step status
*/
public async updatePlanStep(planId: string, stepId: string, status: PlanStep['status'], output?: string): Promise<Plan | null> {
const plan = this.plans.get(planId);
if (!plan) return null;
const step = plan.steps.find(s => s.id === stepId);
if (!step) return null;
step.status = status;
step.output = output;
if (status === 'COMPLETED' || status === 'SKIPPED' || status === 'FAILED') {
step.completedAt = new Date().toISOString();
}
// Update plan status
const allComplete = plan.steps.every(s => s.status === 'COMPLETED' || s.status === 'SKIPPED');
const anyFailed = plan.steps.some(s => s.status === 'FAILED');
const anyInProgress = plan.steps.some(s => s.status === 'IN_PROGRESS');
if (allComplete) {
plan.status = 'COMPLETED';
} else if (anyFailed) {
plan.status = 'FAILED';
} else if (anyInProgress) {
plan.status = 'EXECUTING';
}
// Update goal progress
const goal = this.goals.get(plan.goalId);
if (goal) {
const completedSteps = plan.steps.filter(s => s.status === 'COMPLETED').length;
goal.progress = Math.round((completedSteps / plan.steps.length) * 100);
await this.persistGoal(goal);
}
await this.persistPlan(plan);
return plan;
}
/**
* Get next step to execute in a plan
*/
public getNextStep(planId: string): PlanStep | null {
const plan = this.plans.get(planId);
if (!plan || plan.status !== 'APPROVED' && plan.status !== 'EXECUTING') return null;
// Find first pending step whose dependencies are met
for (const step of plan.steps) {
if (step.status !== 'PENDING') continue;
const depsComplete = step.dependencies.every(depId => {
const depStep = plan.steps.find(s => s.id === depId);
return depStep && (depStep.status === 'COMPLETED' || depStep.status === 'SKIPPED');
});
if (depsComplete) {
return step;
}
}
return null;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Decision Making
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Create a decision to be made
*/
public async createDecision(params: {
question: string;
context: string;
options: Omit<DecisionOption, 'id' | 'score'>[];
}): Promise<Decision> {
const decision: Decision = {
id: `decision-${uuidv4()}`,
question: params.question,
context: params.context,
options: params.options.map(o => ({
...o,
id: `option-${uuidv4()}`,
score: this.scoreOption(o)
})),
status: 'PENDING',
createdAt: new Date().toISOString()
};
this.decisions.set(decision.id, decision);
await this.persistDecision(decision);
console.error(`[PrefrontalCortex] β Decision pending: ${decision.question}`);
return decision;
}
/**
* Score a decision option based on pros/cons/risks
*/
private scoreOption(option: Omit<DecisionOption, 'id' | 'score'>): number {
let score = 50; // Start neutral
// Pros add points
score += option.pros.length * 10;
// Cons subtract points
score -= option.cons.length * 8;
// Risks subtract based on severity (assumed from description length as proxy)
score -= option.risks.length * 5;
return Math.max(0, Math.min(100, score));
}
/**
* Make a decision
*/
public async makeDecision(decisionId: string, optionId: string, rationale: string, decidedBy: string): Promise<Decision | null> {
const decision = this.decisions.get(decisionId);
if (!decision) return null;
decision.selectedOption = optionId;
decision.rationale = rationale;
decision.status = 'DECIDED';
decision.decidedAt = new Date().toISOString();
decision.decidedBy = decidedBy;
await this.persistDecision(decision);
const option = decision.options.find(o => o.id === optionId);
console.error(`[PrefrontalCortex] β
Decision made: ${option?.name || optionId}`);
return decision;
}
/**
* Get pending decisions
*/
public getPendingDecisions(): Decision[] {
return Array.from(this.decisions.values()).filter(d => d.status === 'PENDING');
}
/**
* Get recommendation for a decision
*/
public getRecommendation(decisionId: string): { option: DecisionOption; rationale: string } | null {
const decision = this.decisions.get(decisionId);
if (!decision || decision.options.length === 0) return null;
// Sort by score
const sorted = [...decision.options].sort((a, b) => (b.score || 0) - (a.score || 0));
const best = sorted[0];
const rationale = `Recommended "${best.name}" based on: ${best.pros.length} pros vs ${best.cons.length} cons. Key advantages: ${best.pros.slice(0, 2).join(', ')}`;
return { option: best, rationale };
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Executive Control / Focus Management
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Set current focus to a goal
*/
public setFocus(goalId: string): void {
if (this.currentFocus) {
// End previous focus
const lastFocus = this.focusHistory[this.focusHistory.length - 1];
if (lastFocus && !lastFocus.endedAt) {
lastFocus.endedAt = new Date().toISOString();
}
}
this.currentFocus = goalId;
this.focusHistory.push({
goalId,
startedAt: new Date().toISOString()
});
const goal = this.goals.get(goalId);
console.error(`[PrefrontalCortex] π― Focus set: ${goal?.title || goalId}`);
}
/**
* Get current focus
*/
public getCurrentFocus(): Goal | null {
if (!this.currentFocus) return null;
return this.goals.get(this.currentFocus) || null;
}
/**
* Get executive summary
*/
public getExecutiveSummary(): {
currentFocus: Goal | null;
activeGoals: number;
blockedGoals: number;
pendingDecisions: number;
activePlans: number;
overallProgress: number;
} {
const goals = Array.from(this.goals.values());
const plans = Array.from(this.plans.values());
const activeGoals = goals.filter(g => g.status === 'ACTIVE' || g.status === 'IN_PROGRESS');
const totalProgress = activeGoals.reduce((sum, g) => sum + g.progress, 0);
return {
currentFocus: this.getCurrentFocus(),
activeGoals: activeGoals.length,
blockedGoals: goals.filter(g => g.status === 'BLOCKED').length,
pendingDecisions: this.getPendingDecisions().length,
activePlans: plans.filter(p => p.status === 'APPROVED' || p.status === 'EXECUTING').length,
overallProgress: activeGoals.length > 0 ? Math.round(totalProgress / activeGoals.length) : 0
};
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Persistence
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
private async persistGoal(goal: Goal): Promise<void> {
try {
await neo4jAdapter.executeQuery(`
MERGE (g:Goal {id: $id})
SET g.title = $title,
g.description = $description,
g.status = $status,
g.priority = $priority,
g.timeframe = $timeframe,
g.progress = $progress,
g.tags = $tags,
g.createdAt = $createdAt,
g.updatedAt = $updatedAt
`, {
id: goal.id,
title: goal.title,
description: goal.description,
status: goal.status,
priority: goal.priority,
timeframe: goal.timeframe,
progress: goal.progress,
tags: goal.tags,
createdAt: goal.createdAt,
updatedAt: goal.updatedAt
});
} catch (error) {
console.warn('[PrefrontalCortex] Failed to persist goal:', error);
}
}
private async persistPlan(plan: Plan): Promise<void> {
try {
await neo4jAdapter.executeQuery(`
MERGE (p:Plan {id: $id})
SET p.goalId = $goalId,
p.title = $title,
p.status = $status,
p.estimatedEffort = $estimatedEffort,
p.stepCount = $stepCount,
p.createdAt = $createdAt
`, {
id: plan.id,
goalId: plan.goalId,
title: plan.title,
status: plan.status,
estimatedEffort: plan.estimatedEffort,
stepCount: plan.steps.length,
createdAt: plan.createdAt
});
} catch (error) {
console.warn('[PrefrontalCortex] Failed to persist plan:', error);
}
}
private async persistDecision(decision: Decision): Promise<void> {
try {
await neo4jAdapter.executeQuery(`
MERGE (d:Decision {id: $id})
SET d.question = $question,
d.status = $status,
d.optionCount = $optionCount,
d.selectedOption = $selectedOption,
d.createdAt = $createdAt,
d.decidedAt = $decidedAt
`, {
id: decision.id,
question: decision.question,
status: decision.status,
optionCount: decision.options.length,
selectedOption: decision.selectedOption || '',
createdAt: decision.createdAt,
decidedAt: decision.decidedAt || ''
});
} catch (error) {
console.warn('[PrefrontalCortex] Failed to persist decision:', error);
}
}
private async loadFromNeo4j(): Promise<void> {
try {
const goalResults = await neo4jAdapter.executeQuery(`
MATCH (g:Goal)
WHERE g.status IN ['ACTIVE', 'IN_PROGRESS', 'BLOCKED']
RETURN g
ORDER BY g.priority
LIMIT 100
`);
for (const r of goalResults) {
const g = r.g.properties;
this.goals.set(g.id, {
id: g.id,
title: g.title,
description: g.description,
status: g.status,
priority: g.priority,
timeframe: g.timeframe,
progress: g.progress,
successCriteria: [],
blockers: [],
dependencies: [],
tags: g.tags || [],
createdAt: g.createdAt,
updatedAt: g.updatedAt
});
}
console.error(`[PrefrontalCortex] π Loaded ${goalResults.length} active goals`);
} catch (error) {
console.warn('[PrefrontalCortex] Failed to load from Neo4j:', error);
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Status
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
public getStatus(): {
totalGoals: number;
activePlans: number;
pendingDecisions: number;
currentFocus: string | null;
} {
return {
totalGoals: this.goals.size,
activePlans: Array.from(this.plans.values()).filter(p => p.status === 'EXECUTING').length,
pendingDecisions: this.getPendingDecisions().length,
currentFocus: this.currentFocus
};
}
}
export const prefrontalCortex = PrefrontalCortexService.getInstance();
|