P0-P8: Full V1.0.0 Alpha implementation + audit reports
Implements 123 tasks across 9 phases (T-001..T-809) totaling 146 source files. Monorepo (P0): - 7-package Bun + Turborepo + TypeScript monorepo - dependency-cruiser enforcing 7 forbidden edges + 5 deep-import rules Contracts (P0): - 16 type files (ids/error/event/runtime/ipc/task/worker-result/tool/artifact/evidence/project/provider/permission/ui/capability/platform) Storage & Events (P1): - DatabaseManager + MigrationRunner (19 tables, 22 indexes, 5 schema_meta seeds) - 16 repositories (Repository<T,I,U> pattern, INV-1 status columns via EventStore.project only) - EventSchemaRegistry (54 durable + 7 ephemeral), EventStore, EventBus, EventIngestor - Project/Session/Artifact/Evidence stores + 8-step Recovery Tools & Permission (P2): - PathClassifier (8 categories), CommandRiskAnalyzer (10 categories), SecretRedactor - PermissionEngine 6-layer evaluation (capability→profile→task_scope→risk→credential→user_prompt) - ToolRegistry with 20+ tools across fs/shell/git/project/artifact/context/permission/doctor - CapabilityManifestValidator + CapabilityRegistry LLM & Context (P3): - ModelConfigLoader, CapabilityMatrix, AnthropicCanonicalConverter - AnthropicAdapter + OpenAICompatibleAdapter - ProviderManager facade - PromptLayerLoader (L0/L1/L3/L5), CompactionPolicy, ContextAssembler Worker IPC & Scheduler (P4): - WorkerProtocol (NDJSON), WorkerProcess (exit codes 0-5), WorkerManager (spawn/handshake) - WorkerRuntime (INV-3: IPC only, no direct fs/shell/SQLite) - 5 worker roles (Executor/Reviewer/Debugger/Compactor/ExperienceMiner) - TaskGraph, WavePlanner, RetryPlanner, AgentMonitor, WorkspaceManager - Scheduler (state machine), 8-step Recovery C++ Toolchain (P5): - DiagnosticParser, CppProjectDetector, CMakeConfigurator, CppBuilder - CppTestRunner, CppcheckRunner, ClangdClient - CppToolRegistrar + capability manifest Projection & TUI (P6): - ProjectionStore (hydrate/apply/snapshot/subscribe) - TuiApp + 8 components (Session/Task/Agent/Tool/Diff/Evidence/Permission/Blocker/Hud) - ProjectionClient in-process ref Agents & Knowledge (P7): - MainAgent, ArchitectureDesigner - DebugKnowledgeStore + LearnedMemoryStore (single-writer, outbox model) - Role integration wiring CLI & Doctor & Release (P8): - Logger + DeveloperLogEncryptor (AES-256-GCM) - DoctorService (self_bootstrap first) - RuntimeApp + ServiceRegistry - 11 CLI commands: run/init/doctor/provider/resume/compact/history/session/restore/e2e/release - CliEntrypoint + air<TODO> Audit (in AirPlan/docs/): - Deepseek开发阶段审计.md (97 findings) - Opus开发阶段审计.md (140+ findings, 18 P0 blockers) - MiniMaxM3开发阶段审计.md (18 P0 blockers, focuses on executability) - AirPlan/TODO.md (technical debt + 42 TODOs by phase) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
207
packages/runtime/src/sessions/SessionManager.ts
Executable file
207
packages/runtime/src/sessions/SessionManager.ts
Executable file
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* SessionManager - Open and close sessions per DD §6.2
|
||||
*
|
||||
* Implements SessionManager contract (contracts §8.6).
|
||||
* - open_session: computes db_path, opens+migrates, ingests session.created
|
||||
* - close_session: flushes ui_state, releases handle
|
||||
* - Provider/model fixed at open (immutable per session)
|
||||
*
|
||||
* @module packages/runtime/src/sessions/SessionManager
|
||||
*/
|
||||
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { randomUUID } from 'crypto'
|
||||
|
||||
import type {
|
||||
ProjectContext,
|
||||
SessionContext,
|
||||
OpenSessionOptions,
|
||||
SessionManager as ISessionManager,
|
||||
SessionID,
|
||||
ProviderID,
|
||||
ModelID,
|
||||
ISOTimeString,
|
||||
RuntimeEvent,
|
||||
} from '@aircoding/contracts'
|
||||
|
||||
import { DatabaseManager } from '../storage/DatabaseManager.js'
|
||||
import { MigrationRunner } from '../storage/MigrationRunner.js'
|
||||
import { EventIngestor } from '../events/EventIngestor.js'
|
||||
|
||||
/**
|
||||
* SessionManager implements SessionManager contract per DD §6.2.
|
||||
*
|
||||
* open_session flow:
|
||||
* 1. resolve session_id (options or IdGenerator.session_id())
|
||||
* 2. compute db_path = .air/local/sessions/<session-id>/session.db
|
||||
* 3. DatabaseManager.open(db_path); MigrationRunner.migrate(db)
|
||||
* 4. SessionStore bound to this db
|
||||
* 5. ingest session.created (durable → inserts sessions row)
|
||||
* 6. return SessionContext { session_id, project_id, project_root, db_path, artifact_root }
|
||||
*
|
||||
* close_session flow:
|
||||
* 1. flush ui_state (db-schema §1)
|
||||
* 2. publish terminal session event when archiving
|
||||
* 3. release DB handle
|
||||
*/
|
||||
export class SessionManager implements ISessionManager {
|
||||
private dbManager: DatabaseManager
|
||||
private migrationRunner: MigrationRunner
|
||||
private eventIngestor: EventIngestor
|
||||
private openSessions: Map<string, SessionContext> = new Map()
|
||||
|
||||
constructor(eventIngestor?: EventIngestor) {
|
||||
this.dbManager = new DatabaseManager()
|
||||
this.migrationRunner = new MigrationRunner()
|
||||
this.eventIngestor = eventIngestor ?? new EventIngestor()
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a new session for the given project.
|
||||
* Computes db_path, opens+migrates database, ingests session.created event.
|
||||
* Provider/model selection is captured at open and immutable for the session.
|
||||
*/
|
||||
async open_session(
|
||||
project: ProjectContext,
|
||||
options?: OpenSessionOptions
|
||||
): Promise<SessionContext> {
|
||||
// 1. Resolve session_id
|
||||
const sessionId = this.resolveSessionId(options)
|
||||
|
||||
// 2. Compute db_path = .air/local/sessions/<session-id>/session.db
|
||||
const sessionsDir = path.join(project.local_root, 'sessions', sessionId)
|
||||
const dbPath = path.join(sessionsDir, 'session.db')
|
||||
|
||||
// 3. Create session directory and open database
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true })
|
||||
this.dbManager.open(dbPath)
|
||||
|
||||
// Run migrations using raw database
|
||||
const db = this.dbManager.getRawDatabase()
|
||||
if (db) {
|
||||
await this.migrationRunner.migrate(db)
|
||||
}
|
||||
|
||||
// 4. Ingest session.created event (durable → inserts sessions row)
|
||||
await this.ingestSessionCreated(sessionId, project, options)
|
||||
|
||||
// 5. Compute artifact_root
|
||||
const artifactRoot = path.join(sessionsDir, 'artifacts')
|
||||
fs.mkdirSync(artifactRoot, { recursive: true })
|
||||
|
||||
// 6. Build and return SessionContext
|
||||
const sessionContext: SessionContext = {
|
||||
session_id: sessionId,
|
||||
project_id: project.project_id,
|
||||
project_root: project.project_root,
|
||||
db_path: dbPath,
|
||||
artifact_root: artifactRoot,
|
||||
}
|
||||
|
||||
// Track open session
|
||||
this.openSessions.set(sessionId, sessionContext)
|
||||
|
||||
return sessionContext
|
||||
}
|
||||
|
||||
/**
|
||||
* Close a session - flushes ui_state and releases the DB handle.
|
||||
* If archiving, publishes a terminal session event.
|
||||
*/
|
||||
async close_session(sessionId: SessionID): Promise<void> {
|
||||
const session = this.openSessions.get(sessionId)
|
||||
if (!session) {
|
||||
throw new Error(`Session ${sessionId} is not open`)
|
||||
}
|
||||
|
||||
// Close database connection
|
||||
this.dbManager.close()
|
||||
|
||||
// Remove from tracked sessions
|
||||
this.openSessions.delete(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve session_id from options or generate a new one.
|
||||
*/
|
||||
private resolveSessionId(options?: OpenSessionOptions): SessionID {
|
||||
if (options?.session_id) {
|
||||
return options.session_id
|
||||
}
|
||||
// Generate new session_id (format: sess_<ulid>)
|
||||
return `sess_${randomUUID().replace(/-/g, '').slice(0, 24)}` as SessionID
|
||||
}
|
||||
|
||||
/**
|
||||
* Ingest the session.created event (durable).
|
||||
*/
|
||||
private async ingestSessionCreated(
|
||||
sessionId: SessionID,
|
||||
project: ProjectContext,
|
||||
options?: OpenSessionOptions
|
||||
): Promise<void> {
|
||||
const now = new Date().toISOString() as ISOTimeString
|
||||
|
||||
// Build session.created event payload per event-registry §3.1
|
||||
const payload = {
|
||||
session_id: sessionId,
|
||||
project_id: project.project_id,
|
||||
project_root: project.project_root,
|
||||
title: options?.title,
|
||||
model_provider_id: options?.model_provider_id as ProviderID | undefined,
|
||||
model_id: options?.model_id as ModelID | undefined,
|
||||
metadata: undefined,
|
||||
}
|
||||
|
||||
const event: RuntimeEvent<typeof payload> = {
|
||||
id: `evt_${randomUUID().replace(/-/g, '').slice(0, 24)}` as any,
|
||||
type: 'session.created',
|
||||
version: 1,
|
||||
timestamp: now,
|
||||
session_id: sessionId,
|
||||
project_id: project.project_id as any,
|
||||
source: {
|
||||
kind: 'main',
|
||||
},
|
||||
route: ['session', 'created'],
|
||||
payload,
|
||||
}
|
||||
|
||||
try {
|
||||
await this.eventIngestor.ingest(event)
|
||||
} catch (error) {
|
||||
// If event ingestion fails, close the DB and propagate
|
||||
this.dbManager.close()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current session context if the session is open.
|
||||
*/
|
||||
getSession(sessionId: SessionID): SessionContext | undefined {
|
||||
return this.openSessions.get(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a session is currently open.
|
||||
*/
|
||||
isSessionOpen(sessionId: SessionID): boolean {
|
||||
return this.openSessions.has(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all open session IDs.
|
||||
*/
|
||||
getOpenSessions(): SessionID[] {
|
||||
return Array.from(this.openSessions.keys())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new SessionManager instance.
|
||||
*/
|
||||
export function createSessionManager(eventIngestor?: EventIngestor): SessionManager {
|
||||
return new SessionManager(eventIngestor)
|
||||
}
|
||||
Reference in New Issue
Block a user