diff --git a/README.md b/README.md index da0ed60c..3a074aed 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,16 @@ skillkit issue plan owner/repo#42 # Cross-repo plan skillkit issue list # List open issues ``` +### Session Intelligence + +```bash +skillkit timeline # Unified event stream +skillkit session handoff # Agent-to-agent context +skillkit lineage # Skill impact graph +skillkit session explain # Human-readable summary +skillkit activity # Skill activity log +``` + ### Advanced ```bash diff --git a/apps/skillkit/src/cli.ts b/apps/skillkit/src/cli.ts index 18e14772..8ba822b4 100644 --- a/apps/skillkit/src/cli.ts +++ b/apps/skillkit/src/cli.ts @@ -118,6 +118,9 @@ import { AgentsMdShowCommand, IssuePlanCommand, IssueListCommand, + TimelineCommand, + SessionHandoffCommand, + LineageCommand, } from '@skillkit/cli'; const __filename = fileURLToPath(import.meta.url); @@ -263,4 +266,8 @@ cli.register(AgentsMdShowCommand); cli.register(IssuePlanCommand); cli.register(IssueListCommand); +cli.register(TimelineCommand); +cli.register(SessionHandoffCommand); +cli.register(LineageCommand); + cli.runExit(process.argv.slice(2)); diff --git a/docs/fumadocs/content/docs/commands.mdx b/docs/fumadocs/content/docs/commands.mdx index beb05f2c..77e4d4c6 100644 --- a/docs/fumadocs/content/docs/commands.mdx +++ b/docs/fumadocs/content/docs/commands.mdx @@ -378,6 +378,66 @@ skillkit issue list --json # JSON output The planner extracts task lists (checkboxes) from the issue body, infers file mentions from backtick-quoted paths, and maps labels to tags (e.g., `bug` → `fix`, `enhancement` → `feature`). Generated plans work with `skillkit plan validate` and `skillkit plan execute`. +## Session Intelligence + +Track skill executions, generate handoff documents, and analyze skill impact. + +### Timeline + +View a unified chronological event stream of all session activity. + +```bash +skillkit timeline # Last 50 events +skillkit timeline --type git_commit # Filter by event type +skillkit timeline --skill code-simplifier # Filter by skill +skillkit timeline --since 2026-02-10 # Date filter +skillkit timeline --limit 20 --json # JSON output +``` + +| Option | Short | Purpose | +|--------|-------|---------| +| `--type` | `-t` | Filter: skill_start, skill_complete, task_progress, git_commit, observation, decision, snapshot | +| `--skill` | `-s` | Filter events by skill name | +| `--since` | — | Show events since date (YYYY-MM-DD) | +| `--limit` | `-l` | Max events (default: 50) | +| `--json` | `-j` | JSON output | + +### Session Handoff + +Generate a structured context document for agent switching. + +```bash +skillkit session handoff # Print markdown to stdout +skillkit session handoff --to cursor # Target agent recommendations +skillkit session handoff --out handoff.md # Save to file +skillkit session handoff --json # JSON output +``` + +| Option | Short | Purpose | +|--------|-------|---------| +| `--to` | — | Target agent for recommendations | +| `--out` | `-o` | Save to file path | +| `--json` | `-j` | JSON output | + +### Lineage + +Show which skills produced which code changes with aggregate impact stats. + +```bash +skillkit lineage # Full overview +skillkit lineage --skill code-simplifier # Single skill +skillkit lineage --file src/index.ts # Single file +skillkit lineage --since 2026-02-01 --json # Date filter + JSON +``` + +| Option | Short | Purpose | +|--------|-------|---------| +| `--skill` | `-s` | Filter by skill name | +| `--file` | `-f` | Filter by file path | +| `--since` | — | Show lineage since date | +| `--limit` | `-l` | Max entries | +| `--json` | `-j` | JSON output | + ## Utility Commands ```bash diff --git a/docs/fumadocs/content/docs/contributing.mdx b/docs/fumadocs/content/docs/contributing.mdx index 9d66a436..97479239 100644 --- a/docs/fumadocs/content/docs/contributing.mdx +++ b/docs/fumadocs/content/docs/contributing.mdx @@ -29,7 +29,7 @@ skillkit/ │ ├── core/ # Business logic │ ├── cli/ # CLI │ ├── tui/ # Terminal UI -│ └── agents/ # 32 adapters +│ └── agents/ # 44 adapters ├── marketplace/ # Skills data │ ├── skills.json │ └── sources.json diff --git a/docs/fumadocs/content/docs/index.mdx b/docs/fumadocs/content/docs/index.mdx index d0e1c5ae..818781e6 100644 --- a/docs/fumadocs/content/docs/index.mdx +++ b/docs/fumadocs/content/docs/index.mdx @@ -124,6 +124,16 @@ skillkit memory search "auth patterns" skillkit memory export auth-patterns ``` +### Session Intelligence + +Track skill executions, generate handoff documents for agent switching, and view skill impact lineage: + +```bash +skillkit timeline # Unified event stream +skillkit session handoff # Agent-to-agent context +skillkit lineage # Skill impact graph +``` + ### Primer Auto-generate CLAUDE.md, .cursorrules, and agent instructions by analyzing your codebase: @@ -163,4 +173,4 @@ Team members run `skillkit manifest install` and they're in sync. - [MCP Server](/docs/mcp-server) — Agent-native discovery - [Python Client](/docs/python-client) — Python SDK -**Current version:** v1.12.0 | [npm](https://www.npmjs.com/package/skillkit) | [GitHub](https://github.com/rohitg00/skillkit) | Apache-2.0 +**Current version:** v1.18.0 | [npm](https://www.npmjs.com/package/skillkit) | [GitHub](https://github.com/rohitg00/skillkit) | Apache-2.0 diff --git a/docs/fumadocs/content/docs/primer.mdx b/docs/fumadocs/content/docs/primer.mdx index 757d4239..285d108f 100644 --- a/docs/fumadocs/content/docs/primer.mdx +++ b/docs/fumadocs/content/docs/primer.mdx @@ -5,7 +5,7 @@ description: Auto-generate AI agent instructions from your codebase # Primer -Primer analyzes your codebase and automatically generates optimized instructions for all 32 AI agents. No more manual configuration—let SkillKit detect your tech stack, coding patterns, and project structure. +Primer analyzes your codebase and automatically generates optimized instructions for all 44 AI agents. No more manual configuration—let SkillKit detect your tech stack, coding patterns, and project structure. ## Quick Start @@ -65,7 +65,7 @@ Primer creates agent-specific instructions for: └── copilot-instructions.md ``` -### All 32 Agents +### All 44 Agents Each agent gets optimized instructions in their native format. ## Example Output @@ -86,7 +86,7 @@ Detected: - Claude Code (.claude/CLAUDE.md) - Cursor (.cursor/.cursorrules) - Codex (.codex/instructions.md) - + 29 more agents + + 41 more agents 💡 Tip: Run `skillkit sync` to apply changes ``` diff --git a/docs/fumadocs/content/docs/translation.mdx b/docs/fumadocs/content/docs/translation.mdx index ef77c2c0..ae434036 100644 --- a/docs/fumadocs/content/docs/translation.mdx +++ b/docs/fumadocs/content/docs/translation.mdx @@ -5,7 +5,7 @@ description: Convert skills between AI agent formats # Translation -SkillKit automatically converts between all 32 agent formats using an adapter pattern. +SkillKit automatically converts between all 44 agent formats using an adapter pattern. ## Basic Translation diff --git a/docs/fumadocs/src/app/(home)/page.tsx b/docs/fumadocs/src/app/(home)/page.tsx index de762f0f..2ba7c36a 100644 --- a/docs/fumadocs/src/app/(home)/page.tsx +++ b/docs/fumadocs/src/app/(home)/page.tsx @@ -18,7 +18,7 @@ export default function HomePage() {

One CLI to install, sync, and manage skills across Claude Code, Cursor, - Windsurf, Copilot, and 28 more agents. 15,000+ skills ready to use. + Windsurf, Copilot, and 40 more agents. 15,000+ skills ready to use.

@@ -39,8 +39,8 @@ export default function HomePage() { {/* Features Grid */}
-

32 Agents

-

Claude, Cursor, Codex, Windsurf, Copilot, and 27 more supported out of the box.

+

44 Agents

+

Claude, Cursor, Codex, Windsurf, Copilot, and 39 more supported out of the box.

15,000+ Skills

diff --git a/docs/fumadocs/src/components/Documentation.tsx b/docs/fumadocs/src/components/Documentation.tsx index ada4a12c..9216c851 100644 --- a/docs/fumadocs/src/components/Documentation.tsx +++ b/docs/fumadocs/src/components/Documentation.tsx @@ -44,12 +44,12 @@ const sections: DocSection[] = [ content: (

- SkillKit is a universal command-line interface (CLI) and programmatic toolkit for managing AI agent skills across 32 AI coding platforms. It solves the fragmentation problem where each AI agent uses different skill formats and directory structures. + SkillKit is a universal command-line interface (CLI) and programmatic toolkit for managing AI agent skills across 44 AI coding platforms. It solves the fragmentation problem where each AI agent uses different skill formats and directory structures.

Core Capabilities

  • Skill Discovery - Browse 15,000+ skills from marketplace with AI-powered recommendations
  • -
  • Cross-Agent Translation - Automatically convert skills between 32 agent-specific formats
  • +
  • Cross-Agent Translation - Automatically convert skills between 44 agent-specific formats
  • Team Collaboration - Share skills via .skills manifest files and publish to marketplace
@@ -102,7 +102,7 @@ skillkit install anthropics/skills`}
  • UI Tier - CLI commands, Terminal UI (OpenTUI-based), and documentation website
  • Core Logic Tier - @skillkit/core for business logic; @skillkit/agents for adapter implementations
  • -
  • Integration Tier - File systems, Git repositories, marketplace APIs, and 32 AI agents
  • +
  • Integration Tier - File systems, Git repositories, marketplace APIs, and 44 AI agents

Monorepo Structure

@@ -130,7 +130,7 @@ skillkit install anthropics/skills`} content: (

- SkillKit supports 32 AI coding agents with automatic format translation: + SkillKit supports 44 AI coding agents with automatic format translation:

['Trae', '.trae/skills/', 'SKILL.md'], ['Vercel', '.vercel/skills/', 'SKILL.md'], ['Zencoder', '.zencoder/skills/', 'SKILL.md'], + ['Devin', '.devin/skills/', 'SKILL.md'], + ['Aider', '.aider/skills/', 'SKILL.md'], + ['Sourcegraph Cody', '.cody/skills/', 'SKILL.md'], + ['Amazon Q', '.amazonq/skills/', 'SKILL.md'], + ['Augment Code', '.augment/skills/', 'SKILL.md'], + ['Replit Agent', '.replit/skills/', 'SKILL.md'], + ['Bolt', '.bolt/skills/', 'SKILL.md'], + ['Lovable', '.lovable/skills/', 'SKILL.md'], + ['Tabby', '.tabby/skills/', 'SKILL.md'], + ['Tabnine', '.tabnine/skills/', 'SKILL.md'], + ['CodeGPT', '.codegpt/skills/', 'SKILL.md'], + ['PlayCode Agent', '.playcode/skills/', 'SKILL.md'], ['Universal', 'skills/', 'SKILL.md'], ]} /> diff --git a/docs/fumadocs/src/components/Features.tsx b/docs/fumadocs/src/components/Features.tsx index fec4d618..50a48d43 100644 --- a/docs/fumadocs/src/components/Features.tsx +++ b/docs/fumadocs/src/components/Features.tsx @@ -9,7 +9,7 @@ interface Feature { const FEATURES: Feature[] = [ { title: 'Multi-Agent', - description: 'Deploy to 32 AI coding agents with one command.', + description: 'Deploy to 44 AI coding agents with one command.', icon: ( @@ -64,7 +64,7 @@ const FEATURES: Feature[] = [ ]; const COMPARISONS = [ - ['Agents', '1', '32'], + ['Agents', '1', '44'], ['Translation', 'Manual', 'Auto'], ['Sharing', 'Copy/paste', '.skills manifest'], ['Discovery', 'Forums', 'CLI + AI'], @@ -83,7 +83,7 @@ export function Features(): React.ReactElement {

-
32
+
44
Agents
diff --git a/docs/skillkit/components/AdvancedFeatures.tsx b/docs/skillkit/components/AdvancedFeatures.tsx index dee65e88..a8a0c2be 100644 --- a/docs/skillkit/components/AdvancedFeatures.tsx +++ b/docs/skillkit/components/AdvancedFeatures.tsx @@ -47,6 +47,24 @@ const ADVANCED_FEATURES: AdvancedFeature[] = [ { cmd: 'memory --global', desc: 'Share across all projects' }, ], }, + { + id: 'session', + title: 'Session Intelligence', + subtitle: 'Skill Lineage & Agent Handoffs', + description: 'Track which skills produced which code changes. Generate handoff documents when switching agents. View unified timelines of all session events — skill executions, git commits, observations, and decisions in one stream.', + highlight: 'Timeline, handoff, and lineage in one place', + icon: ( + + + + ), + commands: [ + { cmd: 'timeline', desc: 'Unified event stream' }, + { cmd: 'session handoff', desc: 'Agent-to-agent context' }, + { cmd: 'lineage', desc: 'Skill impact graph' }, + { cmd: 'lineage --skill code-simplifier', desc: 'Per-skill impact' }, + ], + }, { id: 'primer', title: 'Primer', diff --git a/docs/skillkit/components/Commands.tsx b/docs/skillkit/components/Commands.tsx index 842cc33a..2bf377f1 100644 --- a/docs/skillkit/components/Commands.tsx +++ b/docs/skillkit/components/Commands.tsx @@ -104,6 +104,17 @@ const COMMAND_GROUPS: CommandGroup[] = [ { cmd: 'issue list --label bug', desc: 'Filter by label' }, ], }, + { + name: 'Session', + commands: [ + { cmd: 'timeline', desc: 'Unified event stream' }, + { cmd: 'session handoff', desc: 'Agent handoff doc' }, + { cmd: 'lineage', desc: 'Skill impact graph' }, + { cmd: 'session explain', desc: 'Session summary' }, + { cmd: 'activity', desc: 'Skill activity log' }, + { cmd: 'session snapshot save', desc: 'Save state' }, + ], + }, { name: 'Advanced', commands: [ diff --git a/docs/skillkit/components/Documentation.tsx b/docs/skillkit/components/Documentation.tsx index 077b8244..69c93cad 100644 --- a/docs/skillkit/components/Documentation.tsx +++ b/docs/skillkit/components/Documentation.tsx @@ -213,6 +213,13 @@ skillkit primer --dry-run # Preview without writing files skillkit primer --json # Output analysis as JSON skillkit primer --output ./dir # Custom output directory`} +

Session Intelligence

+ {`skillkit timeline # Unified event stream +skillkit session handoff # Agent-to-agent context +skillkit lineage # Skill impact graph +skillkit session explain # Session summary +skillkit activity # Skill activity log`} +

Advanced

{`skillkit ui # Launch Terminal UI skillkit workflow # Manage workflows diff --git a/packages/cli/src/commands/handoff.ts b/packages/cli/src/commands/handoff.ts new file mode 100644 index 00000000..90e24bbb --- /dev/null +++ b/packages/cli/src/commands/handoff.ts @@ -0,0 +1,55 @@ +import { Command, Option } from 'clipanion'; +import { writeFileSync } from 'node:fs'; +import chalk from 'chalk'; +import { SessionHandoff } from '@skillkit/core'; + +export class SessionHandoffCommand extends Command { + static override paths = [['session', 'handoff']]; + + static override usage = Command.Usage({ + description: 'Generate agent-to-agent session handoff document', + examples: [ + ['Print handoff to stdout', '$0 session handoff'], + ['Target agent recommendations', '$0 session handoff --to cursor'], + ['Save to file', '$0 session handoff --out handoff.md'], + ['JSON output', '$0 session handoff --json'], + ], + }); + + to = Option.String('--to', { + description: 'Target agent for recommendations', + }); + + out = Option.String('--out,-o', { + description: 'Save handoff to file', + }); + + json = Option.Boolean('--json,-j', false, { + description: 'Output as JSON', + }); + + async execute(): Promise { + const projectPath = process.cwd(); + const handoff = new SessionHandoff(projectPath); + + const doc = handoff.generate({ + targetAgent: this.to, + }); + + const output = this.json ? handoff.toJson(doc) : handoff.toMarkdown(doc); + + if (this.out) { + try { + writeFileSync(this.out, output, 'utf-8'); + console.log(chalk.green(`Handoff saved to ${this.out}`)); + } catch (error) { + console.error(chalk.red(`Failed to write file: ${(error as Error).message}`)); + return 1; + } + } else { + console.log(output); + } + + return 0; + } +} diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 36b6688f..ed1b714c 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -127,6 +127,9 @@ export { ServeCommand } from './serve.js'; export { ScanCommand } from './scan.js'; export { IssuePlanCommand, IssueListCommand } from './issue.js'; export { DoctorCommand } from './doctor.js'; +export { TimelineCommand } from './timeline.js'; +export { SessionHandoffCommand } from './handoff.js'; +export { LineageCommand } from './lineage.js'; export { SaveCommand } from './save.js'; export { AgentsMdCommand, diff --git a/packages/cli/src/commands/lineage.ts b/packages/cli/src/commands/lineage.ts new file mode 100644 index 00000000..cdf191d7 --- /dev/null +++ b/packages/cli/src/commands/lineage.ts @@ -0,0 +1,66 @@ +import { Command, Option } from 'clipanion'; +import chalk from 'chalk'; +import { SkillLineage } from '@skillkit/core'; + +export class LineageCommand extends Command { + static override paths = [['lineage']]; + + static override usage = Command.Usage({ + description: 'Show skill impact lineage — which skills produced which changes', + examples: [ + ['Full overview', '$0 lineage'], + ['Single skill', '$0 lineage --skill code-simplifier'], + ['Single file', '$0 lineage --file src/index.ts'], + ['Date filter + JSON', '$0 lineage --since 2026-02-01 --json'], + ], + }); + + skill = Option.String('--skill,-s', { + description: 'Filter by skill name', + }); + + file = Option.String('--file,-f', { + description: 'Filter by file path', + }); + + since = Option.String('--since', { + description: 'Show lineage since date (YYYY-MM-DD)', + }); + + limit = Option.String('--limit,-l', { + description: 'Max entries to show', + }); + + json = Option.Boolean('--json,-j', false, { + description: 'Output as JSON', + }); + + async execute(): Promise { + const projectPath = process.cwd(); + const lineage = new SkillLineage(projectPath); + + const parsed = this.limit ? parseInt(this.limit, 10) : undefined; + const limit = parsed && Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; + + const data = lineage.build({ + skill: this.skill, + file: this.file, + since: this.since, + limit, + }); + + if (this.json) { + console.log(lineage.formatJson(data)); + return 0; + } + + if (data.skills.length === 0) { + console.log(chalk.yellow('No skill lineage found.')); + console.log(chalk.dim('Lineage is built from skill execution history and activity logs.')); + return 0; + } + + console.log(lineage.formatText(data)); + return 0; + } +} diff --git a/packages/cli/src/commands/timeline.ts b/packages/cli/src/commands/timeline.ts new file mode 100644 index 00000000..b7108e5d --- /dev/null +++ b/packages/cli/src/commands/timeline.ts @@ -0,0 +1,83 @@ +import { Command, Option } from 'clipanion'; +import chalk from 'chalk'; +import { SessionTimeline } from '@skillkit/core'; +import type { TimelineEventType } from '@skillkit/core'; + +export class TimelineCommand extends Command { + static override paths = [['timeline']]; + + static override usage = Command.Usage({ + description: 'Show unified session event timeline', + examples: [ + ['Show last 50 events', '$0 timeline'], + ['Filter by type', '$0 timeline --type git_commit'], + ['Filter by skill', '$0 timeline --skill code-simplifier'], + ['Date filter', '$0 timeline --since 2026-02-10'], + ['JSON output with limit', '$0 timeline --limit 20 --json'], + ], + }); + + type = Option.String('--type,-t', { + description: 'Filter by event type (skill_start, skill_complete, task_progress, git_commit, observation, decision, snapshot)', + }); + + skill = Option.String('--skill,-s', { + description: 'Filter by skill name', + }); + + since = Option.String('--since', { + description: 'Show events since date (YYYY-MM-DD)', + }); + + limit = Option.String('--limit,-l', { + description: 'Max events to show (default: 50)', + }); + + json = Option.Boolean('--json,-j', false, { + description: 'Output as JSON', + }); + + async execute(): Promise { + const projectPath = process.cwd(); + const timeline = new SessionTimeline(projectPath); + + const parsed = this.limit ? parseInt(this.limit, 10) : 50; + const limit = Number.isFinite(parsed) && parsed > 0 ? parsed : 50; + + const validTypes: TimelineEventType[] = [ + 'skill_start', 'skill_complete', 'task_progress', + 'git_commit', 'observation', 'decision', 'snapshot', + ]; + + let types: TimelineEventType[] | undefined; + if (this.type) { + if (!validTypes.includes(this.type as TimelineEventType)) { + console.log(chalk.red(`Invalid event type: ${this.type}`)); + console.log(chalk.dim(`Valid types: ${validTypes.join(', ')}`)); + return 1; + } + types = [this.type as TimelineEventType]; + } + + const data = timeline.build({ + since: this.since, + types, + limit, + skillFilter: this.skill, + }); + + if (this.json) { + console.log(timeline.formatJson(data)); + return 0; + } + + if (data.events.length === 0) { + console.log(chalk.yellow('No timeline events found.')); + console.log(chalk.dim('Events are recorded during skill execution, git commits, and observations.')); + return 0; + } + + console.log(timeline.formatText(data)); + return 0; + } +} diff --git a/packages/core/src/session/__tests__/handoff.test.ts b/packages/core/src/session/__tests__/handoff.test.ts new file mode 100644 index 00000000..f3f866e6 --- /dev/null +++ b/packages/core/src/session/__tests__/handoff.test.ts @@ -0,0 +1,361 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { stringify } from 'yaml'; +import { SessionHandoff } from '../handoff.js'; +import type { SessionState } from '../types.js'; + +const TEST_DIR = join(process.cwd(), '.test-handoff-' + process.pid); +const SKILLKIT_DIR = join(TEST_DIR, '.skillkit'); + +function writeSessionState(state: SessionState): void { + mkdirSync(SKILLKIT_DIR, { recursive: true }); + writeFileSync(join(SKILLKIT_DIR, 'session.yaml'), stringify(state)); +} + +function writeObservations(observations: Array>): void { + const dir = join(SKILLKIT_DIR, 'memory'); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'observations.yaml'), + stringify({ version: 1, sessionId: 'test', observations }) + ); +} + +beforeEach(() => { + mkdirSync(TEST_DIR, { recursive: true }); +}); + +afterEach(() => { + if (existsSync(TEST_DIR)) { + rmSync(TEST_DIR, { recursive: true, force: true }); + } +}); + +describe('SessionHandoff', () => { + it('should create handoff instance', () => { + const handoff = new SessionHandoff(TEST_DIR); + expect(handoff).toBeDefined(); + }); + + it('should generate empty handoff when no data', () => { + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.generatedAt).toBeTruthy(); + expect(doc.projectPath).toBe(TEST_DIR); + expect(doc.accomplished.tasks).toEqual([]); + expect(doc.pending.tasks).toEqual([]); + expect(doc.keyFiles).toEqual([]); + }); + + it('should collect accomplished tasks', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + currentExecution: { + skillName: 'test-skill', + skillSource: 'test', + currentStep: 2, + totalSteps: 3, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { + id: 't1', + name: 'Setup project', + type: 'auto', + status: 'completed', + startedAt: '2026-02-12T10:00:00.000Z', + completedAt: '2026-02-12T10:03:00.000Z', + commitSha: 'abc1234', + }, + { + id: 't2', + name: 'Write tests', + type: 'auto', + status: 'completed', + startedAt: '2026-02-12T10:03:00.000Z', + completedAt: '2026-02-12T10:08:00.000Z', + }, + { + id: 't3', + name: 'Update docs', + type: 'auto', + status: 'pending', + }, + ], + }, + }); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.accomplished.tasks.length).toBe(2); + expect(doc.accomplished.tasks[0].name).toBe('Setup project'); + expect(doc.accomplished.tasks[0].duration).toBe('3m'); + expect(doc.accomplished.tasks[0].commitSha).toBe('abc1234'); + }); + + it('should collect pending tasks', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + currentExecution: { + skillName: 'test-skill', + skillSource: 'test', + currentStep: 0, + totalSteps: 2, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { id: 't1', name: 'Pending task', type: 'auto', status: 'pending' }, + { id: 't2', name: 'In progress task', type: 'auto', status: 'in_progress', startedAt: '2026-02-12T10:00:00.000Z' }, + ], + }, + }); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.pending.tasks.length).toBe(2); + expect(doc.pending.tasks[0].name).toBe('Pending task'); + expect(doc.pending.tasks[1].name).toBe('In progress task'); + }); + + it('should collect key files from tasks and history', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'old-skill', + skillSource: 'test', + completedAt: '2026-02-11T15:00:00.000Z', + durationMs: 120000, + status: 'completed', + commits: [], + filesModified: ['src/old.ts', 'src/shared.ts'], + }, + ], + decisions: [], + currentExecution: { + skillName: 'test-skill', + skillSource: 'test', + currentStep: 1, + totalSteps: 1, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { + id: 't1', + name: 'Task 1', + type: 'auto', + status: 'completed', + filesModified: ['src/new.ts', 'src/shared.ts'], + }, + ], + }, + }); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.keyFiles.length).toBe(3); + const paths = doc.keyFiles.map((f) => f.path); + expect(paths).toContain('src/new.ts'); + expect(paths).toContain('src/old.ts'); + expect(paths).toContain('src/shared.ts'); + }); + + it('should collect observations by type', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + }); + + writeObservations([ + { + id: 'o1', + timestamp: '2026-02-12T10:00:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'error', + content: { action: 'build', context: 'src', error: 'missing import' }, + relevance: 90, + }, + { + id: 'o2', + timestamp: '2026-02-12T10:01:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'solution', + content: { action: 'fix', context: 'src', solution: 'added import' }, + relevance: 85, + }, + { + id: 'o3', + timestamp: '2026-02-12T10:02:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'pattern', + content: { action: 'review', context: 'always check imports' }, + relevance: 70, + }, + ]); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.observations.errors.length).toBe(1); + expect(doc.observations.errors[0].error).toBe('missing import'); + expect(doc.observations.solutions.length).toBe(1); + expect(doc.observations.solutions[0].solution).toBe('added import'); + expect(doc.observations.patterns.length).toBe(1); + }); + + it('should generate recommendations from pending tasks', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + currentExecution: { + skillName: 'test-skill', + skillSource: 'test', + currentStep: 0, + totalSteps: 1, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { id: 't1', name: 'Write documentation', type: 'auto', status: 'pending' }, + ], + }, + }); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.recommendations.length).toBeGreaterThan(0); + expect(doc.recommendations[0]).toContain('Write documentation'); + }); + + it('should format markdown output', () => { + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + const md = handoff.toMarkdown(doc); + + expect(md).toContain('# Session Handoff'); + expect(md).toContain('## Accomplished'); + expect(md).toContain('## Pending'); + }); + + it('should format JSON output', () => { + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + const json = handoff.toJson(doc); + + const parsed = JSON.parse(json); + expect(parsed.projectPath).toBe(TEST_DIR); + expect(parsed.accomplished).toBeDefined(); + expect(parsed.pending).toBeDefined(); + }); + + it('should include history in accomplished', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'completed-skill', + skillSource: 'test', + completedAt: '2026-02-12T09:00:00.000Z', + durationMs: 300000, + status: 'completed', + commits: ['def5678'], + filesModified: ['src/foo.ts'], + }, + ], + decisions: [], + }); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false }); + + expect(doc.accomplished.tasks.length).toBe(1); + expect(doc.accomplished.tasks[0].name).toBe('completed-skill'); + expect(doc.accomplished.tasks[0].duration).toBe('5m'); + }); + + it('should respect maxObservations option', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + }); + + writeObservations( + Array.from({ length: 10 }, (_, i) => ({ + id: `o${i}`, + timestamp: `2026-02-12T10:${String(i).padStart(2, '0')}:00.000Z`, + sessionId: 'test', + agent: 'claude-code', + type: 'error', + content: { action: `action-${i}`, context: 'src', error: `error-${i}` }, + relevance: 90 - i, + })) + ); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false, maxObservations: 3 }); + + const totalObs = + doc.observations.errors.length + + doc.observations.solutions.length + + doc.observations.patterns.length; + expect(totalObs).toBeLessThanOrEqual(3); + }); + + it('should skip observations when disabled', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + }); + + writeObservations([ + { + id: 'o1', + timestamp: '2026-02-12T10:00:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'error', + content: { action: 'build', context: 'src', error: 'fail' }, + relevance: 90, + }, + ]); + + const handoff = new SessionHandoff(TEST_DIR); + const doc = handoff.generate({ includeGit: false, includeObservations: false }); + + expect(doc.observations.errors).toEqual([]); + expect(doc.observations.solutions).toEqual([]); + expect(doc.observations.patterns).toEqual([]); + }); +}); diff --git a/packages/core/src/session/__tests__/lineage.test.ts b/packages/core/src/session/__tests__/lineage.test.ts new file mode 100644 index 00000000..5eadef56 --- /dev/null +++ b/packages/core/src/session/__tests__/lineage.test.ts @@ -0,0 +1,554 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { stringify } from 'yaml'; +import { SkillLineage } from '../lineage.js'; +import type { SessionState } from '../types.js'; + +const TEST_DIR = join(process.cwd(), '.test-lineage-' + process.pid); +const SKILLKIT_DIR = join(TEST_DIR, '.skillkit'); + +function writeSessionState(state: SessionState): void { + mkdirSync(SKILLKIT_DIR, { recursive: true }); + writeFileSync(join(SKILLKIT_DIR, 'session.yaml'), stringify(state)); +} + +function writeActivityLog(activities: Array>): void { + mkdirSync(SKILLKIT_DIR, { recursive: true }); + writeFileSync( + join(SKILLKIT_DIR, 'activity.yaml'), + stringify({ version: 1, activities }) + ); +} + +function writeObservations(observations: Array>): void { + const dir = join(SKILLKIT_DIR, 'memory'); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'observations.yaml'), + stringify({ version: 1, sessionId: 'test', observations }) + ); +} + +beforeEach(() => { + mkdirSync(TEST_DIR, { recursive: true }); +}); + +afterEach(() => { + if (existsSync(TEST_DIR)) { + rmSync(TEST_DIR, { recursive: true, force: true }); + } +}); + +describe('SkillLineage', () => { + it('should create lineage instance', () => { + const lineage = new SkillLineage(TEST_DIR); + expect(lineage).toBeDefined(); + }); + + it('should return empty lineage when no data', () => { + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + expect(data.skills).toEqual([]); + expect(data.files).toEqual([]); + expect(data.stats.totalSkillExecutions).toBe(0); + expect(data.stats.mostImpactfulSkill).toBeNull(); + }); + + it('should build lineage from execution history', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'code-simplifier', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 120000, + status: 'completed', + commits: ['abc1234', 'def5678'], + filesModified: ['src/index.ts', 'src/utils.ts'], + }, + { + skillName: 'code-simplifier', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['ghi9012'], + filesModified: ['src/index.ts'], + }, + { + skillName: 'pro-workflow', + skillSource: 'test', + completedAt: '2026-02-12T12:00:00.000Z', + durationMs: 180000, + status: 'completed', + commits: ['jkl3456'], + filesModified: ['src/index.ts', 'README.md'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + expect(data.skills.length).toBe(2); + + const cs = data.skills.find((s) => s.skillName === 'code-simplifier'); + expect(cs).toBeDefined(); + expect(cs!.executions).toBe(2); + expect(cs!.totalDurationMs).toBe(180000); + expect(cs!.commits.length).toBe(3); + expect(cs!.filesModified).toContain('src/index.ts'); + expect(cs!.filesModified).toContain('src/utils.ts'); + + const pw = data.skills.find((s) => s.skillName === 'pro-workflow'); + expect(pw).toBeDefined(); + expect(pw!.executions).toBe(1); + }); + + it('should build file lineage', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'skill-a', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['abc'], + filesModified: ['src/shared.ts'], + }, + { + skillName: 'skill-b', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['def'], + filesModified: ['src/shared.ts', 'src/only-b.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + const shared = data.files.find((f) => f.path === 'src/shared.ts'); + expect(shared).toBeDefined(); + expect(shared!.skills.length).toBe(2); + expect(shared!.skills).toContain('skill-a'); + expect(shared!.skills).toContain('skill-b'); + }); + + it('should compute stats', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'big-skill', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['a', 'b'], + filesModified: ['f1.ts', 'f2.ts', 'f3.ts'], + }, + { + skillName: 'small-skill', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 30000, + status: 'completed', + commits: ['c'], + filesModified: ['f1.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + expect(data.stats.totalSkillExecutions).toBe(2); + expect(data.stats.totalCommits).toBe(3); + expect(data.stats.totalFilesChanged).toBe(3); + expect(data.stats.mostImpactfulSkill).toBe('big-skill'); + }); + + it('should filter by skill name', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'target', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['a'], + filesModified: ['src/a.ts'], + }, + { + skillName: 'other', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['b'], + filesModified: ['src/b.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build({ skill: 'target' }); + + expect(data.skills.length).toBe(1); + expect(data.skills[0].skillName).toBe('target'); + expect(data.files.every((f) => f.skills.includes('target'))).toBe(true); + }); + + it('should filter by file path', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'skill-a', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['a'], + filesModified: ['src/target.ts', 'src/other.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build({ file: 'target.ts' }); + + expect(data.files.length).toBe(1); + expect(data.files[0].path).toBe('src/target.ts'); + }); + + it('should filter by since date', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'old', + skillSource: 'test', + completedAt: '2026-01-01T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['a'], + filesModified: ['old.ts'], + }, + { + skillName: 'recent', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['b'], + filesModified: ['recent.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build({ since: '2026-02-01' }); + + expect(data.skills.length).toBe(1); + expect(data.skills[0].skillName).toBe('recent'); + }); + + it('should include current execution in lineage', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + currentExecution: { + skillName: 'active-skill', + skillSource: 'test', + currentStep: 1, + totalSteps: 2, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { + id: 't1', + name: 'Task 1', + type: 'auto', + status: 'completed', + commitSha: 'abc', + filesModified: ['src/active.ts'], + }, + ], + }, + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + expect(data.skills.length).toBe(1); + expect(data.skills[0].skillName).toBe('active-skill'); + expect(data.skills[0].commits).toContain('abc'); + expect(data.skills[0].filesModified).toContain('src/active.ts'); + }); + + it('should merge activity log data', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'my-skill', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['abc'], + filesModified: ['src/a.ts'], + }, + ], + decisions: [], + }); + + writeActivityLog([ + { + commitSha: 'xyz', + committedAt: '2026-02-12T11:00:00.000Z', + activeSkills: ['my-skill'], + filesChanged: ['src/b.ts'], + message: 'extra commit', + }, + ]); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + const skill = data.skills.find((s) => s.skillName === 'my-skill'); + expect(skill).toBeDefined(); + expect(skill!.commits).toContain('xyz'); + }); + + it('should match observations by timestamp overlap', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'test-skill', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 3600000, + status: 'completed', + commits: [], + filesModified: [], + }, + ], + decisions: [], + }); + + writeObservations([ + { + id: 'obs1', + timestamp: '2026-02-12T10:30:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'error', + content: { action: 'build', context: 'src', files: ['src/buggy.ts'] }, + relevance: 80, + }, + ]); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + expect(data.stats.errorProneFiles).toContain('src/buggy.ts'); + }); + + it('should getSkillLineage for a specific skill', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'target-skill', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['abc'], + filesModified: ['src/foo.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const entry = lineage.getSkillLineage('target-skill'); + + expect(entry).toBeDefined(); + expect(entry!.skillName).toBe('target-skill'); + expect(entry!.executions).toBe(1); + }); + + it('should getFileLineage for a specific file', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'skill-a', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['abc'], + filesModified: ['src/target.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const fl = lineage.getFileLineage('src/target.ts'); + + expect(fl).toBeDefined(); + expect(fl!.path).toBe('src/target.ts'); + expect(fl!.skills).toContain('skill-a'); + }); + + it('should format text output', () => { + const lineage = new SkillLineage(TEST_DIR); + const data = { + projectPath: TEST_DIR, + skills: [ + { + skillName: 'test-skill', + executions: 3, + totalDurationMs: 180000, + commits: ['a', 'b'], + filesModified: ['f1.ts', 'f2.ts'], + observationIds: [], + firstSeen: '2026-02-12T08:00:00.000Z', + lastSeen: '2026-02-12T12:00:00.000Z', + }, + ], + files: [ + { path: 'f1.ts', skills: ['test-skill', 'other'], commitCount: 5, lastModified: '2026-02-12T12:00:00.000Z' }, + ], + stats: { + totalSkillExecutions: 3, + totalCommits: 2, + totalFilesChanged: 2, + mostImpactfulSkill: 'test-skill', + mostChangedFile: 'f1.ts', + errorProneFiles: ['f1.ts'], + }, + }; + + const text = lineage.formatText(data); + expect(text).toContain('Skill Lineage'); + expect(text).toContain('test-skill'); + expect(text).toContain('3 runs'); + expect(text).toContain('File Hotspots'); + expect(text).toContain('Stats'); + }); + + it('should format JSON output', () => { + const lineage = new SkillLineage(TEST_DIR); + const data = { + projectPath: TEST_DIR, + skills: [], + files: [], + stats: { + totalSkillExecutions: 0, + totalCommits: 0, + totalFilesChanged: 0, + mostImpactfulSkill: null, + mostChangedFile: null, + errorProneFiles: [], + }, + }; + + const json = lineage.formatJson(data); + const parsed = JSON.parse(json); + expect(parsed.projectPath).toBe(TEST_DIR); + }); + + it('should handle empty lineage in text format', () => { + const lineage = new SkillLineage(TEST_DIR); + const data = { + projectPath: TEST_DIR, + skills: [], + files: [], + stats: { + totalSkillExecutions: 0, + totalCommits: 0, + totalFilesChanged: 0, + mostImpactfulSkill: null, + mostChangedFile: null, + errorProneFiles: [], + }, + }; + + const text = lineage.formatText(data); + expect(text).toContain('No skill executions found'); + }); + + it('should deduplicate commits and files', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'dup-skill', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: ['abc', 'abc'], + filesModified: ['src/a.ts', 'src/a.ts', 'src/b.ts'], + }, + ], + decisions: [], + }); + + const lineage = new SkillLineage(TEST_DIR); + const data = lineage.build(); + + const skill = data.skills.find((s) => s.skillName === 'dup-skill'); + expect(skill!.commits.length).toBe(1); + expect(skill!.filesModified.length).toBe(2); + }); +}); diff --git a/packages/core/src/session/__tests__/timeline.test.ts b/packages/core/src/session/__tests__/timeline.test.ts new file mode 100644 index 00000000..600c4b2c --- /dev/null +++ b/packages/core/src/session/__tests__/timeline.test.ts @@ -0,0 +1,423 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { stringify } from 'yaml'; +import { SessionTimeline } from '../timeline.js'; +import type { SessionState, TimelineOptions } from '../types.js'; + +const TEST_DIR = join(process.cwd(), '.test-timeline-' + process.pid); +const SKILLKIT_DIR = join(TEST_DIR, '.skillkit'); + +function writeSessionState(state: SessionState): void { + mkdirSync(SKILLKIT_DIR, { recursive: true }); + writeFileSync(join(SKILLKIT_DIR, 'session.yaml'), stringify(state)); +} + +function writeObservations(observations: Array>): void { + const dir = join(SKILLKIT_DIR, 'memory'); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'observations.yaml'), + stringify({ version: 1, sessionId: 'test', observations }) + ); +} + +function writeSnapshots(snapshots: Array>): void { + const dir = join(SKILLKIT_DIR, 'snapshots'); + mkdirSync(dir, { recursive: true }); + for (const snap of snapshots) { + writeFileSync(join(dir, `${snap.name}.yaml`), stringify(snap)); + } +} + +beforeEach(() => { + mkdirSync(TEST_DIR, { recursive: true }); +}); + +afterEach(() => { + if (existsSync(TEST_DIR)) { + rmSync(TEST_DIR, { recursive: true, force: true }); + } +}); + +describe('SessionTimeline', () => { + it('should create timeline instance', () => { + const timeline = new SessionTimeline(TEST_DIR); + expect(timeline).toBeDefined(); + }); + + it('should return empty timeline when no data', () => { + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build(); + expect(data.events).toEqual([]); + expect(data.totalCount).toBe(0); + expect(data.projectPath).toBe(TEST_DIR); + }); + + it('should collect events from current execution', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + currentExecution: { + skillName: 'test-skill', + skillSource: 'test', + currentStep: 1, + totalSteps: 2, + status: 'running', + startedAt: '2026-02-12T10:00:00.000Z', + tasks: [ + { + id: 't1', + name: 'Task 1', + type: 'auto', + status: 'completed', + startedAt: '2026-02-12T10:00:00.000Z', + completedAt: '2026-02-12T10:01:00.000Z', + }, + { + id: 't2', + name: 'Task 2', + type: 'auto', + status: 'in_progress', + startedAt: '2026-02-12T10:01:00.000Z', + }, + ], + }, + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + const skillStarts = data.events.filter((e) => e.type === 'skill_start'); + expect(skillStarts.length).toBe(1); + expect(skillStarts[0].source).toBe('test-skill'); + + const taskEvents = data.events.filter((e) => e.type === 'task_progress'); + expect(taskEvents.length).toBe(2); + }); + + it('should collect events from execution history', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'old-skill', + skillSource: 'test', + completedAt: '2026-02-11T15:00:00.000Z', + durationMs: 120000, + status: 'completed', + commits: ['abc1234'], + filesModified: ['src/index.ts'], + }, + ], + decisions: [], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + const completes = data.events.filter((e) => e.type === 'skill_complete'); + expect(completes.length).toBe(1); + expect(completes[0].summary).toContain('old-skill'); + expect(completes[0].summary).toContain('2m'); + }); + + it('should collect decision events', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [ + { + key: 'api-style', + value: 'REST', + madeAt: '2026-02-12T11:00:00.000Z', + skillName: 'architect', + }, + ], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + const decisions = data.events.filter((e) => e.type === 'decision'); + expect(decisions.length).toBe(1); + expect(decisions[0].summary).toContain('REST'); + }); + + it('should collect observation events', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + }); + + writeObservations([ + { + id: 'obs1', + timestamp: '2026-02-12T10:30:00.000Z', + sessionId: 'test', + agent: 'claude-code', + type: 'error', + content: { action: 'build', context: 'src', error: 'missing import' }, + relevance: 80, + }, + ]); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + const obs = data.events.filter((e) => e.type === 'observation'); + expect(obs.length).toBe(1); + expect(obs[0].summary).toContain('error'); + }); + + it('should collect snapshot events', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [], + decisions: [], + }); + + writeSnapshots([ + { + version: 1, + name: 'pre-refactor', + createdAt: '2026-02-12T09:00:00.000Z', + description: 'Before big refactor', + sessionState: { + version: 1, + lastActivity: '2026-02-12T09:00:00.000Z', + projectPath: TEST_DIR, + history: [], + decisions: [], + }, + observations: [], + }, + ]); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + const snaps = data.events.filter((e) => e.type === 'snapshot'); + expect(snaps.length).toBe(1); + expect(snaps[0].summary).toContain('pre-refactor'); + }); + + it('should filter by event type', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'skill-a', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + ], + decisions: [ + { key: 'k', value: 'v', madeAt: '2026-02-12T10:01:00.000Z' }, + ], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ types: ['decision'], includeGit: false }); + + expect(data.events.every((e) => e.type === 'decision')).toBe(true); + expect(data.events.length).toBe(1); + }); + + it('should filter by since date', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'old', + skillSource: 'test', + completedAt: '2026-02-01T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + { + skillName: 'recent', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + ], + decisions: [], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ since: '2026-02-10', includeGit: false }); + + expect(data.events.length).toBe(1); + expect(data.events[0].source).toBe('recent'); + }); + + it('should respect limit', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: Array.from({ length: 10 }, (_, i) => ({ + skillName: `skill-${i}`, + skillSource: 'test', + completedAt: `2026-02-12T${String(i).padStart(2, '0')}:00:00.000Z`, + durationMs: 60000, + status: 'completed' as const, + commits: [], + filesModified: [], + })), + decisions: [], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ limit: 3, includeGit: false }); + + expect(data.events.length).toBe(3); + expect(data.totalCount).toBe(10); + }); + + it('should sort events chronologically', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'later', + skillSource: 'test', + completedAt: '2026-02-12T12:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + { + skillName: 'earlier', + skillSource: 'test', + completedAt: '2026-02-12T08:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + ], + decisions: [], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ includeGit: false }); + + expect(data.events[0].source).toBe('earlier'); + expect(data.events[1].source).toBe('later'); + }); + + it('should format text output', () => { + const timeline = new SessionTimeline(TEST_DIR); + const data = { + projectPath: TEST_DIR, + sessionDate: '2026-02-12', + events: [ + { + timestamp: '2026-02-12T10:30:00.000Z', + type: 'skill_start' as const, + source: 'test-skill', + summary: 'test-skill started', + }, + ], + totalCount: 1, + }; + + const text = timeline.formatText(data); + expect(text).toContain('Session Timeline'); + expect(text).toContain('test-skill started'); + expect(text).toContain('1 event total'); + }); + + it('should format JSON output', () => { + const timeline = new SessionTimeline(TEST_DIR); + const data = { + projectPath: TEST_DIR, + sessionDate: '2026-02-12', + events: [], + totalCount: 0, + }; + + const json = timeline.formatJson(data); + const parsed = JSON.parse(json); + expect(parsed.projectPath).toBe(TEST_DIR); + expect(parsed.events).toEqual([]); + }); + + it('should filter by skill name', () => { + writeSessionState({ + version: 1, + lastActivity: new Date().toISOString(), + projectPath: TEST_DIR, + history: [ + { + skillName: 'target-skill', + skillSource: 'test', + completedAt: '2026-02-12T10:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + { + skillName: 'other-skill', + skillSource: 'test', + completedAt: '2026-02-12T11:00:00.000Z', + durationMs: 60000, + status: 'completed', + commits: [], + filesModified: [], + }, + ], + decisions: [], + }); + + const timeline = new SessionTimeline(TEST_DIR); + const data = timeline.build({ skillFilter: 'target-skill', includeGit: false }); + + expect(data.events.length).toBe(1); + expect(data.events[0].source).toBe('target-skill'); + }); + + it('should handle empty events in text format', () => { + const timeline = new SessionTimeline(TEST_DIR); + const data = { + projectPath: TEST_DIR, + sessionDate: '2026-02-12', + events: [], + totalCount: 0, + }; + + const text = timeline.formatText(data); + expect(text).toContain('No events found'); + }); +}); diff --git a/packages/core/src/session/handoff.ts b/packages/core/src/session/handoff.ts new file mode 100644 index 00000000..e9ac76ee --- /dev/null +++ b/packages/core/src/session/handoff.ts @@ -0,0 +1,314 @@ +import { SessionManager } from './manager.js'; +import { ActivityLog } from './activity-log.js'; +import { ObservationStore } from '../memory/observation-store.js'; +import { getGitCommits } from '../learning/git-analyzer.js'; +import { loadConfig } from '../config.js'; +import type { + HandoffDocument, + HandoffSection, + HandoffOptions, + SessionTask, + ExecutionHistory, +} from './types.js'; + +function formatDuration(ms: number): string { + const seconds = Math.floor(ms / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m`; + return `${seconds}s`; +} + +export class SessionHandoff { + private readonly projectPath: string; + private readonly sessionManager: SessionManager; + private readonly activityLog: ActivityLog; + + constructor(projectPath: string) { + this.projectPath = projectPath; + this.sessionManager = new SessionManager(projectPath); + this.activityLog = new ActivityLog(projectPath); + } + + generate(options?: HandoffOptions): HandoffDocument { + const state = this.sessionManager.get(); + const includeGit = options?.includeGit !== false; + const includeObservations = options?.includeObservations !== false; + const maxObservations = options?.maxObservations ?? 20; + + let agent = 'unknown'; + try { + const configAgent = loadConfig().agent; + if (configAgent && configAgent !== 'universal') { + agent = configAgent; + } + } catch { + // use default + } + + if (agent === 'unknown' && state?.currentExecution?.skillSource) { + agent = state.currentExecution.skillSource; + } + + const accomplished = this.buildAccomplished(state?.currentExecution?.tasks, state?.history ?? [], includeGit); + const pending = this.buildPending(state?.currentExecution?.tasks); + const keyFiles = this.buildKeyFiles(state?.currentExecution?.tasks, state?.history ?? []); + const observations = includeObservations + ? this.buildObservations(maxObservations) + : { errors: [], solutions: [], patterns: [] }; + const recommendations = this.buildRecommendations(pending, observations, includeGit); + + return { + generatedAt: new Date().toISOString(), + fromAgent: agent, + projectPath: this.projectPath, + accomplished, + pending, + keyFiles, + observations, + recommendations, + }; + } + + private buildAccomplished( + tasks: SessionTask[] | undefined, + history: ExecutionHistory[], + includeGit: boolean + ): HandoffSection { + const section: HandoffSection = { tasks: [], commits: [] }; + + for (const task of tasks ?? []) { + if (task.status === 'completed') { + let duration: string | undefined; + if (task.startedAt && task.completedAt) { + duration = formatDuration( + new Date(task.completedAt).getTime() - new Date(task.startedAt).getTime() + ); + } + section.tasks.push({ + name: task.name, + duration, + commitSha: task.commitSha, + }); + } + } + + for (const hist of history) { + if (hist.status === 'completed') { + section.tasks.push({ + name: hist.skillName, + duration: Number.isFinite(hist.durationMs) ? formatDuration(hist.durationMs) : undefined, + commitSha: hist.commits?.[0], + }); + } + } + + if (includeGit) { + try { + const today = new Date().toISOString().split('T')[0]; + const commits = getGitCommits(this.projectPath, { commits: 50 }); + for (const commit of commits) { + if (commit.date.startsWith(today)) { + section.commits.push({ + sha: commit.shortHash, + message: commit.message, + filesCount: commit.files.length, + }); + } + } + } catch { + // git not available + } + } + + return section; + } + + private buildPending(tasks: SessionTask[] | undefined): HandoffSection { + const section: HandoffSection = { tasks: [], commits: [] }; + + const pendingStatuses = new Set(['pending', 'in_progress', 'paused']); + for (const task of tasks ?? []) { + if (pendingStatuses.has(task.status)) { + section.tasks.push({ name: task.name }); + } + } + + return section; + } + + private buildKeyFiles( + tasks: SessionTask[] | undefined, + history: ExecutionHistory[] + ): Array<{ path: string; changeType: string }> { + const fileMap = new Map(); + + for (const task of tasks ?? []) { + for (const f of task.filesModified ?? []) { + fileMap.set(f, task.status === 'completed' ? 'modified' : 'in-progress'); + } + } + + for (const hist of history) { + for (const f of hist.filesModified ?? []) { + if (!fileMap.has(f)) { + fileMap.set(f, 'modified'); + } + } + } + + return Array.from(fileMap.entries()) + .map(([path, changeType]) => ({ path, changeType })) + .sort((a, b) => a.path.localeCompare(b.path)); + } + + private buildObservations(max: number): HandoffDocument['observations'] { + const result: HandoffDocument['observations'] = { + errors: [], + solutions: [], + patterns: [], + }; + + try { + const observations = ObservationStore.readAll(this.projectPath); + const sorted = [...observations].sort((a, b) => b.relevance - a.relevance); + let count = 0; + + for (const obs of sorted) { + if (count >= max) break; + if (obs.type === 'error' && obs.content.error) { + result.errors.push({ action: obs.content.action, error: obs.content.error }); + count++; + } else if (obs.type === 'solution' && obs.content.solution) { + result.solutions.push({ action: obs.content.action, solution: obs.content.solution }); + count++; + } else if (obs.type === 'pattern' && obs.content.context) { + result.patterns.push({ action: obs.content.action, context: obs.content.context }); + count++; + } + } + } catch { + // no observations + } + + return result; + } + + private buildRecommendations( + pending: HandoffSection, + observations: HandoffDocument['observations'], + includeGit: boolean + ): string[] { + const recs: string[] = []; + + if (pending.tasks.length > 0) { + recs.push(`Complete pending tasks: ${pending.tasks.map((t) => t.name).join(', ')}`); + } + + if (observations.errors.length > 0) { + const unresolved = observations.errors.filter( + (e) => !observations.solutions.some((s) => s.action === e.action) + ); + if (unresolved.length > 0) { + recs.push(`Resolve ${unresolved.length} unresolved error(s)`); + } + } + + if (includeGit) { + try { + const activities = this.activityLog.getRecent(50); + const fileCounts = new Map(); + for (const activity of activities) { + for (const f of activity.filesChanged) { + fileCounts.set(f, (fileCounts.get(f) ?? 0) + 1); + } + } + const highChurn = Array.from(fileCounts.entries()) + .filter(([, count]) => count >= 3) + .sort((a, b) => b[1] - a[1]) + .slice(0, 3); + + for (const [file, count] of highChurn) { + recs.push(`Review high-churn file: ${file} (${count} changes)`); + } + } catch { + // activity log not available + } + } + + return recs; + } + + toMarkdown(doc: HandoffDocument): string { + const lines: string[] = []; + lines.push(`# Session Handoff`); + lines.push(`Agent: ${doc.fromAgent} | ${doc.generatedAt.split('T')[0]}\n`); + + lines.push(`## Accomplished`); + if (doc.accomplished.tasks.length === 0 && doc.accomplished.commits.length === 0) { + lines.push('No completed tasks.\n'); + } else { + for (const task of doc.accomplished.tasks) { + const dur = task.duration ? ` (${task.duration})` : ''; + const sha = task.commitSha ? ` [${task.commitSha.slice(0, 7)}]` : ''; + lines.push(`- ${task.name}${dur}${sha}`); + } + for (const commit of doc.accomplished.commits) { + lines.push(`- ${commit.sha} — ${commit.message} (${commit.filesCount} files)`); + } + lines.push(''); + } + + lines.push(`## Pending`); + if (doc.pending.tasks.length === 0) { + lines.push('No pending tasks.\n'); + } else { + for (const task of doc.pending.tasks) { + lines.push(`- ${task.name}`); + } + lines.push(''); + } + + if (doc.keyFiles.length > 0) { + lines.push(`## Key Files`); + for (const f of doc.keyFiles) { + lines.push(`- \`${f.path}\` (${f.changeType})`); + } + lines.push(''); + } + + const hasObs = + doc.observations.errors.length > 0 || + doc.observations.solutions.length > 0 || + doc.observations.patterns.length > 0; + + if (hasObs) { + lines.push(`## Observations`); + for (const e of doc.observations.errors) { + lines.push(`- Error: ${e.error} (${e.action})`); + } + for (const s of doc.observations.solutions) { + lines.push(`- Solution: ${s.solution} (${s.action})`); + } + for (const p of doc.observations.patterns) { + lines.push(`- Pattern: ${p.action} — ${p.context}`); + } + lines.push(''); + } + + if (doc.recommendations.length > 0) { + lines.push(`## Recommendations`); + doc.recommendations.forEach((r, i) => { + lines.push(`${i + 1}. ${r}`); + }); + lines.push(''); + } + + return lines.join('\n'); + } + + toJson(doc: HandoffDocument): string { + return JSON.stringify(doc, null, 2); + } +} diff --git a/packages/core/src/session/index.ts b/packages/core/src/session/index.ts index 03bb6050..032e4f76 100644 --- a/packages/core/src/session/index.ts +++ b/packages/core/src/session/index.ts @@ -11,3 +11,6 @@ export { SessionManager, createSessionManager } from './manager.js'; export { ActivityLog } from './activity-log.js'; export { SnapshotManager } from './snapshot-manager.js'; export { SessionExplainer } from './session-explainer.js'; +export { SessionTimeline } from './timeline.js'; +export { SessionHandoff } from './handoff.js'; +export { SkillLineage } from './lineage.js'; diff --git a/packages/core/src/session/lineage.ts b/packages/core/src/session/lineage.ts new file mode 100644 index 00000000..1079706e --- /dev/null +++ b/packages/core/src/session/lineage.ts @@ -0,0 +1,288 @@ +import { SessionManager } from './manager.js'; +import { ActivityLog } from './activity-log.js'; +import { ObservationStore } from '../memory/observation-store.js'; +import type { + SkillLineageEntry, + FileLineage, + LineageData, + LineageOptions, +} from './types.js'; + +function formatDurationMs(ms: number): string { + const seconds = Math.floor(ms / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m`; + return `${seconds}s`; +} + +export class SkillLineage { + private readonly projectPath: string; + private readonly sessionManager: SessionManager; + private readonly activityLog: ActivityLog; + + constructor(projectPath: string) { + this.projectPath = projectPath; + this.sessionManager = new SessionManager(projectPath); + this.activityLog = new ActivityLog(projectPath); + } + + build(options?: LineageOptions): LineageData { + const state = this.sessionManager.get(); + const sinceDate = options?.since ? new Date(options.since) : undefined; + + const skillMap = new Map(); + const fileSkillMap = new Map>(); + const fileCommitCount = new Map(); + const fileLastModified = new Map(); + + for (const hist of state?.history ?? []) { + if (sinceDate && new Date(hist.completedAt) < sinceDate) continue; + + const entry = skillMap.get(hist.skillName) ?? { + skillName: hist.skillName, + executions: 0, + totalDurationMs: 0, + commits: [], + filesModified: [], + observationIds: [], + firstSeen: hist.completedAt, + lastSeen: hist.completedAt, + }; + + entry.executions++; + entry.totalDurationMs += hist.durationMs; + entry.commits.push(...(hist.commits ?? [])); + entry.filesModified.push(...(hist.filesModified ?? [])); + + if (new Date(hist.completedAt) < new Date(entry.firstSeen)) { + entry.firstSeen = hist.completedAt; + } + if (new Date(hist.completedAt) > new Date(entry.lastSeen)) { + entry.lastSeen = hist.completedAt; + } + + skillMap.set(hist.skillName, entry); + + for (const f of hist.filesModified ?? []) { + const skills = fileSkillMap.get(f) ?? new Set(); + skills.add(hist.skillName); + fileSkillMap.set(f, skills); + + fileCommitCount.set(f, (fileCommitCount.get(f) ?? 0) + (hist.commits?.length ?? 0)); + const existing = fileLastModified.get(f); + if (!existing || new Date(hist.completedAt) > new Date(existing)) { + fileLastModified.set(f, hist.completedAt); + } + } + } + + if (state?.currentExecution) { + const exec = state.currentExecution; + const startTime = new Date(exec.startedAt); + if (!sinceDate || startTime >= sinceDate) { + const entry = skillMap.get(exec.skillName) ?? { + skillName: exec.skillName, + executions: 0, + totalDurationMs: 0, + commits: [], + filesModified: [], + observationIds: [], + firstSeen: exec.startedAt, + lastSeen: exec.startedAt, + }; + + entry.executions++; + entry.totalDurationMs += Date.now() - startTime.getTime(); + + for (const task of exec.tasks) { + if (task.commitSha) entry.commits.push(task.commitSha); + entry.filesModified.push(...(task.filesModified ?? [])); + for (const f of task.filesModified ?? []) { + const skills = fileSkillMap.get(f) ?? new Set(); + skills.add(exec.skillName); + fileSkillMap.set(f, skills); + + if (task.commitSha) { + fileCommitCount.set(f, (fileCommitCount.get(f) ?? 0) + 1); + } + const existing = fileLastModified.get(f); + if (!existing || new Date(exec.startedAt) > new Date(existing)) { + fileLastModified.set(f, exec.startedAt); + } + } + } + + if (new Date(exec.startedAt) < new Date(entry.firstSeen)) { + entry.firstSeen = exec.startedAt; + } + entry.lastSeen = new Date().toISOString(); + + skillMap.set(exec.skillName, entry); + } + } + + try { + const activities = this.activityLog.getRecent(500); + for (const activity of activities) { + if (sinceDate && new Date(activity.committedAt) < sinceDate) continue; + const countedFiles = new Set(); + for (const skill of activity.activeSkills) { + const entry = skillMap.get(skill); + if (entry && !entry.commits.includes(activity.commitSha)) { + entry.commits.push(activity.commitSha); + } + for (const f of activity.filesChanged) { + const skills = fileSkillMap.get(f) ?? new Set(); + skills.add(skill); + fileSkillMap.set(f, skills); + if (!countedFiles.has(f)) { + fileCommitCount.set(f, (fileCommitCount.get(f) ?? 0) + 1); + countedFiles.add(f); + } + const existing = fileLastModified.get(f); + if (!existing || new Date(activity.committedAt) > new Date(existing)) { + fileLastModified.set(f, activity.committedAt); + } + } + } + } + } catch { + // activity log not available + } + + const errorProneFiles: string[] = []; + try { + const observations = ObservationStore.readAll(this.projectPath); + for (const obs of observations) { + if (sinceDate && new Date(obs.timestamp) < sinceDate) continue; + + for (const [, entry] of skillMap) { + const execStart = new Date(entry.firstSeen).getTime(); + const execEnd = new Date(entry.lastSeen).getTime(); + const obsTime = new Date(obs.timestamp).getTime(); + if (obsTime >= execStart && obsTime <= execEnd) { + if (!entry.observationIds.includes(obs.id)) { + entry.observationIds.push(obs.id); + } + } + } + + if (obs.type === 'error' && Array.isArray(obs.content?.files)) { + errorProneFiles.push(...obs.content.files); + } + } + } catch { + // no observations + } + + for (const entry of skillMap.values()) { + entry.commits = [...new Set(entry.commits)]; + entry.filesModified = [...new Set(entry.filesModified)]; + } + + let skills = Array.from(skillMap.values()); + let files: FileLineage[] = Array.from(fileSkillMap.entries()).map(([path, skillSet]) => ({ + path, + skills: Array.from(skillSet), + commitCount: fileCommitCount.get(path) ?? 0, + lastModified: fileLastModified.get(path) ?? '', + })); + + if (options?.skill) { + skills = skills.filter((s) => s.skillName === options.skill); + const skillFiles = new Set(skills.flatMap((s) => s.filesModified)); + files = files.filter((f) => skillFiles.has(f.path)); + } + + if (options?.file) { + files = files.filter((f) => f.path === options.file || f.path.includes(options.file!)); + const fileSkills = new Set(files.flatMap((f) => f.skills)); + skills = skills.filter((s) => fileSkills.has(s.skillName)); + } + + skills.sort((a, b) => b.filesModified.length - a.filesModified.length); + files.sort((a, b) => b.skills.length - a.skills.length || b.commitCount - a.commitCount); + + if (options?.limit) { + skills = skills.slice(0, options.limit); + files = files.slice(0, options.limit); + } + + const uniqueErrorFiles = [...new Set(errorProneFiles)]; + const allCommits = new Set(skills.flatMap((s) => s.commits)); + const allFiles = new Set(skills.flatMap((s) => s.filesModified)); + + const mostImpactful = skills.length > 0 ? skills[0].skillName : null; + const mostChanged = files.length > 0 ? files[0].path : null; + + return { + projectPath: this.projectPath, + skills, + files, + stats: { + totalSkillExecutions: skills.reduce((sum, s) => sum + s.executions, 0), + totalCommits: allCommits.size, + totalFilesChanged: allFiles.size, + mostImpactfulSkill: mostImpactful, + mostChangedFile: mostChanged, + errorProneFiles: uniqueErrorFiles.slice(0, 5), + }, + }; + } + + getSkillLineage(skillName: string): SkillLineageEntry | undefined { + const data = this.build({ skill: skillName }); + return data.skills.find((s) => s.skillName === skillName); + } + + getFileLineage(filePath: string): FileLineage | undefined { + const data = this.build({ file: filePath }); + return data.files.find((f) => f.path === filePath || f.path.includes(filePath)); + } + + formatText(data: LineageData): string { + const lines: string[] = []; + lines.push(' Skill Lineage\n'); + + if (data.skills.length === 0) { + lines.push(' No skill executions found.\n'); + return lines.join('\n'); + } + + lines.push(' Skills'); + for (const skill of data.skills) { + const duration = formatDurationMs(skill.totalDurationMs); + lines.push( + ` ${skill.skillName.padEnd(24)} ${skill.executions} runs ${skill.commits.length} commits ${skill.filesModified.length} files ${duration} total` + ); + } + lines.push(''); + + const hotspots = data.files.filter((f) => f.skills.length >= 2); + if (hotspots.length > 0) { + lines.push(' File Hotspots (touched by 2+ skills)'); + for (const f of hotspots.slice(0, 10)) { + lines.push(` ${f.path.padEnd(40)} ${f.skills.join(', ')}`); + } + lines.push(''); + } + + lines.push(' Stats'); + lines.push(` Total executions: ${data.stats.totalSkillExecutions} | Commits: ${data.stats.totalCommits}`); + if (data.stats.mostImpactfulSkill) { + const skill = data.skills.find((s) => s.skillName === data.stats.mostImpactfulSkill); + lines.push(` Most impactful: ${data.stats.mostImpactfulSkill} (${skill?.filesModified.length ?? 0} files)`); + } + if (data.stats.errorProneFiles.length > 0) { + lines.push(` Error-prone: ${data.stats.errorProneFiles.join(', ')}`); + } + + return lines.join('\n'); + } + + formatJson(data: LineageData): string { + return JSON.stringify(data, null, 2); + } +} diff --git a/packages/core/src/session/timeline.ts b/packages/core/src/session/timeline.ts new file mode 100644 index 00000000..6580e5ac --- /dev/null +++ b/packages/core/src/session/timeline.ts @@ -0,0 +1,231 @@ +import { SessionManager } from './manager.js'; +import { ActivityLog } from './activity-log.js'; +import { SnapshotManager } from './snapshot-manager.js'; +import { ObservationStore } from '../memory/observation-store.js'; +import { getGitCommits } from '../learning/git-analyzer.js'; +import type { + TimelineEvent, + TimelineData, + TimelineOptions, + TimelineEventType, +} from './types.js'; + +function formatDuration(ms: number): string { + const seconds = Math.floor(ms / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + if (hours > 0) return `${hours}h ${minutes % 60}m`; + if (minutes > 0) return `${minutes}m`; + return `${seconds}s`; +} + +function formatTime(iso: string): string { + const d = new Date(iso); + if (isNaN(d.getTime())) return iso; + return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true }); +} + +export class SessionTimeline { + private readonly projectPath: string; + private readonly sessionManager: SessionManager; + private readonly activityLog: ActivityLog; + private readonly snapshotManager: SnapshotManager; + + constructor(projectPath: string) { + this.projectPath = projectPath; + this.sessionManager = new SessionManager(projectPath); + this.activityLog = new ActivityLog(projectPath); + this.snapshotManager = new SnapshotManager(projectPath); + } + + build(options?: TimelineOptions): TimelineData { + const events: TimelineEvent[] = []; + const state = this.sessionManager.get(); + const limit = options?.limit ?? 50; + const includeGit = options?.includeGit !== false; + const sinceDate = options?.since ? new Date(options.since) : undefined; + if (sinceDate && isNaN(sinceDate.getTime())) { + return { projectPath: this.projectPath, sessionDate: new Date().toISOString().split('T')[0], events: [], totalCount: 0 }; + } + + if (state?.currentExecution) { + const exec = state.currentExecution; + events.push({ + timestamp: exec.startedAt, + type: 'skill_start', + source: exec.skillName, + summary: `${exec.skillName} started`, + details: { status: exec.status, totalSteps: exec.totalSteps }, + }); + + const activeStatuses = new Set(['in_progress', 'completed', 'failed']); + for (const task of exec.tasks) { + if (task.startedAt && activeStatuses.has(task.status)) { + events.push({ + timestamp: task.completedAt ?? task.startedAt, + type: 'task_progress', + source: exec.skillName, + summary: `${task.name} (${task.status})`, + details: { taskId: task.id, error: task.error }, + }); + } + } + } + + for (const hist of state?.history ?? []) { + events.push({ + timestamp: hist.completedAt, + type: 'skill_complete', + source: hist.skillName, + summary: `${hist.skillName} ${hist.status} (${formatDuration(hist.durationMs)})`, + details: { + durationMs: hist.durationMs, + commits: hist.commits, + filesModified: hist.filesModified, + }, + }); + } + + if (includeGit) { + try { + const commits = getGitCommits(this.projectPath, { + commits: 50, + since: options?.since, + }); + for (const commit of commits) { + const activity = this.activityLog.getByCommit(commit.shortHash); + events.push({ + timestamp: commit.date, + type: 'git_commit', + source: activity?.activeSkills?.join(', ') ?? 'git', + summary: `${commit.shortHash} — ${commit.message} (${commit.files.length} files)`, + details: { + sha: commit.hash, + author: commit.author, + skills: activity?.activeSkills, + }, + }); + } + } catch { + // git not available + } + } + + try { + const observations = ObservationStore.readAll(this.projectPath); + for (const obs of observations) { + events.push({ + timestamp: obs.timestamp, + type: 'observation', + source: String(obs.agent), + summary: `${obs.type}: ${obs.content?.action ?? 'unknown'}`, + details: { observationId: obs.id, ...obs.content }, + }); + } + } catch { + // no observations + } + + for (const decision of state?.decisions ?? []) { + events.push({ + timestamp: decision.madeAt, + type: 'decision', + source: decision.skillName ?? 'user', + summary: `${decision.key} → ${decision.value}`, + }); + } + + try { + const snapshots = this.snapshotManager.list(); + for (const snap of snapshots) { + events.push({ + timestamp: snap.createdAt, + type: 'snapshot', + source: 'snapshot', + summary: `snapshot: ${snap.name}${snap.description ? ` — ${snap.description}` : ''}`, + details: { skillCount: snap.skillCount }, + }); + } + } catch { + // no snapshots + } + + let filtered = events; + + if (sinceDate) { + filtered = filtered.filter((e) => new Date(e.timestamp) >= sinceDate); + } + + if (options?.types && options.types.length > 0) { + const typeSet = new Set(options.types); + filtered = filtered.filter((e) => typeSet.has(e.type)); + } + + if (options?.skillFilter) { + const skill = options.skillFilter; + filtered = filtered.filter( + (e) => e.source.includes(skill) || (e.details?.skills as string[] | undefined)?.includes(skill) + ); + } + + filtered.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()); + + const totalCount = filtered.length; + const limited = filtered.slice(-limit); + + return { + projectPath: this.projectPath, + sessionDate: new Date().toISOString().split('T')[0], + events: limited, + totalCount, + }; + } + + formatText(data: TimelineData): string { + const lines: string[] = []; + lines.push(' Session Timeline\n'); + + if (data.events.length === 0) { + lines.push(' No events found.\n'); + return lines.join('\n'); + } + + const icons: Record = { + skill_start: '>', + skill_complete: '\u2713', + task_progress: '\u2022', + git_commit: '*', + observation: '!', + decision: '?', + snapshot: '\u25C9', + }; + + let lastTimeBlock = ''; + + for (const event of data.events) { + const time = formatTime(event.timestamp); + + if (time !== lastTimeBlock) { + if (lastTimeBlock) lines.push(''); + lines.push(` ${time}`); + lastTimeBlock = time; + } + + const icon = icons[event.type] ?? '\u2022'; + lines.push(` ${icon} ${event.summary}`); + } + + lines.push(''); + if (data.totalCount > data.events.length) { + lines.push(` Showing ${data.events.length} of ${data.totalCount} events`); + } else { + lines.push(` ${data.totalCount} ${data.totalCount === 1 ? 'event' : 'events'} total`); + } + + return lines.join('\n'); + } + + formatJson(data: TimelineData): string { + return JSON.stringify(data, null, 2); + } +} diff --git a/packages/core/src/session/types.ts b/packages/core/src/session/types.ts index 378dba38..728b3b20 100644 --- a/packages/core/src/session/types.ts +++ b/packages/core/src/session/types.ts @@ -146,6 +146,100 @@ export interface SessionSnapshot { }>; } +// Timeline types +export type TimelineEventType = 'skill_start' | 'skill_complete' | 'task_progress' | 'git_commit' | 'observation' | 'decision' | 'snapshot'; + +export interface TimelineEvent { + timestamp: string; + type: TimelineEventType; + source: string; + summary: string; + details?: Record; +} + +export interface TimelineData { + projectPath: string; + sessionDate: string; + events: TimelineEvent[]; + totalCount: number; +} + +export interface TimelineOptions { + since?: string; + types?: TimelineEventType[]; + limit?: number; + skillFilter?: string; + includeGit?: boolean; +} + +// Handoff types +export interface HandoffDocument { + generatedAt: string; + fromAgent: string; + projectPath: string; + accomplished: HandoffSection; + pending: HandoffSection; + keyFiles: Array<{ path: string; changeType: string }>; + observations: { + errors: Array<{ action: string; error: string }>; + solutions: Array<{ action: string; solution: string }>; + patterns: Array<{ action: string; context: string }>; + }; + recommendations: string[]; +} + +export interface HandoffSection { + tasks: Array<{ name: string; duration?: string; commitSha?: string }>; + commits: Array<{ sha: string; message: string; filesCount: number }>; +} + +export interface HandoffOptions { + targetAgent?: string; + includeGit?: boolean; + includeObservations?: boolean; + maxObservations?: number; +} + +// Lineage types +export interface SkillLineageEntry { + skillName: string; + executions: number; + totalDurationMs: number; + commits: string[]; + filesModified: string[]; + observationIds: string[]; + firstSeen: string; + lastSeen: string; +} + +export interface FileLineage { + path: string; + skills: string[]; + commitCount: number; + lastModified: string; +} + +export interface LineageData { + projectPath: string; + skills: SkillLineageEntry[]; + files: FileLineage[]; + stats: { + totalSkillExecutions: number; + totalCommits: number; + totalFilesChanged: number; + mostImpactfulSkill: string | null; + mostChangedFile: string | null; + errorProneFiles: string[]; + }; +} + +export interface LineageOptions { + skill?: string; + file?: string; + limit?: number; + since?: string; +} + export interface SessionExplanation { date: string; agent: string;