@gitgov/core 2.1.2 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -6
- package/dist/src/{agent_runner-ByOUWOt6.d.ts → agent_runner-Cs5HXt4h.d.ts} +2 -1
- package/dist/src/fs.d.ts +11 -20
- package/dist/src/fs.js +9 -0
- package/dist/src/fs.js.map +1 -1
- package/dist/src/github.d.ts +472 -0
- package/dist/src/github.js +1281 -0
- package/dist/src/github.js.map +1 -0
- package/dist/src/{index--ahcnsG3.d.ts → index-D1RVufxB.d.ts} +38 -234
- package/dist/src/index.d.ts +10 -7
- package/dist/src/index.js +9 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/key_provider-CRpHFGjN.d.ts +227 -0
- package/dist/src/memory.d.ts +10 -4
- package/dist/src/memory.js +9 -1
- package/dist/src/memory.js.map +1 -1
- package/dist/src/{memory_file_lister-BkQ_C3ZU.d.ts → memory_file_lister-CfHtByeZ.d.ts} +2 -1
- package/package.json +6 -1
package/dist/src/fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/record_store/fs/fs_record_store.ts","../../src/config_manager/config_manager.ts","../../src/config_store/fs/fs_config_store.ts","../../src/session_manager/session_manager.ts","../../src/session_store/fs/fs_session_store.ts","../../src/key_provider/key_provider.ts","../../src/key_provider/fs/fs_key_provider.ts","../../src/file_lister/file_lister.errors.ts","../../src/file_lister/fs/fs_file_lister.ts","../../src/record_types/type_guards.ts","../../src/utils/id_parser.ts","../../src/utils/array_utils.ts","../../src/logger/logger.ts","../../src/crypto/checksum.ts","../../src/record_types/common.types.ts","../../src/record_schemas/errors.ts","../../src/record_schemas/generated/actor_record_schema.json","../../src/record_schemas/generated/agent_record_schema.json","../../src/record_schemas/generated/changelog_record_schema.json","../../src/record_schemas/generated/cycle_record_schema.json","../../src/record_schemas/generated/embedded_metadata_schema.json","../../src/record_schemas/generated/execution_record_schema.json","../../src/record_schemas/generated/feedback_record_schema.json","../../src/record_schemas/generated/task_record_schema.json","../../src/record_schemas/generated/workflow_record_schema.json","../../src/record_schemas/generated/index.ts","../../src/record_schemas/schema_cache.ts","../../src/crypto/signatures.ts","../../src/record_validations/embedded_metadata_validator.ts","../../src/record_validations/actor_validator.ts","../../src/record_factories/actor_factory.ts","../../src/record_validations/agent_validator.ts","../../src/record_factories/agent_factory.ts","../../src/record_validations/task_validator.ts","../../src/record_factories/task_factory.ts","../../src/record_validations/cycle_validator.ts","../../src/record_factories/cycle_factory.ts","../../src/record_validations/execution_validator.ts","../../src/record_factories/execution_factory.ts","../../src/record_validations/changelog_validator.ts","../../src/record_factories/changelog_factory.ts","../../src/record_validations/feedback_validator.ts","../../src/record_factories/feedback_factory.ts","../../src/lint/fs/fs_lint.ts","../../src/utils/esm_helper.ts","../../src/project_initializer/fs/fs_project_initializer.ts","../../src/git/errors.ts","../../src/git/local/local_git_module.ts","../../src/utils/project_discovery.ts","../../src/sync_state/sync_state.errors.ts","../../src/sync_state/sync_state.types.ts","../../src/sync_state/fs/fs_sync_state.ts","../../src/watcher_state/watcher_state.errors.ts","../../src/watcher_state/fs/fs_watcher_state.ts","../../src/agent_runner/agent_runner.errors.ts","../../src/agent_runner/backends/local_backend.ts","../../src/agent_runner/backends/api_backend.ts","../../src/agent_runner/backends/mcp_backend.ts","../../src/agent_runner/backends/custom_backend.ts","../../src/agent_runner/fs/fs_agent_runner.ts","../../src/agent_runner/fs/index.ts"],"names":["path","path2","fs","path3","fs4","path4","path5","fs5","logger","readdir","join","dirname","path6","require","path7","path8","existsSync","promisify","stat","readFileSync","verifySignatures","repoRoot","gitgovPath","gitgovExists","ChecksumMismatchError","readFile","basename"],"mappings":";;;;;;;;;;;;;;;;;;AA2BO,IAAM,kBAAA,GAAgC;AAAA,EAC3C,QAAQ,CAAC,EAAA,KAAe,EAAA,CAAG,OAAA,CAAQ,MAAM,GAAG,CAAA;AAAA,EAC5C,QAAQ,CAAC,OA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CAAS,WAAW,OAAO,CAAA;AACpD,MAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,OAAO,CAAA;AAEjC,MAAA,OAAO,OAAO,OAAA,IAAW,MAAA;AAAA,IAC3B,CAAA,CAAA,MAAQ;AACN,MAAA,MAAM,IAAI,mBAAmB,OAAO,CAAA;AAAA,IACtC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,UAAU,KAAA,EAA+B;AAC/C,IAAA,IAAI,KAAK,QAAA,EAAU;AACjB,MAAA,IAAA,CAAK,SAAS,OAAA,CAAQ;AAAA,QACpB,MAAM,KAAA,CAAM,IAAA;AAAA,QACZ,SAAA,EAAW,KAAK,GAAA,EAAI;AAAA,QACpB,MAAA,EAAQ,qBAAA;AAAA,QACR,SAAS,KAAA,CAAM;AAAA,OAChB,CAAA;AAAA,IACH;AAAA,EACF;AACF;;;ACvQO,SAAS,kBAAkB,IAAA,EAA6C;AAC7E,EAAA,OAAO,IAAI,cAAc,IAAI,CAAA;AAC/B","file":"fs.js","sourcesContent":["import * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { RecordStore } from '../record_store';\n\n/**\n * Serializer for FsRecordStore - allows custom serialization\n */\nexport interface Serializer {\n stringify: (value: unknown) => string;\n parse: <T>(text: string) => T;\n}\n\n/**\n * IdEncoder for transforming IDs to filesystem-safe filenames\n * Useful for characters not allowed in filesystem (e.g., `:` on Windows)\n */\nexport interface IdEncoder {\n /** Transform ID to filename-safe string */\n encode: (id: string) => string;\n /** Recover original ID from filename */\n decode: (encoded: string) => string;\n}\n\n/**\n * Default encoder: `:` → `_` (for IDs like \"human:camilo\")\n * Reversible because IDs cannot contain `_` (see id_generator.ts)\n */\nexport const DEFAULT_ID_ENCODER: IdEncoder = {\n encode: (id: string) => id.replace(/:/g, '_'),\n decode: (encoded: string) => encoded.replace(/_/g, ':'),\n};\n\n/**\n * Options for FsRecordStore\n */\nexport interface FsRecordStoreOptions {\n /** Base directory for files */\n basePath: string;\n\n /** File extension (default: \".json\") */\n extension?: string;\n\n /** Custom serializer (default: JSON with indent 2) */\n serializer?: Serializer;\n\n /** Create directory if it doesn't exist (default: true) */\n createIfMissing?: boolean;\n\n /** ID encoder for filesystem-safe filenames (default: undefined = no encoding) */\n idEncoder?: IdEncoder;\n}\n\nconst DEFAULT_SERIALIZER: Serializer = {\n stringify: (value) => JSON.stringify(value, null, 2),\n parse: (text) => JSON.parse(text),\n};\n\n/**\n * Validates that an ID does not contain path traversal.\n * Blocks: `..`, `/`, `\\`\n * Allows: single `.` (e.g., \"human.camilo\")\n */\nfunction validateId(id: string): void {\n if (!id || typeof id !== 'string') {\n throw new Error('ID must be a non-empty string');\n }\n if (id.includes('..') || /[\\/\\\\]/.test(id)) {\n throw new Error(`Invalid ID: \"${id}\". IDs cannot contain /, \\\\, or ..`);\n }\n}\n\n/**\n * FsRecordStore<T> - Filesystem implementation of Store<T>\n *\n * Persists records as JSON files on disk.\n *\n * @example\n * const store = new FsRecordStore<TaskRecord>({\n * basePath: '.gitgov/tasks',\n * });\n *\n * await store.put('123-task-foo', task);\n * const task = await store.get('123-task-foo');\n */\nexport class FsRecordStore<T> implements RecordStore<T> {\n private readonly basePath: string;\n private readonly extension: string;\n private readonly serializer: Serializer;\n private readonly createIfMissing: boolean;\n private readonly idEncoder: IdEncoder | undefined;\n\n constructor(options: FsRecordStoreOptions) {\n this.basePath = options.basePath;\n this.extension = options.extension ?? '.json';\n this.serializer = options.serializer ?? DEFAULT_SERIALIZER;\n this.createIfMissing = options.createIfMissing ?? true;\n this.idEncoder = options.idEncoder;\n }\n\n private getFilePath(id: string): string {\n validateId(id);\n const fileId = this.idEncoder ? this.idEncoder.encode(id) : id;\n return path.join(this.basePath, `${fileId}${this.extension}`);\n }\n\n async get(id: string): Promise<T | null> {\n const filePath = this.getFilePath(id);\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return this.serializer.parse<T>(content);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n }\n\n async put(id: string, value: T): Promise<void> {\n const filePath = this.getFilePath(id);\n if (this.createIfMissing) {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n }\n const content = this.serializer.stringify(value);\n await fs.writeFile(filePath, content, 'utf-8');\n }\n\n async delete(id: string): Promise<void> {\n const filePath = this.getFilePath(id);\n try {\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n async list(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.basePath);\n const ids = files\n .filter((f) => f.endsWith(this.extension))\n .map((f) => f.slice(0, -this.extension.length));\n return this.idEncoder ? ids.map((id) => this.idEncoder!.decode(id)) : ids;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n const filePath = this.getFilePath(id);\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * ConfigManager - Project Configuration Manager\n *\n * Provides typed access to GitGovernance project configuration (config.json).\n * Configuration is versioned in Git and shared between collaborators.\n *\n * Uses ConfigStore abstraction for backend-agnostic persistence.\n *\n * NOTE: Session state (.session.json) is handled by SessionManager, not ConfigManager.\n */\n\nimport type { ConfigStore } from '../config_store/config_store';\nimport type {\n IConfigManager,\n GitGovConfig,\n AuditState,\n SyncConfig,\n SyncDefaults,\n AuditStateUpdate\n} from './config_manager.types';\n\n/**\n * Configuration Manager Class\n *\n * Provides typed access to GitGovernance project configuration.\n * Uses ConfigStore abstraction for backend-agnostic persistence.\n *\n * @example\n * ```typescript\n * // Production usage\n * import { FsConfigStore } from '@gitgov/core/fs';\n * const configStore = new FsConfigStore('/path/to/project');\n * const configManager = new ConfigManager(configStore);\n *\n * // Test usage\n * import { MemoryConfigStore } from '@gitgov/core/memory';\n * const configStore = new MemoryConfigStore();\n * configStore.setConfig({ ... });\n * const configManager = new ConfigManager(configStore);\n * ```\n */\nexport class ConfigManager implements IConfigManager {\n private readonly configStore: ConfigStore;\n\n constructor(configStore: ConfigStore) {\n this.configStore = configStore;\n }\n\n /**\n * Load GitGovernance configuration\n */\n async loadConfig(): Promise<GitGovConfig | null> {\n return this.configStore.loadConfig();\n }\n\n /**\n * Get root cycle from configuration\n */\n async getRootCycle(): Promise<string | null> {\n const config = await this.loadConfig();\n return config?.rootCycle || null;\n }\n\n /**\n * Get project information from configuration\n */\n async getProjectInfo(): Promise<{ id: string; name: string } | null> {\n const config = await this.loadConfig();\n if (!config) return null;\n\n return {\n id: config.projectId,\n name: config.projectName\n };\n }\n\n /**\n * Get sync configuration from config.json\n * Returns sync strategy and related settings with defaults\n */\n async getSyncConfig(): Promise<SyncConfig | null> {\n const config = await this.loadConfig();\n if (!config?.state?.sync) return null;\n\n return {\n strategy: config.state.sync.strategy || \"manual\",\n maxRetries: config.state.sync.maxRetries || 3,\n pushIntervalSeconds: config.state.sync.pushIntervalSeconds || 30,\n batchIntervalSeconds: config.state.sync.batchIntervalSeconds || 60\n };\n }\n\n /**\n * Get sync defaults from config.json\n * Returns recommended defaults for pullScheduler and fileWatcher\n */\n async getSyncDefaults(): Promise<SyncDefaults> {\n const config = await this.loadConfig();\n\n return {\n pullScheduler: {\n defaultIntervalSeconds: config?.state?.defaults?.pullScheduler?.defaultIntervalSeconds || 30,\n defaultEnabled: config?.state?.defaults?.pullScheduler?.defaultEnabled || false,\n defaultContinueOnNetworkError: config?.state?.defaults?.pullScheduler?.defaultContinueOnNetworkError ?? true,\n defaultStopOnConflict: config?.state?.defaults?.pullScheduler?.defaultStopOnConflict || false\n },\n fileWatcher: {\n defaultDebounceMs: config?.state?.defaults?.fileWatcher?.defaultDebounceMs || 300,\n defaultIgnoredPatterns: config?.state?.defaults?.fileWatcher?.defaultIgnoredPatterns || [\"*.tmp\", \".DS_Store\", \"*.swp\"]\n }\n };\n }\n\n /**\n * Get audit state from config.json\n * Returns last full audit commit and timestamp for incremental mode\n */\n async getAuditState(): Promise<AuditState> {\n const config = await this.loadConfig();\n return {\n lastFullAuditCommit: config?.state?.audit?.lastFullAuditCommit || null,\n lastFullAuditTimestamp: config?.state?.audit?.lastFullAuditTimestamp || null,\n lastFullAuditFindingsCount: config?.state?.audit?.lastFullAuditFindingsCount ?? null\n };\n }\n\n /**\n * Update audit state in config.json after a full audit\n * This is used to enable incremental audits\n */\n async updateAuditState(auditState: AuditStateUpdate): Promise<void> {\n const config = await this.loadConfig();\n if (!config) {\n throw new Error('Cannot update audit state: config.json not found');\n }\n\n if (!config.state) {\n config.state = {};\n }\n\n config.state.audit = {\n lastFullAuditCommit: auditState.lastFullAuditCommit,\n lastFullAuditTimestamp: auditState.lastFullAuditTimestamp,\n lastFullAuditFindingsCount: auditState.lastFullAuditFindingsCount\n };\n\n await this.configStore.saveConfig(config);\n }\n\n /**\n * Get state branch name from configuration\n */\n async getStateBranch(): Promise<string> {\n const config = await this.loadConfig();\n return config?.state?.branch || 'gitgov-state';\n }\n}\n","/**\n * FsConfigStore - Filesystem implementation of ConfigStore\n *\n * Handles persistence of config.json to the local filesystem.\n *\n * NOTE: Session state (.session.json) is handled by FsSessionStore.\n * NOTE: Project discovery utilities are in src/utils/project_discovery.ts\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { ConfigStore } from '../config_store';\nimport type { GitGovConfig } from '../../config_manager/config_manager.types';\nimport { ConfigManager } from '../../config_manager/config_manager';\n\n/**\n * Filesystem-based ConfigStore implementation.\n *\n * Stores configuration in .gitgov/config.json.\n * Implements fail-safe pattern: returns null instead of throwing for missing files.\n *\n * @example\n * ```typescript\n * const store = new FsConfigStore('/path/to/project');\n * const config = await store.loadConfig();\n * if (config) {\n * console.log(config.projectName);\n * }\n * ```\n */\nexport class FsConfigStore implements ConfigStore {\n private readonly configPath: string;\n\n constructor(projectRootPath: string) {\n this.configPath = path.join(projectRootPath, '.gitgov', 'config.json');\n }\n\n /**\n * Load project configuration from .gitgov/config.json\n *\n * [EARS-A1] Returns complete GitGovConfig for valid files\n * [EARS-A2] Returns null for non-existent files (fail-safe)\n * [EARS-A3] Returns null for invalid JSON (graceful degradation)\n */\n async loadConfig(): Promise<GitGovConfig | null> {\n try {\n const configContent = await fs.readFile(this.configPath, 'utf-8');\n const config = JSON.parse(configContent) as GitGovConfig;\n\n // [EARS-A5] Warn if rootCycle doesn't match expected format\n if (config.rootCycle && !/^\\d+-cycle-[a-z0-9-]+$/.test(config.rootCycle)) {\n console.warn(\n `Warning: rootCycle \"${config.rootCycle}\" doesn't match expected format ` +\n `\"{timestamp}-cycle-{slug}\". This may cause issues with cycle navigation.`\n );\n }\n\n return config;\n } catch (error) {\n // Config file doesn't exist or is invalid - fail-safe behavior\n return null;\n }\n }\n\n /**\n * Save project configuration to .gitgov/config.json\n *\n * [EARS-A4] Writes config with JSON indentation\n */\n async saveConfig(config: GitGovConfig): Promise<void> {\n await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), 'utf-8');\n }\n}\n\n/**\n * Create a ConfigManager instance for a project.\n *\n * [EARS-B1] Factory function that creates a ConfigManager with FsConfigStore backend.\n * Use this when you already have the projectRoot (e.g., from DI container).\n *\n * @param projectRoot - Absolute path to project root (REQUIRED)\n * @returns ConfigManager instance with FsConfigStore backend\n */\nexport function createConfigManager(projectRoot: string): ConfigManager {\n const configStore = new FsConfigStore(projectRoot);\n return new ConfigManager(configStore);\n}\n","/**\n * SessionManager - Local Session State Manager\n *\n * Provides typed access to GitGovernance session state (.session.json).\n * Session state is ephemeral, machine-local, and NOT versioned in Git.\n *\n * Uses SessionStore abstraction for backend-agnostic persistence.\n */\n\nimport type { SessionStore } from '../session_store/session_store';\nimport type {\n ISessionManager,\n GitGovSession,\n ActorState,\n SyncPreferencesUpdate\n} from './session_manager.types';\n\n/**\n * Session Manager Class\n *\n * Provides typed access to GitGovernance session state.\n * Uses SessionStore abstraction for backend-agnostic persistence.\n *\n * @example\n * ```typescript\n * // Production usage\n * import { FsSessionStore } from '@gitgov/core/fs';\n * const sessionStore = new FsSessionStore('/path/to/project');\n * const sessionManager = new SessionManager(sessionStore);\n *\n * // Test usage\n * import { MemorySessionStore } from '@gitgov/core/memory';\n * const sessionStore = new MemorySessionStore();\n * sessionStore.setSession({ ... });\n * const sessionManager = new SessionManager(sessionStore);\n * ```\n */\nexport class SessionManager implements ISessionManager {\n private readonly sessionStore: SessionStore;\n\n constructor(sessionStore: SessionStore) {\n this.sessionStore = sessionStore;\n }\n\n /**\n * Load GitGovernance session state\n * [EARS-E1] Auto-detects actor from .key files if no session or no actorId exists\n */\n async loadSession(): Promise<GitGovSession | null> {\n let session = await this.sessionStore.loadSession();\n\n // [EARS-E1] If session exists but no lastSession.actorId, try to auto-detect\n if (session && !session.lastSession?.actorId) {\n const detectedActorId = await this.detectActorFromKeyFiles();\n if (detectedActorId) {\n session.lastSession = {\n actorId: detectedActorId,\n timestamp: new Date().toISOString()\n };\n await this.sessionStore.saveSession(session);\n }\n }\n\n // [EARS-E1] If no session, try to create from .key files\n if (!session) {\n const detectedActorId = await this.detectActorFromKeyFiles();\n if (detectedActorId) {\n const newSession: GitGovSession = {\n lastSession: {\n actorId: detectedActorId,\n timestamp: new Date().toISOString()\n },\n actorState: {}\n };\n try {\n await this.sessionStore.saveSession(newSession);\n return newSession;\n } catch {\n return newSession;\n }\n }\n }\n\n return session;\n }\n\n /**\n * [EARS-E1] Detect actor from .key files in .gitgov/actors/\n */\n async detectActorFromKeyFiles(): Promise<string | null> {\n if (this.sessionStore.detectActorFromKeyFiles) {\n return this.sessionStore.detectActorFromKeyFiles();\n }\n return null;\n }\n\n /**\n * Get actor state for a specific actor\n */\n async getActorState(actorId: string): Promise<ActorState | null> {\n const session = await this.loadSession();\n return session?.actorState?.[actorId] || null;\n }\n\n /**\n * Update actor state for a specific actor\n */\n async updateActorState(actorId: string, state: Partial<ActorState>): Promise<void> {\n const session = await this.loadSession() || {};\n if (!session.actorState) session.actorState = {};\n\n session.actorState[actorId] = {\n ...session.actorState[actorId],\n ...state,\n lastSync: new Date().toISOString()\n };\n\n // Update lastSession if the actor is a human (not an agent)\n if (actorId.startsWith('human:')) {\n session.lastSession = {\n actorId,\n timestamp: new Date().toISOString()\n };\n }\n\n await this.sessionStore.saveSession(session);\n }\n\n /**\n * Get cloud session token\n */\n async getCloudSessionToken(): Promise<string | null> {\n const session = await this.loadSession();\n return session?.cloud?.sessionToken || null;\n }\n\n /**\n * Get sync preferences from session\n */\n async getSyncPreferences(): Promise<GitGovSession['syncPreferences'] | null> {\n const session = await this.loadSession();\n return session?.syncPreferences || null;\n }\n\n /**\n * Update sync preferences in .session.json\n * These are local machine preferences that override project defaults\n */\n async updateSyncPreferences(preferences: SyncPreferencesUpdate): Promise<void> {\n const session = await this.loadSession() || {};\n\n if (!session.syncPreferences) {\n session.syncPreferences = {};\n }\n\n if (preferences.pullScheduler) {\n session.syncPreferences.pullScheduler = {\n ...session.syncPreferences.pullScheduler,\n ...preferences.pullScheduler\n };\n }\n\n if (preferences.fileWatcher) {\n session.syncPreferences.fileWatcher = {\n ...session.syncPreferences.fileWatcher,\n ...preferences.fileWatcher\n };\n }\n\n await this.sessionStore.saveSession(session);\n }\n\n /**\n * Get last session info (last human who interacted)\n */\n async getLastSession(): Promise<{ actorId: string; timestamp: string } | null> {\n const session = await this.loadSession();\n return session?.lastSession || null;\n }\n}\n","/**\n * FsSessionStore - Filesystem implementation of SessionStore\n *\n * Handles persistence of .session.json to the local filesystem.\n * Session files are machine-local and NOT versioned in Git.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { SessionStore } from '../session_store';\nimport type { GitGovSession } from '../../session_manager/session_manager.types';\nimport { SessionManager } from '../../session_manager/session_manager';\n\n/**\n * Filesystem-based SessionStore implementation.\n *\n * Stores session state in .gitgov/.session.json.\n * Implements fail-safe pattern: returns null instead of throwing for missing files.\n *\n * @example\n * ```typescript\n * const store = new FsSessionStore('/path/to/project');\n * const session = await store.loadSession();\n * if (session) {\n * console.log(session.lastSession?.actorId);\n * }\n * ```\n */\nexport class FsSessionStore implements SessionStore {\n private readonly sessionPath: string;\n private readonly actorsPath: string;\n\n constructor(projectRootPath: string) {\n this.sessionPath = path.join(projectRootPath, '.gitgov', '.session.json');\n this.actorsPath = path.join(projectRootPath, '.gitgov', 'actors');\n }\n\n /**\n * Load local session from .gitgov/.session.json\n *\n * [EARS-A1] Returns complete GitGovSession for valid files\n * [EARS-A2] Returns null for non-existent files (fail-safe)\n * [EARS-A3] Returns null for invalid JSON (graceful degradation)\n * [EARS-A4] Returns cloud token if present\n * [EARS-A5] Returns syncPreferences if present\n */\n async loadSession(): Promise<GitGovSession | null> {\n try {\n const sessionContent = await fs.readFile(this.sessionPath, 'utf-8');\n return JSON.parse(sessionContent) as GitGovSession;\n } catch (error) {\n // Session file doesn't exist or is invalid - fail-safe behavior\n return null;\n }\n }\n\n /**\n * Save local session to .gitgov/.session.json\n *\n * [EARS-B1] Writes session to .gitgov/.session.json with JSON indentation\n * [EARS-B2] Preserves all fields (cloud, actorState, syncPreferences)\n */\n async saveSession(session: GitGovSession): Promise<void> {\n await fs.writeFile(this.sessionPath, JSON.stringify(session, null, 2), 'utf-8');\n }\n\n /**\n * Detect actor from .key files in .gitgov/actors/\n *\n * [EARS-C1] Returns actor ID from first .key file\n * [EARS-C2] Returns first .key file alphabetically if multiple exist\n * [EARS-C3] Returns null if no .key files exist\n * [EARS-C4] Returns null if actors directory doesn't exist\n * [EARS-C5] Ignores non-.key files\n * [EARS-C6] Returns null for empty directory\n *\n * @returns Actor ID (e.g., \"human:camilo-v2\") or null\n */\n async detectActorFromKeyFiles(): Promise<string | null> {\n try {\n const files = await fs.readdir(this.actorsPath);\n\n // Find all .key files\n const keyFiles = files.filter(f => f.endsWith('.key'));\n\n // Get first .key file\n const firstKeyFile = keyFiles[0];\n if (!firstKeyFile) {\n return null;\n }\n\n // Extract actor ID from filename (remove .key extension)\n // e.g., \"human:camilo-v2.key\" -> \"human:camilo-v2\"\n const actorId = firstKeyFile.replace('.key', '');\n return actorId;\n } catch {\n // Directory doesn't exist or can't be read\n return null;\n }\n }\n}\n\n/**\n * Create a SessionManager instance for a project.\n *\n * [EARS-D1] Factory function that creates a SessionManager with FsSessionStore backend.\n * Use this when you already have the projectRoot (e.g., from DI container).\n *\n * @param projectRoot - Absolute path to project root (REQUIRED)\n * @returns SessionManager instance with FsSessionStore backend\n */\nexport function createSessionManager(projectRoot: string): SessionManager {\n const sessionStore = new FsSessionStore(projectRoot);\n return new SessionManager(sessionStore);\n}\n\n","/**\n * KeyProvider Interface\n *\n * Abstracts private key storage for Actor signing operations.\n * Enables different backends: filesystem (development), environment variables (serverless),\n * or cloud KMS (enterprise).\n *\n * @module key_provider\n */\n\n/**\n * Error codes for KeyProvider operations.\n */\nexport type KeyProviderErrorCode =\n | 'KEY_NOT_FOUND'\n | 'KEY_READ_ERROR'\n | 'KEY_WRITE_ERROR'\n | 'KEY_DELETE_ERROR'\n | 'INVALID_KEY_FORMAT'\n | 'INVALID_ACTOR_ID';\n\n/**\n * Error thrown when key operations fail.\n */\nexport class KeyProviderError extends Error {\n constructor(\n message: string,\n public readonly code: KeyProviderErrorCode,\n public readonly actorId?: string\n ) {\n super(message);\n this.name = 'KeyProviderError';\n }\n}\n\n/**\n * Interface for managing private key storage.\n * Implementations handle the actual persistence mechanism.\n *\n * @example\n * ```typescript\n * // Filesystem backend (development)\n * const provider = new FsKeyProvider({ actorsDir: '.gitgov/actors' });\n *\n * // Environment backend (serverless)\n * const provider = new EnvKeyProvider({ prefix: 'GITGOV_KEY_' });\n *\n * // Usage\n * const privateKey = await provider.getPrivateKey('actor:human:alice');\n * if (privateKey) {\n * const signature = signPayload(payload, privateKey, actorId, role);\n * }\n * ```\n */\nexport interface KeyProvider {\n /**\n * Retrieves the private key for an actor.\n * @param actorId - The actor's ID (e.g., 'actor:human:alice')\n * @returns The base64-encoded private key, or null if not found\n */\n getPrivateKey(actorId: string): Promise<string | null>;\n\n /**\n * Stores a private key for an actor.\n * @param actorId - The actor's ID\n * @param privateKey - The base64-encoded private key\n * @throws KeyProviderError if write fails\n */\n setPrivateKey(actorId: string, privateKey: string): Promise<void>;\n\n /**\n * Checks if a private key exists for an actor.\n * @param actorId - The actor's ID\n * @returns true if key exists, false otherwise\n */\n hasPrivateKey(actorId: string): Promise<boolean>;\n\n /**\n * Deletes the private key for an actor.\n * @param actorId - The actor's ID\n * @returns true if key was deleted, false if it didn't exist\n */\n deletePrivateKey(actorId: string): Promise<boolean>;\n}\n","/**\n * FsKeyProvider - Filesystem-based KeyProvider implementation\n *\n * Stores private keys alongside actor records in .gitgov/actors/{actorId}.key\n * Used in development and CLI environments.\n *\n * @module key_provider/fs/fs_key_provider\n */\n\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { KeyProvider } from '../key_provider';\nimport { KeyProviderError } from '../key_provider';\n\n/**\n * Options for FsKeyProvider.\n */\nexport interface FsKeyProviderOptions {\n /** Directory where key files are stored (same as actors: .gitgov/actors) */\n actorsDir: string;\n /** File extension for key files (default: '.key') */\n extension?: string;\n /** File permissions for key files (default: 0o600 - owner read/write only) */\n fileMode?: number;\n}\n\n/**\n * Filesystem-based KeyProvider implementation.\n * Keys are stored alongside actor records with .key extension.\n *\n * @example\n * ```typescript\n * const provider = new FsKeyProvider({ actorsDir: '.gitgov/actors' });\n * await provider.setPrivateKey('actor:human:alice', 'base64PrivateKey...');\n * const key = await provider.getPrivateKey('actor:human:alice');\n * ```\n */\nexport class FsKeyProvider implements KeyProvider {\n private readonly actorsDir: string;\n private readonly extension: string;\n private readonly fileMode: number;\n\n constructor(options: FsKeyProviderOptions) {\n this.actorsDir = options.actorsDir;\n this.extension = options.extension ?? '.key';\n this.fileMode = options.fileMode ?? 0o600;\n }\n\n /**\n * [EARS-KP01] Retrieves the private key for an actor.\n * [EARS-FKP07] Trims whitespace from content.\n * [EARS-FKP08] Returns null for empty key file.\n */\n async getPrivateKey(actorId: string): Promise<string | null> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n const content = await fs.readFile(keyPath, 'utf-8');\n const key = content.trim();\n\n if (!key) {\n return null;\n }\n\n return key;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // [EARS-KP02] File not found - return null\n return null;\n }\n\n throw new KeyProviderError(\n `Failed to read private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_READ_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-KP03] Stores a private key for an actor.\n * [EARS-FKP01] Creates actorsDir if not exists.\n * [EARS-FKP02] Writes key to {actorsDir}/{actorId}.key.\n * [EARS-FKP03] Sets secure file permissions (0600).\n */\n async setPrivateKey(actorId: string, privateKey: string): Promise<void> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n // [EARS-FKP01] Ensure directory exists\n await fs.mkdir(this.actorsDir, { recursive: true });\n\n // [EARS-FKP02] Write key to {actorsDir}/{actorId}.key\n await fs.writeFile(keyPath, privateKey, 'utf-8');\n\n // [EARS-FKP03] Set secure file permissions (owner read/write only)\n await fs.chmod(keyPath, this.fileMode);\n } catch (error) {\n throw new KeyProviderError(\n `Failed to write private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_WRITE_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-FKP06] Checks if a private key exists for an actor.\n */\n async hasPrivateKey(actorId: string): Promise<boolean> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n await fs.access(keyPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * [EARS-KP04] Deletes the private key for an actor.\n */\n async deletePrivateKey(actorId: string): Promise<boolean> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n await fs.unlink(keyPath);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File didn't exist\n return false;\n }\n\n throw new KeyProviderError(\n `Failed to delete private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_DELETE_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-FKP04] Builds the key file path, sanitizing actorId to prevent path traversal.\n * [EARS-FKP05] Replaces slashes with underscores.\n */\n private getKeyPath(actorId: string): string {\n // Sanitize actorId to prevent path traversal attacks\n const sanitized = this.sanitizeActorId(actorId);\n return path.join(this.actorsDir, `${sanitized}${this.extension}`);\n }\n\n /**\n * [EARS-FKP04] Sanitizes actorId to prevent directory traversal.\n * [EARS-FKP05] Replaces path separators with underscores.\n * [EARS-FKP09] Throws INVALID_ACTOR_ID for empty actorId.\n */\n private sanitizeActorId(actorId: string): string {\n // Remove path traversal attempts\n let sanitized = actorId\n .replace(/\\.\\./g, '') // Remove ..\n .replace(/[/\\\\]/g, '_'); // Replace path separators with underscore\n\n // Validate result is not empty\n if (!sanitized || sanitized === '') {\n throw new KeyProviderError(\n 'Invalid actorId: empty after sanitization',\n 'INVALID_ACTOR_ID',\n actorId\n );\n }\n\n return sanitized;\n }\n\n /**\n * Sanitizes actorId for logging (removes potential secrets).\n */\n private sanitizeForLog(actorId: string): string {\n // Just show first part for privacy\n if (actorId.length > 20) {\n return actorId.substring(0, 20) + '...';\n }\n return actorId;\n }\n}\n","/**\n * Error codes for FileLister operations.\n */\nexport type FileListerErrorCode =\n | 'FILE_NOT_FOUND'\n | 'READ_ERROR'\n | 'PERMISSION_DENIED'\n | 'INVALID_PATH';\n\n/**\n * Error thrown when file operations fail.\n */\nexport class FileListerError extends Error {\n constructor(\n message: string,\n public readonly code: FileListerErrorCode,\n public readonly filePath?: string\n ) {\n super(message);\n this.name = 'FileListerError';\n }\n}\n","/**\n * FsFileLister - Filesystem-based FileLister implementation\n *\n * Uses fast-glob for pattern matching and fs/promises for file operations.\n * Used in CLI and development environments.\n *\n * @module file_lister/fs/fs_file_lister\n */\n\nimport fg from 'fast-glob';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { FileLister, FileListOptions, FileStats, FsFileListerOptions } from '../file_lister';\nimport { FileListerError } from '../file_lister';\n\n/**\n * Filesystem-based FileLister implementation.\n * Uses fast-glob for pattern matching and fs/promises for file operations.\n *\n * @example\n * ```typescript\n * const lister = new FsFileLister({ cwd: '/path/to/project' });\n * const files = await lister.list(['**\\/*.ts'], { ignore: ['node_modules/**'] });\n * const content = await lister.read('src/index.ts');\n * ```\n */\nexport class FsFileLister implements FileLister {\n private readonly cwd: string;\n\n constructor(options: FsFileListerOptions) {\n this.cwd = options.cwd;\n }\n\n /**\n * [EARS-FL01] Lists files matching glob patterns.\n * [EARS-FFL01] Excludes files matching ignore patterns.\n */\n async list(patterns: string[], options?: FileListOptions): Promise<string[]> {\n // [EARS-FFL04] Validate patterns don't contain path traversal\n // [EARS-FFL05] Validate patterns are not absolute paths\n for (const pattern of patterns) {\n if (pattern.includes('..')) {\n throw new FileListerError(\n `Invalid pattern: path traversal not allowed: ${pattern}`,\n 'INVALID_PATH',\n pattern\n );\n }\n if (path.isAbsolute(pattern)) {\n throw new FileListerError(\n `Invalid pattern: absolute paths not allowed: ${pattern}`,\n 'INVALID_PATH',\n pattern\n );\n }\n }\n\n const fgOptions: Parameters<typeof fg>[1] = {\n cwd: this.cwd,\n ignore: options?.ignore ?? [],\n onlyFiles: options?.onlyFiles ?? true,\n absolute: options?.absolute ?? false,\n dot: true,\n };\n\n // Only add deep if maxDepth is specified\n if (options?.maxDepth !== undefined) {\n fgOptions.deep = options.maxDepth;\n }\n\n return fg(patterns, fgOptions);\n }\n\n /**\n * [EARS-FL02] Checks if a file exists.\n */\n async exists(filePath: string): Promise<boolean> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n try {\n const fullPath = path.join(this.cwd, filePath);\n await fs.access(fullPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * [EARS-FL03] Reads file content as string.\n * [EARS-FFL03] Throws FILE_NOT_FOUND for missing files.\n */\n async read(filePath: string): Promise<string> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n const fullPath = path.join(this.cwd, filePath);\n try {\n return await fs.readFile(fullPath, 'utf-8');\n } catch (err: unknown) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n throw new FileListerError(\n `File not found: ${filePath}`,\n 'FILE_NOT_FOUND',\n filePath\n );\n }\n if (error.code === 'EACCES') {\n throw new FileListerError(\n `Permission denied: ${filePath}`,\n 'PERMISSION_DENIED',\n filePath\n );\n }\n throw new FileListerError(\n `Read error: ${error.message}`,\n 'READ_ERROR',\n filePath\n );\n }\n }\n\n /**\n * [EARS-FL04] Gets file statistics.\n * [EARS-FFL03] Throws FILE_NOT_FOUND for missing files.\n */\n async stat(filePath: string): Promise<FileStats> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n const fullPath = path.join(this.cwd, filePath);\n try {\n const stats = await fs.stat(fullPath);\n return {\n size: stats.size,\n mtime: stats.mtimeMs,\n isFile: stats.isFile(),\n };\n } catch (err: unknown) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n throw new FileListerError(\n `File not found: ${filePath}`,\n 'FILE_NOT_FOUND',\n filePath\n );\n }\n throw new FileListerError(\n `Stat error: ${error.message}`,\n 'READ_ERROR',\n filePath\n );\n }\n }\n\n /**\n * [EARS-FFL04] Validates that the path doesn't contain traversal characters.\n * [EARS-FFL05] Validates that the path is not absolute.\n */\n private validatePath(filePath: string): void {\n if (filePath.includes('..')) {\n throw new FileListerError(\n `Invalid path: path traversal not allowed: ${filePath}`,\n 'INVALID_PATH',\n filePath\n );\n }\n // [EARS-FFL05] Prevent absolute paths to avoid escaping cwd\n if (path.isAbsolute(filePath)) {\n throw new FileListerError(\n `Invalid path: absolute paths not allowed: ${filePath}`,\n 'INVALID_PATH',\n filePath\n );\n }\n }\n}\n","/**\n * Lightweight Type Guards for GitGov Record Payloads\n *\n * These type guards are for narrowing already-validated GitGovRecordPayload unions.\n * They check structural properties, NOT schema validation.\n *\n * For schema validation (with AJV), use validators in validation/*.ts:\n * - isTaskRecord(unknown) in task_validator.ts\n * - isCycleRecord(unknown) in cycle_validator.ts\n * etc.\n *\n * @module types/type_guards\n */\n\nimport type {\n GitGovRecordPayload,\n TaskRecord,\n CycleRecord,\n ExecutionRecord,\n ActorRecord,\n AgentRecord,\n ChangelogRecord,\n FeedbackRecord\n} from './index';\n\n/**\n * Type guard: checks if payload is a TaskRecord.\n * Verifies presence of task-specific fields: title, status, priority, description.\n */\nexport function isTaskPayload(payload: GitGovRecordPayload): payload is TaskRecord {\n return 'title' in payload && 'status' in payload && 'priority' in payload && 'description' in payload;\n}\n\n/**\n * Type guard: checks if payload is a CycleRecord.\n * Verifies presence of cycle-specific fields: title, status (but NOT priority).\n */\nexport function isCyclePayload(payload: GitGovRecordPayload): payload is CycleRecord {\n return 'title' in payload && 'status' in payload && !('priority' in payload);\n}\n\n/**\n * Type guard: checks if payload is an ExecutionRecord.\n * Verifies presence of execution-specific fields: taskId, title, type, result.\n */\nexport function isExecutionPayload(payload: GitGovRecordPayload): payload is ExecutionRecord {\n return 'taskId' in payload && 'title' in payload && 'type' in payload && 'result' in payload;\n}\n\n/**\n * Type guard: checks if payload is an ActorRecord.\n * Verifies presence of actor-specific fields: displayName, publicKey, roles, type.\n */\nexport function isActorPayload(payload: GitGovRecordPayload): payload is ActorRecord {\n return 'displayName' in payload && 'publicKey' in payload && 'roles' in payload && 'type' in payload;\n}\n\n/**\n * Type guard: checks if payload is an AgentRecord (agent manifest).\n * Verifies presence of agent-specific field: engine.\n * Note: AgentRecord is a manifest, different from ActorRecord with type='agent'.\n */\nexport function isAgentPayload(payload: GitGovRecordPayload): payload is AgentRecord {\n return 'engine' in payload;\n}\n\n/**\n * Type guard: checks if payload is a ChangelogRecord.\n * Verifies presence of changelog-specific fields: title, description, relatedTasks, completedAt.\n */\nexport function isChangelogPayload(payload: GitGovRecordPayload): payload is ChangelogRecord {\n return 'title' in payload && 'description' in payload && 'relatedTasks' in payload && 'completedAt' in payload;\n}\n\n/**\n * Type guard: checks if payload is a FeedbackRecord.\n * Verifies presence of feedback-specific fields: entityType, entityId, type, status, content.\n */\nexport function isFeedbackPayload(payload: GitGovRecordPayload): payload is FeedbackRecord {\n return 'entityType' in payload && 'entityId' in payload && 'type' in payload && 'status' in payload && 'content' in payload;\n}\n","/**\n * ID Parsing Utilities for GitGov Records\n *\n * Functions for extracting information from record IDs and file paths.\n * Complements id_generator.ts (which creates IDs).\n *\n * @module utils/id_parser\n */\n\nimport type { GitGovRecordType } from '../record_types';\n\n/**\n * Mapping from directory names to entity types.\n */\nconst DIR_TO_TYPE: Record<string, Exclude<GitGovRecordType, 'custom'>> = {\n 'tasks': 'task',\n 'cycles': 'cycle',\n 'executions': 'execution',\n 'changelogs': 'changelog',\n 'feedbacks': 'feedback',\n 'actors': 'actor',\n 'agents': 'agent'\n};\n\n/**\n * Valid directory names for GitGov records.\n */\nconst VALID_DIRS = Object.keys(DIR_TO_TYPE);\n\n/**\n * Extracts the record ID from a file path.\n *\n * @param filePath - Path to a record file (e.g., '.gitgov/tasks/123-task-foo.json')\n * @returns The record ID without extension (e.g., '123-task-foo')\n *\n * @example\n * extractRecordIdFromPath('.gitgov/tasks/123-task-foo.json') // '123-task-foo'\n * extractRecordIdFromPath('/abs/path/.gitgov/actors/human_dev.json') // 'human_dev'\n */\nexport function extractRecordIdFromPath(filePath: string): string {\n const parts = filePath.split('/');\n const filename = parts[parts.length - 1] || '';\n return filename.replace('.json', '');\n}\n\n/**\n * Extracts the entity type from a file path based on directory name.\n *\n * @param filePath - Path to a record file (e.g., '.gitgov/tasks/123.json')\n * @returns The entity type or null if not found\n *\n * @example\n * getEntityTypeFromPath('.gitgov/tasks/123.json') // 'task'\n * getEntityTypeFromPath('.gitgov/actors/human_dev.json') // 'actor'\n * getEntityTypeFromPath('/some/other/path.json') // null\n */\nexport function getEntityTypeFromPath(filePath: string): Exclude<GitGovRecordType, 'custom'> | null {\n const pathParts = filePath.split('/');\n const typeDirIndex = pathParts.findIndex(part => VALID_DIRS.includes(part));\n\n if (typeDirIndex >= 0) {\n const dirName = pathParts[typeDirIndex];\n return dirName ? DIR_TO_TYPE[dirName] || null : null;\n }\n\n return null;\n}\n\n/**\n * Infers the entity type from a record ID pattern.\n *\n * Uses ID naming conventions:\n * - `{timestamp}-exec-*` or `*-execution-*` → execution\n * - `{timestamp}-changelog-*` → changelog\n * - `{timestamp}-feedback-*` → feedback\n * - `{timestamp}-cycle-*` or `cycle:*` → cycle\n * - `{timestamp}-task-*` or `task:*` → task\n * - `human:*` or `human_*` → actor\n * - `agent:*` or `agent_*` → agent\n *\n * @param recordId - The record ID to analyze\n * @returns The inferred entity type (defaults to 'task' if unknown)\n *\n * @example\n * inferEntityTypeFromId('1234567890-exec-commit') // 'execution'\n * inferEntityTypeFromId('human:developer') // 'actor'\n * inferEntityTypeFromId('agent:code-reviewer') // 'agent'\n * inferEntityTypeFromId('1234567890-task-implement-auth') // 'task'\n */\nexport function inferEntityTypeFromId(recordId: string): Exclude<GitGovRecordType, 'custom'> {\n // Execution patterns\n if (recordId.match(/^\\d+-exec-/) || recordId.includes('-execution-')) {\n return 'execution';\n }\n\n // Changelog pattern\n if (recordId.match(/^\\d+-changelog-/)) {\n return 'changelog';\n }\n\n // Feedback pattern\n if (recordId.match(/^\\d+-feedback-/)) {\n return 'feedback';\n }\n\n // Cycle patterns\n if (recordId.match(/^\\d+-cycle-/) || recordId.startsWith('cycle:')) {\n return 'cycle';\n }\n\n // Task patterns\n if (recordId.match(/^\\d+-task-/) || recordId.startsWith('task:')) {\n return 'task';\n }\n\n // Actor patterns (human)\n if (recordId.startsWith('human:') || recordId.startsWith('human_')) {\n return 'actor';\n }\n\n // Agent patterns\n if (recordId.startsWith('agent:') || recordId.startsWith('agent_')) {\n return 'agent';\n }\n\n // Default to task\n return 'task';\n}\n\n/**\n * Valid prefixes for timestamp-based record IDs.\n */\nconst VALID_PREFIXES = ['task', 'cycle', 'exec', 'changelog', 'feedback'] as const;\n\n/**\n * Parses a timestamp-based record ID (e.g., '12345-task-slug') into its components.\n *\n * @param id - The record ID to parse\n * @returns Parsed components or null if invalid format\n *\n * @example\n * parseTimestampedId('1234567890-task-implement-auth')\n * // { timestamp: 1234567890, prefix: 'task', slug: 'implement-auth' }\n */\nexport function parseTimestampedId(id: string): { timestamp: number; prefix: string; slug: string } | null {\n if (typeof id !== 'string') return null;\n const match = id.match(/^(\\d+)-(\\w+)-(.+)$/);\n if (!match || !match[1] || !match[2] || !match[3]) {\n return null;\n }\n return {\n timestamp: parseInt(match[1], 10),\n prefix: match[2],\n slug: match[3],\n };\n}\n\n/**\n * Parses an Actor ID (e.g., 'human:camilo') into its components.\n *\n * @param id - The actor ID to parse\n * @returns Parsed components or null if invalid format\n *\n * @example\n * parseActorId('human:camilo-velandia') // { type: 'human', slug: 'camilo-velandia' }\n * parseActorId('agent:code-reviewer') // { type: 'agent', slug: 'code-reviewer' }\n */\nexport function parseActorId(id: string): { type: 'human' | 'agent'; slug: string } | null {\n if (typeof id !== 'string') return null;\n const parts = id.split(':');\n if (parts.length < 2 || (parts[0] !== 'human' && parts[0] !== 'agent')) {\n return null;\n }\n const type = parts[0] as 'human' | 'agent';\n const slug = parts.slice(1).join(':'); // Re-join in case slug contains ':'\n return { type, slug };\n}\n\n/**\n * Validates the format of a timestamp-based record ID.\n *\n * @param id - The record ID to validate\n * @returns True if valid format, false otherwise\n *\n * @example\n * isValidTimestampedId('12345-task-valid-slug') // true\n * isValidTimestampedId('123-badprefix-slug') // false\n */\nexport function isValidTimestampedId(id: string): boolean {\n const parsed = parseTimestampedId(id);\n if (!parsed) return false;\n\n // Check if prefix is valid and slug is not empty\n return VALID_PREFIXES.includes(parsed.prefix as typeof VALID_PREFIXES[number]) && parsed.slug.length > 0;\n}\n","/**\n * Array Utility Functions\n *\n * Generic helpers for array manipulation.\n *\n * @module utils/array_utils\n */\n\n/**\n * Splits an array into chunks of a specified size.\n *\n * @param array - The array to split\n * @param size - Maximum size of each chunk\n * @returns Array of chunks\n *\n * @example\n * chunkArray([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]\n * chunkArray(['a', 'b', 'c'], 3) // [['a', 'b', 'c']]\n * chunkArray([], 5) // []\n */\nexport function chunkArray<T>(array: T[], size: number): T[][] {\n if (size <= 0) {\n throw new Error('Chunk size must be greater than 0');\n }\n\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n}\n","export type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\nexport interface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n}\n\nclass ConsoleLogger implements Logger {\n private level: LogLevel;\n private prefix: string;\n\n constructor(prefix: string = \"\", level: LogLevel = \"info\") {\n this.prefix = prefix;\n this.level = level;\n }\n\n private shouldLog(level: LogLevel): boolean {\n const levels: LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\", \"silent\"];\n const currentLevelIndex = levels.indexOf(this.level);\n const messageLevelIndex = levels.indexOf(level);\n\n return currentLevelIndex <= messageLevelIndex && this.level !== \"silent\";\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.shouldLog(\"debug\")) {\n console.log(`${this.prefix}${message}`, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.shouldLog(\"info\")) {\n console.log(`${this.prefix}${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.shouldLog(\"warn\")) {\n console.warn(`${this.prefix}${message}`, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (this.shouldLog(\"error\")) {\n console.error(`${this.prefix}${message}`, ...args);\n }\n }\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n}\n\n// Factory function para crear loggers\nexport function createLogger(prefix: string = \"\", level?: LogLevel): Logger {\n const logLevel = level ||\n (process.env['NODE_ENV'] === \"test\" ? \"silent\" : \"info\") ||\n (process.env['LOG_LEVEL'] as LogLevel) ||\n \"info\";\n\n return new ConsoleLogger(prefix, logLevel);\n}\n\n// Logger global para uso directo\nexport const logger = createLogger(\"[App] \"); ","import { createHash } from \"crypto\";\nimport type { GitGovRecordPayload } from \"../record_types\";\n\n/**\n * Recursively sorts the keys of an object, including nested objects.\n * This is the core of canonical serialization.\n * @param obj The object to sort.\n * @returns A new object with all keys sorted alphabetically.\n */\nfunction sortKeys(obj: any): any {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n const sortedKeys = Object.keys(obj).sort();\n const newObj: Record<string, any> = {};\n for (const key of sortedKeys) {\n newObj[key] = sortKeys(obj[key]);\n }\n return newObj;\n}\n\n/**\n * Canonically serializes a payload object.\n * @param payload The object to serialize.\n * @returns A deterministic JSON string.\n */\nfunction canonicalize(payload: object): string {\n const sortedPayload = sortKeys(payload);\n return JSON.stringify(sortedPayload);\n}\n\n/**\n * Calculates the SHA-256 checksum of a record's payload.\n */\nexport function calculatePayloadChecksum(payload: GitGovRecordPayload): string {\n const jsonString = canonicalize(payload);\n return createHash(\"sha256\").update(jsonString, \"utf8\").digest(\"hex\");\n} ","import type { ActorRecord } from \"./\";\nimport type { AgentRecord } from \"./\";\nimport type { CycleRecord } from \"./\";\nimport type { TaskRecord } from \"./\";\nimport type { ExecutionRecord } from \"./\";\nimport type { ChangelogRecord } from \"./\";\nimport type { FeedbackRecord } from \"./\";\nimport type { EmbeddedMetadataRecord } from \"./embedded.types\";\n\n/**\n * A custom record type for testing purposes.\n */\nexport type CustomRecord = {\n type: 'custom';\n data: unknown;\n}\n\n/**\n * Defines the possible 'type' values for any record in the system.\n */\nexport type GitGovRecordType =\n | \"actor\"\n | \"agent\"\n | \"cycle\"\n | \"task\"\n | \"execution\"\n | \"changelog\"\n | \"feedback\"\n | \"custom\";\n\n/**\n * The canonical payload for any GitGovernance record.\n */\nexport type GitGovRecordPayload =\n | ActorRecord\n | AgentRecord\n | CycleRecord\n | TaskRecord\n | ExecutionRecord\n | ChangelogRecord\n | FeedbackRecord\n | CustomRecord;\n\n/**\n * The canonical type for any record in GitGovernance, wrapping a payload with metadata.\n */\nexport type GitGovRecord = EmbeddedMetadataRecord<GitGovRecordPayload>;\n\n/**\n * Specific GitGov record types with full metadata (header + payload).\n * These types provide clean, type-safe access to records with their signatures and checksums.\n * \n * @example\n * const taskRecord: GitGovTaskRecord = await taskStore.read(taskId);\n * const authorId = taskRecord.header.signatures[0].keyId;\n */\nexport type GitGovTaskRecord = EmbeddedMetadataRecord<TaskRecord>;\nexport type GitGovCycleRecord = EmbeddedMetadataRecord<CycleRecord>;\nexport type GitGovFeedbackRecord = EmbeddedMetadataRecord<FeedbackRecord>;\nexport type GitGovExecutionRecord = EmbeddedMetadataRecord<ExecutionRecord>;\nexport type GitGovChangelogRecord = EmbeddedMetadataRecord<ChangelogRecord>;\nexport type GitGovActorRecord = EmbeddedMetadataRecord<ActorRecord>;\nexport type GitGovAgentRecord = EmbeddedMetadataRecord<AgentRecord>;\n\n// Payloads for creating new records\nexport type ActorPayload = Partial<ActorRecord>;\nexport type AgentPayload = Partial<AgentRecord>;\nexport type CyclePayload = Partial<CycleRecord>;\nexport type TaskPayload = Partial<TaskRecord>;\nexport type ExecutionPayload = Partial<ExecutionRecord>;\nexport type ChangelogPayload = Partial<ChangelogRecord>;\nexport type FeedbackPayload = Partial<FeedbackRecord>;\n\n/**\n * Base class for all GitGovernance-specific errors.\n * Centralized here as it's used across multiple modules (schemas, validation, etc.)\n */\nexport class GitGovError extends Error {\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n\n","/**\n * Schema-specific error types for GitGovernance core.\n * These errors are thrown during JSON Schema validation and compilation.\n */\n\n// Import GitGovError from models (common types) - no circular dependencies\nimport { GitGovError } from '../record_types/common.types';\n\n// Re-export for backward compatibility\nexport { GitGovError };\n\n/**\n * Custom Error type for failures related to JSON Schema validation.\n */\nexport class SchemaValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/**\n * Error for detailed AJV validation failures with multiple field errors.\n */\nexport class DetailedValidationError extends GitGovError {\n constructor(\n recordType: string,\n public readonly errors: Array<{\n field: string;\n message: string;\n value: unknown;\n }>\n ) {\n const errorSummary = errors\n .map(err => `${err.field}: ${err.message}`)\n .join(', ');\n\n super(\n `${recordType} validation failed: ${errorSummary}`,\n 'DETAILED_VALIDATION_ERROR'\n );\n }\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"actor_record_schema.json\",\n \"title\": \"ActorRecord\",\n \"description\": \"Canonical schema for actor records as defined in actor_protocol.md\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"type\",\n \"displayName\",\n \"publicKey\",\n \"roles\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"Unique, human-readable identifier for the actor.\",\n \"examples\": [\n \"human:camilo\",\n \"agent:aion\",\n \"agent:camilo:cursor\"\n ]\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"human\",\n \"agent\"\n ],\n \"description\": \"The type of actor.\"\n },\n \"displayName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100,\n \"description\": \"The name of the actor to be used in user interfaces.\"\n },\n \"publicKey\": {\n \"type\": \"string\",\n \"minLength\": 44,\n \"maxLength\": 44,\n \"description\": \"The Ed25519 public key (base64 encoded, 44 characters) for verifying the actor's signatures.\"\n },\n \"roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"minItems\": 1,\n \"uniqueItems\": true,\n \"description\": \"List of capacity roles defining the actor's skills and permissions. Uses hierarchical format with colons.\",\n \"examples\": [\n [\n \"developer:backend:go\",\n \"auditor\"\n ],\n [\n \"planner:ai\"\n ]\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"active\",\n \"revoked\"\n ],\n \"default\": \"active\",\n \"description\": \"Optional. The lifecycle status of the actor. Defaults to 'active' if not specified.\"\n },\n \"supersededBy\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"Optional. The ID of the actor that replaces this one.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"description\": \"An optional field for additional, non-canonical metadata.\",\n \"examples\": [\n {\n \"version\": \"1.2.0\",\n \"source\": \"https://github.com/...\"\n },\n {\n \"team\": \"frontend\"\n }\n ]\n }\n }\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"agent_record_schema.json\",\n \"title\": \"AgentRecord\",\n \"description\": \"Canonical schema for agent operational manifests.\",\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"engine\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^agent:[a-z0-9:-]+$\",\n \"description\": \"Unique identifier for the agent, linking to an ActorRecord.\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"active\",\n \"archived\"\n ],\n \"default\": \"active\"\n },\n \"triggers\": {\n \"type\": \"array\",\n \"default\": [],\n \"description\": \"Optional list of triggers that activate the agent.\\nAdditional fields are allowed and depend on trigger type:\\n- webhook triggers: 'event' (event identifier), 'filter' (condition)\\n- scheduled triggers: 'cron' (cron expression)\\n- manual triggers: 'command' (example CLI command)\\n\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"manual\",\n \"webhook\",\n \"scheduled\"\n ],\n \"description\": \"Type of trigger that activates the agent\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": true\n }\n },\n \"knowledge_dependencies\": {\n \"type\": \"array\",\n \"default\": [],\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Glob patterns for blueprint files this agent needs access to\"\n }\n },\n \"prompt_engine_requirements\": {\n \"type\": \"object\",\n \"properties\": {\n \"roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"skills\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"metadata\": {\n \"type\": \"object\",\n \"description\": \"Optional framework-specific or deployment-specific metadata for agent extensions.\\nCommon use cases: framework identification (langchain, google-adk), deployment info (provider, image, region),\\ncost tracking (cost_per_invocation, currency), tool capabilities, maintainer info.\\nThis field does NOT affect agent execution - it is purely informational.\\n\",\n \"additionalProperties\": true\n },\n \"engine\": {\n \"type\": \"object\",\n \"oneOf\": [\n {\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"local\"\n },\n \"runtime\": {\n \"type\": \"string\",\n \"description\": \"Runtime environment (typescript, python, etc.)\"\n },\n \"entrypoint\": {\n \"type\": \"string\",\n \"description\": \"Path to the agent entry file\"\n },\n \"function\": {\n \"type\": \"string\",\n \"description\": \"Function name to invoke\"\n }\n }\n },\n {\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"api\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"HTTP endpoint for the agent\"\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"POST\",\n \"GET\",\n \"PUT\"\n ],\n \"default\": \"POST\"\n },\n \"auth\": {\n \"type\": \"object\",\n \"description\": \"Authentication configuration for API requests\",\n \"additionalProperties\": true,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"bearer\",\n \"oauth\",\n \"api-key\",\n \"actor-signature\"\n ],\n \"description\": \"Authentication type. 'actor-signature' uses the agent's ActorRecord keypair to sign requests.\"\n },\n \"secret_key\": {\n \"type\": \"string\",\n \"description\": \"Reference to secret in Secret Manager (for bearer/api-key/oauth auth types)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Direct token value (not recommended for production, use secret_key instead)\"\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"mcp\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"MCP server endpoint\"\n },\n \"tool\": {\n \"type\": \"string\",\n \"description\": \"Name of the MCP tool to invoke. If not specified, defaults to agentId without 'agent:' prefix.\"\n },\n \"auth\": {\n \"type\": \"object\",\n \"description\": \"Authentication configuration for MCP server\",\n \"additionalProperties\": true,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"bearer\",\n \"oauth\",\n \"api-key\",\n \"actor-signature\"\n ],\n \"description\": \"Authentication type. 'actor-signature' uses the agent's ActorRecord keypair to sign requests.\"\n },\n \"secret_key\": {\n \"type\": \"string\",\n \"description\": \"Reference to secret in Secret Manager (for bearer/api-key/oauth auth types)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Direct token value (not recommended for production, use secret_key instead)\"\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"custom\"\n },\n \"protocol\": {\n \"type\": \"string\",\n \"description\": \"Custom protocol identifier (e.g., 'a2a', 'grpc')\"\n },\n \"config\": {\n \"type\": \"object\",\n \"description\": \"Protocol-specific configuration\"\n }\n }\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"agent:scribe\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"local\",\n \"runtime\": \"typescript\",\n \"entrypoint\": \"packages/agents/scribe/index.ts\",\n \"function\": \"runScribe\"\n },\n \"metadata\": {\n \"purpose\": \"documentation-generation\",\n \"maintainer\": \"team:platform\"\n },\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ],\n \"knowledge_dependencies\": [\n \"packages/blueprints/**/*.md\"\n ]\n },\n {\n \"id\": \"agent:langchain-analyzer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"https://langchain-service-xyz.a.run.app/analyze\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"framework\": \"langchain\",\n \"version\": \"0.2.0\",\n \"model\": \"gpt-4-turbo\",\n \"deployment\": {\n \"provider\": \"gcp\",\n \"service\": \"cloud-run\",\n \"region\": \"us-central1\"\n },\n \"cost_per_invocation\": 0.03,\n \"currency\": \"USD\"\n },\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"task.ready\"\n }\n ],\n \"knowledge_dependencies\": [\n \"docs/architecture/**/*.md\"\n ]\n },\n {\n \"id\": \"agent:sentiment-analyzer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"http://sentiment-analyzer:8082/analyze\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"framework\": \"google-adk\",\n \"version\": \"1.0.0\",\n \"model\": \"gemini-pro\",\n \"deployment\": {\n \"runtime\": \"docker\",\n \"image\": \"gitgov/sentiment-analyzer:v1.2.0\",\n \"port\": 8082\n },\n \"max_tokens\": 1024\n },\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"feedback.created\"\n }\n ]\n },\n {\n \"id\": \"agent:cursor-reviewer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"mcp\",\n \"url\": \"http://localhost:8083/mcp\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"ide\": \"cursor\",\n \"tool\": \"code-review\",\n \"accepts_tools\": [\n \"review\",\n \"refactor\",\n \"test\"\n ]\n },\n \"knowledge_dependencies\": [\n \"packages/**/*.ts\",\n \"packages/**/*.tsx\"\n ],\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"task.status.ready\"\n }\n ]\n },\n {\n \"id\": \"agent:deepl-translator\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"https://api.deepl.com/v2/translate\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"bearer\",\n \"secret_key\": \"DEEPL_API_KEY\"\n }\n },\n \"metadata\": {\n \"provider\": \"deepl\",\n \"supported_languages\": [\n \"EN\",\n \"ES\",\n \"FR\",\n \"DE\",\n \"PT\"\n ],\n \"max_chars_per_request\": 5000\n },\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ]\n },\n {\n \"id\": \"agent:coordinator\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"custom\",\n \"protocol\": \"a2a\",\n \"config\": {\n \"endpoint\": \"https://agent-hub.gitgov.io/a2a\",\n \"version\": \"draft-2025-01\",\n \"capabilities\": [\n \"task-delegation\",\n \"status-sync\",\n \"feedback-loop\"\n ]\n }\n },\n \"metadata\": {\n \"purpose\": \"multi-agent-orchestration\",\n \"experimental\": true\n },\n \"triggers\": [\n {\n \"type\": \"scheduled\",\n \"cron\": \"0 */4 * * *\"\n }\n ]\n },\n {\n \"id\": \"agent:minimal-watcher\",\n \"engine\": {\n \"type\": \"local\"\n }\n },\n {\n \"id\": \"agent:local-mcp-server\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"mcp\",\n \"url\": \"http://localhost:9000/mcp\"\n },\n \"knowledge_dependencies\": [\n \"packages/blueprints/**/*.md\"\n ],\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ]\n },\n {\n \"id\": \"agent:code-reviewer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"local\",\n \"runtime\": \"typescript\",\n \"entrypoint\": \"packages/agents/code-reviewer/index.ts\",\n \"function\": \"reviewCode\"\n },\n \"prompt_engine_requirements\": {\n \"roles\": [\n \"code-reviewer\",\n \"security-auditor\"\n ],\n \"skills\": [\n \"typescript\",\n \"security-best-practices\",\n \"code-quality-analysis\"\n ]\n },\n \"knowledge_dependencies\": [\n \"packages/**/*.ts\",\n \"packages/**/*.tsx\"\n ],\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"pull-request.opened\",\n \"filter\": \"branch:main\"\n }\n ]\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"changelog_record_schema.json\",\n \"title\": \"ChangelogRecord\",\n \"description\": \"Canonical schema for changelog records - aggregates N tasks into 1 release note\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"description\",\n \"relatedTasks\",\n \"completedAt\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-changelog-[a-z0-9-]{1,50}$\",\n \"maxLength\": 71,\n \"description\": \"Unique identifier for the changelog entry\",\n \"examples\": [\n \"1752707800-changelog-sistema-autenticacion-v1\",\n \"1752707800-changelog-sprint-24-api-performance\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 150,\n \"description\": \"Executive title of the deliverable\",\n \"examples\": [\n \"Sistema de Autenticación Completo v1.0\",\n \"Sprint 24 - Performance Optimizations\"\n ]\n },\n \"description\": {\n \"type\": \"string\",\n \"minLength\": 20,\n \"maxLength\": 5000,\n \"description\": \"Detailed description of the value delivered, including key decisions and impact\"\n },\n \"relatedTasks\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\"\n },\n \"minItems\": 1,\n \"description\": \"IDs of tasks that compose this deliverable (minimum 1 required)\"\n },\n \"completedAt\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"description\": \"Unix timestamp in seconds when the deliverable was completed\"\n },\n \"relatedCycles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\"\n },\n \"default\": [],\n \"description\": \"Optional IDs of cycles related to this deliverable\"\n },\n \"relatedExecutions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-exec-[a-z0-9-]{1,50}$\"\n },\n \"default\": [],\n \"description\": \"Optional IDs of key execution records related to this work\"\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 50,\n \"description\": \"Optional version or release identifier (e.g., 'v1.0.0', 'sprint-24')\",\n \"examples\": [\n \"v1.0.0\",\n \"v2.1.3\",\n \"sprint-24\"\n ]\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"default\": [],\n \"description\": \"Optional tags for categorization (e.g., 'feature:auth', 'bugfix', 'security')\"\n },\n \"commits\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 100\n },\n \"default\": [],\n \"description\": \"Optional list of git commit hashes related to this deliverable\"\n },\n \"files\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Optional list of main files that were created or modified\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"maxLength\": 3000,\n \"description\": \"Optional additional context, decisions, or learnings\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1752707800-changelog-sistema-autenticacion-v1\",\n \"title\": \"Sistema de Autenticación Completo v1.0\",\n \"description\": \"Implementación completa del sistema de autenticación con OAuth2, 2FA via TOTP, recuperación de contraseña, y UI responsive. Incluye tests E2E completos (95% coverage) y documentación técnica actualizada.\",\n \"relatedTasks\": [\n \"1752274500-task-crear-ui-login\",\n \"1752274600-task-integrar-oauth2-backend\",\n \"1752274700-task-implementar-2fa-totp\",\n \"1752274800-task-tests-e2e-auth\",\n \"1752274900-task-documentar-flujo-auth\"\n ],\n \"completedAt\": 1752707800,\n \"relatedCycles\": [\n \"1752200000-cycle-q1-auth-milestone\"\n ],\n \"relatedExecutions\": [\n \"1752274550-exec-analisis-auth-providers\",\n \"1752707750-exec-final-integration-test\"\n ],\n \"version\": \"v1.0.0\",\n \"tags\": [\n \"feature:auth\",\n \"security\",\n \"frontend\",\n \"backend\"\n ],\n \"commits\": [\n \"abc123def\",\n \"456ghi789\",\n \"jkl012mno\"\n ],\n \"files\": [\n \"src/pages/Login.tsx\",\n \"src/services/auth.ts\",\n \"src/components/TwoFactorSetup.tsx\",\n \"e2e/auth.spec.ts\"\n ],\n \"notes\": \"Decisión técnica: Usamos NextAuth.js después de evaluar Passport.js. El 2FA se implementó con TOTP (Google Authenticator compatible) en lugar de SMS por seguridad y costo.\"\n },\n {\n \"id\": \"1752707900-changelog-hotfix-payment-timeout\",\n \"title\": \"Hotfix: Critical Payment Timeout Fix\",\n \"description\": \"Fixed critical payment timeout issue affecting 15% of transactions. Increased timeout from 5s to 30s and added circuit breaker pattern for third-party API calls.\",\n \"relatedTasks\": [\n \"1752707850-task-fix-payment-timeout\",\n \"1752707870-task-add-circuit-breaker\"\n ],\n \"completedAt\": 1752707900,\n \"version\": \"v1.2.1\",\n \"tags\": [\n \"hotfix\",\n \"critical\",\n \"payment\"\n ],\n \"commits\": [\n \"xyz789abc\"\n ],\n \"notes\": \"Emergency response to production incident. Deployed to production within 2 hours.\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"cycle_record_schema.json\",\n \"title\": \"CycleRecord\",\n \"description\": \"Canonical schema for cycle records - strategic grouping of work\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"status\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67,\n \"description\": \"Unique identifier for the cycle (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\",\n \"examples\": [\n \"1754400000-cycle-sprint-24-api-performance\",\n \"1754500000-cycle-auth-system-v2\",\n \"1754600000-cycle-q4-2025-growth\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"Human-readable title for the cycle (e.g., 'Sprint 24', 'Auth v2.0', 'Q4 2025')\",\n \"examples\": [\n \"Sprint 24 - API Performance\",\n \"Authentication System v2.0\",\n \"Q4 2025 - Growth & Scale\"\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"planning\",\n \"active\",\n \"completed\",\n \"archived\"\n ],\n \"description\": \"The lifecycle status of the cycle\"\n },\n \"taskIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66\n },\n \"default\": [],\n \"description\": \"Optional array of Task IDs that belong to this cycle. Can be empty for cycles that only contain child cycles. (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n [\n \"1752274500-task-optimizar-endpoint-search\",\n \"1752360900-task-anadir-cache-a-redis\"\n ]\n ]\n },\n \"childCycleIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67\n },\n \"default\": [],\n \"description\": \"Optional array of Cycle IDs that are children of this cycle, allowing for hierarchies (e.g., Q1 containing Sprint 1, Sprint 2, Sprint 3). (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\",\n \"examples\": [\n [\n \"1754400000-cycle-sprint-24\",\n \"1754500000-cycle-sprint-25\"\n ]\n ]\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\",\n \"maxLength\": 100\n },\n \"default\": [],\n \"description\": \"Optional list of key:value tags for categorization (e.g., 'roadmap:q4', 'team:alpha', 'okr:growth').\",\n \"examples\": [\n [\n \"roadmap:q4\",\n \"team:backend\"\n ],\n [\n \"sprint:24\",\n \"focus:performance\"\n ],\n [\n \"milestone:v2\",\n \"security\"\n ]\n ]\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 0,\n \"maxLength\": 10000,\n \"description\": \"Optional description of the cycle's goals, objectives, and context\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1754400000-cycle-sprint-24-api-performance\",\n \"title\": \"Sprint 24 - API Performance\",\n \"status\": \"active\",\n \"taskIds\": [\n \"1752274500-task-optimizar-endpoint-search\",\n \"1752360900-task-anadir-cache-a-redis\",\n \"1752447300-task-implementar-rate-limiting\"\n ],\n \"tags\": [\n \"sprint:24\",\n \"team:backend\",\n \"focus:performance\"\n ],\n \"notes\": \"Objetivo: Reducir la latencia p95 de la API por debajo de 200ms y preparar infraestructura para Black Friday.\"\n },\n {\n \"id\": \"1754500000-cycle-auth-system-v2\",\n \"title\": \"Authentication System v2.0\",\n \"status\": \"planning\",\n \"taskIds\": [\n \"1752274500-task-oauth2-integration\",\n \"1752360900-task-2fa-implementation\",\n \"1752447300-task-password-recovery\",\n \"1752533700-task-session-management\"\n ],\n \"tags\": [\n \"milestone:v2\",\n \"security\",\n \"feature:auth\"\n ],\n \"notes\": \"Milestone mayor: Sistema completo de autenticación con OAuth2, 2FA, y gestión avanzada de sesiones. Crítico para lanzamiento Q4.\"\n },\n {\n \"id\": \"1754600000-cycle-q4-2025-growth\",\n \"title\": \"Q4 2025 - Growth & Scale\",\n \"status\": \"active\",\n \"childCycleIds\": [\n \"1754400000-cycle-sprint-24-api-performance\",\n \"1754500000-cycle-auth-system-v2\",\n \"1754650000-cycle-mobile-app-launch\"\n ],\n \"tags\": [\n \"roadmap:q4\",\n \"strategy:growth\",\n \"okr:scale-to-1m-users\"\n ],\n \"notes\": \"Objetivo trimestral: Escalar a 1M usuarios activos. Incluye mejoras de performance, nuevo sistema de auth, y lanzamiento de app móvil.\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"embedded_metadata_schema.json\",\n \"title\": \"EmbeddedMetadataRecord\",\n \"description\": \"Canonical schema for the wrapper structure of all GitGovernance records.\",\n \"type\": \"object\",\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"version\": {\n \"type\": \"string\",\n \"enum\": [\n \"1.0\"\n ],\n \"description\": \"Version of the embedded metadata format.\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"actor\",\n \"agent\",\n \"task\",\n \"execution\",\n \"changelog\",\n \"feedback\",\n \"cycle\",\n \"custom\"\n ],\n \"description\": \"The type of the record contained in the payload.\"\n },\n \"schemaUrl\": {\n \"type\": \"string\",\n \"description\": \"Optional URL to a custom schema for the payload.\"\n },\n \"schemaChecksum\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-fA-F0-9]{64}$\",\n \"description\": \"Optional SHA-256 checksum of the custom schema.\"\n },\n \"payloadChecksum\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-fA-F0-9]{64}$\",\n \"description\": \"SHA-256 checksum of the canonically serialized payload.\"\n },\n \"signatures\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"keyId\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"The Actor ID of the signer (must match ActorRecord.id pattern).\"\n },\n \"role\": {\n \"type\": \"string\",\n \"pattern\": \"^([a-z-]+|custom:[a-z0-9-]+)$\",\n \"minLength\": 1,\n \"maxLength\": 50,\n \"description\": \"The context role of the signature (e.g., 'author', 'reviewer', 'auditor', or 'custom:*').\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 1000,\n \"description\": \"Human-readable note from the signer. Part of the signature digest.\"\n },\n \"signature\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9+/]{86}==$\",\n \"description\": \"The Ed25519 signature (base64 encoded, 88 chars with padding) of the signature digest.\"\n },\n \"timestamp\": {\n \"type\": \"integer\",\n \"description\": \"Unix timestamp of the signature.\"\n }\n },\n \"required\": [\n \"keyId\",\n \"role\",\n \"notes\",\n \"signature\",\n \"timestamp\"\n ],\n \"additionalProperties\": false\n },\n \"description\": \"An array of one or more signature objects.\"\n }\n },\n \"required\": [\n \"version\",\n \"type\",\n \"payloadChecksum\",\n \"signatures\"\n ],\n \"additionalProperties\": false\n },\n \"payload\": {\n \"type\": \"object\",\n \"description\": \"The specific record data, validated against the schema defined by header.type.\"\n }\n },\n \"required\": [\n \"header\",\n \"payload\"\n ],\n \"additionalProperties\": false,\n \"oneOf\": [\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"actor\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:actor_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"agent\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:agent_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"task\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:task_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"execution\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:execution_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"changelog\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:changelog_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"feedback\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:feedback_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"cycle\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:cycle_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"custom\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"required\": [\n \"schemaUrl\",\n \"schemaChecksum\"\n ]\n }\n }\n },\n \"else\": false\n }\n ],\n \"examples\": [\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"task\",\n \"payloadChecksum\": \"a1b2c3d4e5f6...\",\n \"signatures\": [\n {\n \"keyId\": \"human:lead-dev\",\n \"role\": \"author\",\n \"notes\": \"Initial task creation for OAuth 2.0 implementation\",\n \"signature\": \"...\",\n \"timestamp\": 1752274500\n }\n ]\n },\n \"payload\": {\n \"id\": \"1752274500-task-implementar-auth\",\n \"status\": \"pending\",\n \"priority\": \"high\",\n \"description\": \"Implementar autenticación OAuth 2.0.\",\n \"tags\": [\n \"skill:go\",\n \"area:backend\"\n ]\n }\n },\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"execution\",\n \"payloadChecksum\": \"b2c3d4e5f6a1...\",\n \"signatures\": [\n {\n \"keyId\": \"agent:cursor\",\n \"role\": \"author\",\n \"notes\": \"OAuth 2.0 flow completed with GitHub provider integration\",\n \"signature\": \"...\",\n \"timestamp\": 1752274600\n },\n {\n \"keyId\": \"human:camilo\",\n \"role\": \"reviewer\",\n \"notes\": \"Reviewed and tested locally. LGTM.\",\n \"signature\": \"...\",\n \"timestamp\": 1752274650\n }\n ]\n },\n \"payload\": {\n \"id\": \"1752274600-exec-implement-oauth\",\n \"taskId\": \"1752274500-task-implement-oauth\",\n \"type\": \"progress\",\n \"title\": \"OAuth 2.0 flow implemented\",\n \"result\": \"Completed the OAuth 2.0 authentication flow...\"\n }\n },\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"actor\",\n \"payloadChecksum\": \"c3d4e5f6a1b2...\",\n \"signatures\": [\n {\n \"keyId\": \"human:admin\",\n \"role\": \"author\",\n \"notes\": \"New developer onboarded to team\",\n \"signature\": \"...\",\n \"timestamp\": 1752274700\n },\n {\n \"keyId\": \"agent:aion\",\n \"role\": \"auditor\",\n \"notes\": \"Actor verification: 10/10. Credentials validated.\",\n \"signature\": \"...\",\n \"timestamp\": 1752274705\n }\n ]\n },\n \"payload\": {\n \"id\": \"human:new-developer\",\n \"type\": \"human\",\n \"displayName\": \"New Developer\",\n \"publicKey\": \"...\",\n \"roles\": [\n \"developer\"\n ]\n }\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"execution_record_schema.json\",\n \"title\": \"ExecutionRecord\",\n \"description\": \"Canonical schema for execution log records - the universal event stream\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"taskId\",\n \"type\",\n \"title\",\n \"result\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-exec-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"Unique identifier for the execution log entry (10 timestamp + 1 dash + 4 'exec' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n \"1752275000-exec-refactor-queries\",\n \"1752361200-exec-api-externa-caida\"\n ]\n },\n \"taskId\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"ID of the parent task this execution belongs to (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"analysis\",\n \"progress\",\n \"blocker\",\n \"completion\",\n \"info\",\n \"correction\"\n ],\n \"description\": \"Semantic classification of the execution event\",\n \"examples\": [\n \"progress\",\n \"analysis\",\n \"blocker\",\n \"completion\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"Human-readable title for the execution (used to generate ID)\",\n \"examples\": [\n \"Refactor de queries N+1\",\n \"API Externa Caída\",\n \"Plan de implementación OAuth2\"\n ]\n },\n \"result\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 22000,\n \"description\": \"The tangible, verifiable output or result of the execution. \\nThis is the \\\"WHAT\\\" - evidence of work or event summary.\\n\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"maxLength\": 6500,\n \"description\": \"Optional narrative, context and decisions behind the execution.\\nThis is the \\\"HOW\\\" and \\\"WHY\\\" - the story behind the result.\\n\"\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Optional list of typed references to relevant commits, files, PRs, or external documents.\\nShould use typed prefixes for clarity and trazabilidad (see execution_protocol_appendix.md):\\n- commit: Git commit SHA\\n- pr: Pull Request number\\n- file: File path (relative to repo root)\\n- url: External URL\\n- issue: GitHub Issue number\\n- task: TaskRecord ID\\n- exec: ExecutionRecord ID (for corrections or dependencies)\\n- changelog: ChangelogRecord ID\\n\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Optional structured data for machine consumption.\\nUse this field for data that needs to be programmatically processed (e.g., audit findings,\\nperformance metrics, scan results). This complements result (human-readable WHAT) and\\nnotes (narrative HOW/WHY) by providing structured, queryable data.\\nCommon use cases: audit findings arrays, performance metrics, tool outputs, scan summaries.\\n\",\n \"examples\": [\n {\n \"findings\": [\n {\n \"type\": \"PII\",\n \"file\": \"src/user.ts\",\n \"line\": 42\n }\n ],\n \"scannedFiles\": 245\n },\n {\n \"metrics\": {\n \"duration_ms\": 1250,\n \"memory_mb\": 512\n }\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"1752275500-exec-refactor-queries\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"progress\",\n \"title\": \"Refactor de queries N+1\",\n \"result\": \"Refactorizados 3 queries N+1 a un solo JOIN optimizado. Performance mejoró de 2.5s a 200ms.\",\n \"notes\": \"Identificados 3 N+1 queries en el endpoint /api/search. Aplicado eager loading y caching de relaciones.\",\n \"references\": [\n \"commit:b2c3d4e\",\n \"file:src/api/search.ts\"\n ]\n },\n {\n \"id\": \"1752361200-exec-api-externa-caida\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"blocker\",\n \"title\": \"API Externa Caída\",\n \"result\": \"No se puede continuar con testing de integración. API de pagos devuelve 503.\",\n \"notes\": \"La API de pagos de terceros (api.payments.com) está devolviendo errores 503. Contactado soporte del proveedor. ETA de resolución: 2-3 horas.\",\n \"references\": [\n \"url:https://status.payments.com\"\n ]\n },\n {\n \"id\": \"1752188000-exec-plan-oauth-implementation\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"analysis\",\n \"title\": \"Plan de implementación OAuth2\",\n \"result\": \"Documento de diseño técnico completado. 5 sub-tareas identificadas con estimaciones de complejidad.\",\n \"notes\": \"Evaluadas 3 opciones: NextAuth.js (elegida), Passport.js, custom implementation. NextAuth.js por madurez y soporte de múltiples providers.\",\n \"references\": [\n \"file:docs/oauth-design.md\"\n ]\n },\n {\n \"id\": \"1752707800-exec-oauth-completed\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"completion\",\n \"title\": \"OAuth Implementation Completed\",\n \"result\": \"Sistema OAuth2 completamente implementado, testeado y deployado a staging. 95% test coverage. Todos los acceptance criteria cumplidos.\",\n \"notes\": \"Implementación finalizada. Code review aprobado. Tests E2E passing. Ready para changelog y deploy a producción.\",\n \"references\": [\n \"pr:456\",\n \"commit:def789abc\",\n \"url:https://staging.app.com/login\"\n ]\n },\n {\n \"id\": \"1752275600-exec-cambio-estrategia-redis\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"info\",\n \"title\": \"Cambio de estrategia: Usar Redis para sessions\",\n \"result\": \"Decisión: Migrar de JWT stateless a sessions en Redis por requisito de revocación inmediata.\",\n \"notes\": \"Durante code review se identificó requisito crítico: revocar sesiones inmediatamente (ej: compromiso de cuenta). JWT stateless no permite esto sin lista negra compleja. Redis sessions permite revocación instantánea.\",\n \"references\": [\n \"issue:567\",\n \"url:https://redis.io/docs/manual/keyspace-notifications/\"\n ]\n },\n {\n \"id\": \"1752275700-exec-correccion-metricas\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"correction\",\n \"title\": \"Corrección: Métricas de performance\",\n \"result\": \"Corrección de execution 1752275500-exec-refactor-queries: El performance fue 200ms, no 50ms como se reportó.\",\n \"notes\": \"Error de tipeo en execution original. La mejora real fue de 2.5s a 200ms (no 50ms). Sigue siendo significativa (92% mejora) pero números correctos son importantes para métricas.\",\n \"references\": [\n \"exec:1752275500-exec-refactor-queries\"\n ]\n },\n {\n \"id\": \"1752276000-exec-source-audit-scan\",\n \"taskId\": \"1752274500-task-audit-compliance\",\n \"type\": \"analysis\",\n \"title\": \"Source Audit Scan - 2025-01-15\",\n \"result\": \"Escaneados 245 archivos. Encontrados 10 findings (3 critical, 4 high, 3 medium). Ver metadata para detalles estructurados.\",\n \"notes\": \"Scan ejecutado con RegexDetector + HeuristicDetector. LLM calls: 0 (tier free).\",\n \"references\": [\n \"file:src/config/db.ts\",\n \"file:src/auth/keys.ts\"\n ],\n \"metadata\": {\n \"scannedFiles\": 245,\n \"scannedLines\": 18420,\n \"duration_ms\": 1250,\n \"findings\": [\n {\n \"id\": \"SEC-001\",\n \"severity\": \"critical\",\n \"file\": \"src/config/db.ts\",\n \"line\": 5,\n \"type\": \"api_key\"\n },\n {\n \"id\": \"SEC-003\",\n \"severity\": \"critical\",\n \"file\": \"src/auth/keys.ts\",\n \"line\": 2,\n \"type\": \"private_key\"\n },\n {\n \"id\": \"PII-003\",\n \"severity\": \"critical\",\n \"file\": \"src/payments/stripe.ts\",\n \"line\": 8,\n \"type\": \"credit_card\"\n }\n ],\n \"summary\": {\n \"critical\": 3,\n \"high\": 4,\n \"medium\": 3,\n \"low\": 0\n }\n }\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"feedback_record_schema.json\",\n \"title\": \"FeedbackRecord\",\n \"description\": \"Canonical schema for feedback records - structured conversation about work\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"entityType\",\n \"entityId\",\n \"type\",\n \"status\",\n \"content\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\",\n \"maxLength\": 70,\n \"description\": \"Unique identifier for the feedback entry\",\n \"examples\": [\n \"1752788100-feedback-blocking-rest-api\",\n \"1752788200-feedback-question-test-coverage\"\n ]\n },\n \"entityType\": {\n \"type\": \"string\",\n \"enum\": [\n \"task\",\n \"execution\",\n \"changelog\",\n \"feedback\",\n \"cycle\"\n ],\n \"description\": \"The type of entity this feedback refers to\"\n },\n \"entityId\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"The ID of the entity this feedback refers to.\\nMust match the pattern for its entityType:\\n- task: ^\\\\d{10}-task-[a-z0-9-]{1,50}$\\n- execution: ^\\\\d{10}-exec-[a-z0-9-]{1,50}$\\n- changelog: ^\\\\d{10}-changelog-[a-z0-9-]{1,50}$\\n- feedback: ^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\\n- cycle: ^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\\n\",\n \"examples\": [\n \"1752274500-task-implementar-oauth\",\n \"1752642000-exec-subtarea-9-4\",\n \"1752788100-feedback-blocking-rest-api\"\n ]\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"blocking\",\n \"suggestion\",\n \"question\",\n \"approval\",\n \"clarification\",\n \"assignment\"\n ],\n \"description\": \"The semantic intent of the feedback\",\n \"examples\": [\n \"blocking\",\n \"question\",\n \"approval\"\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"open\",\n \"acknowledged\",\n \"resolved\",\n \"wontfix\"\n ],\n \"description\": \"The lifecycle status of the feedback. \\nNote: FeedbackRecords are immutable. To change status, create a new feedback \\nthat references this one using entityType: \\\"feedback\\\" and resolvesFeedbackId.\\n\"\n },\n \"content\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 5000,\n \"description\": \"The content of the feedback. Reduced from 10000 to 5000 chars for practical use.\"\n },\n \"assignee\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"maxLength\": 256,\n \"description\": \"Optional. The Actor ID responsible for addressing the feedback (e.g., 'human:maria', 'agent:camilo:cursor')\",\n \"examples\": [\n \"human:maria\",\n \"agent:code-reviewer\",\n \"agent:camilo:cursor\"\n ]\n },\n \"resolvesFeedbackId\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\",\n \"maxLength\": 70,\n \"description\": \"Optional. The ID of another feedback record that this one resolves or responds to\",\n \"examples\": [\n \"1752788100-feedback-blocking-rest-api\"\n ]\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Optional structured data for machine consumption.\\nUse this field for domain-specific data that needs to be programmatically processed.\\nCommon use cases: waiver details (fingerprint, ruleId, file, line), approval context, assignment metadata.\\n\",\n \"examples\": [\n {\n \"fingerprint\": \"abc123def456\",\n \"ruleId\": \"PII-001\",\n \"file\": \"src/user.ts\",\n \"line\": 42,\n \"expiresAt\": \"2025-12-31T23:59:59Z\"\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"1752788100-feedback-blocking-rest-api\",\n \"entityType\": \"execution\",\n \"entityId\": \"1752642000-exec-subtarea-9-4\",\n \"type\": \"blocking\",\n \"status\": \"open\",\n \"content\": \"Esta implementación no cumple el estándar de rutas REST. Los endpoints deben seguir el patrón /api/v1/{resource}/{id}. Actualmente usa /get-user?id=X que no es RESTful.\"\n },\n {\n \"id\": \"1752788200-feedback-rest-api-fixed\",\n \"entityType\": \"feedback\",\n \"entityId\": \"1752788100-feedback-blocking-rest-api\",\n \"type\": \"clarification\",\n \"status\": \"resolved\",\n \"content\": \"Implementada la corrección. Ahora todos los endpoints siguen el estándar REST: GET /api/v1/users/:id, POST /api/v1/users, etc. Tests actualizados y passing.\",\n \"resolvesFeedbackId\": \"1752788100-feedback-blocking-rest-api\"\n },\n {\n \"id\": \"1752788300-feedback-assign-auth-task\",\n \"entityType\": \"task\",\n \"entityId\": \"1752274500-task-implementar-oauth\",\n \"type\": \"assignment\",\n \"status\": \"open\",\n \"content\": \"Asignando esta tarea a María por su experiencia con OAuth2. Prioridad alta para el sprint actual.\",\n \"assignee\": \"human:maria\"\n },\n {\n \"id\": \"1752788400-feedback-question-test-coverage\",\n \"entityType\": \"task\",\n \"entityId\": \"1752274500-task-implementar-oauth\",\n \"type\": \"question\",\n \"status\": \"open\",\n \"content\": \"¿Cuál es el nivel de test coverage esperado para esta feature? El spec no lo menciona explícitamente. ¿Debemos apuntar a 80% como el resto del proyecto?\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"task_record_schema.json\",\n \"title\": \"TaskRecord\",\n \"description\": \"Canonical schema for task records as defined in task_protocol.md\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"status\",\n \"priority\",\n \"description\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"Unique identifier for the task (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n \"1752274500-task-implementar-auth\",\n \"1752347700-task-fix-logging\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 3,\n \"maxLength\": 150,\n \"description\": \"A brief, human-readable title for the task. Used to generate the ID slug.\"\n },\n \"cycleIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67\n },\n \"default\": [],\n \"description\": \"Optional. The IDs of the strategic cycles this task belongs to. (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"draft\",\n \"review\",\n \"ready\",\n \"active\",\n \"done\",\n \"archived\",\n \"paused\",\n \"discarded\"\n ],\n \"maxLength\": 40,\n \"description\": \"Current state of the task in the institutional flow\"\n },\n \"priority\": {\n \"type\": \"string\",\n \"enum\": [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"maxLength\": 40,\n \"description\": \"Strategic or tactical priority level\"\n },\n \"description\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 22000,\n \"description\": \"Functional, technical or strategic summary of the objective\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-:]+)*$\"\n },\n \"default\": [],\n \"description\": \"Optional. List of key:value tags for categorization and role suggestion (e.g., 'skill:react', 'role:agent:developer').\"\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Valid links or files, when mentioned\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 0,\n \"maxLength\": 3000,\n \"description\": \"Additional comments, decisions made or added context\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1752274500-task-implement-oauth-flow\",\n \"title\": \"Implement OAuth 2.0 authentication flow\",\n \"status\": \"draft\",\n \"priority\": \"high\",\n \"description\": \"Implement complete OAuth 2.0 flow with GitHub provider. Include token refresh, session management, and secure storage. Must support both web and CLI flows.\",\n \"cycleIds\": [\n \"1752270000-cycle-auth-mvp\"\n ],\n \"tags\": [\n \"skill:security\",\n \"category:feature\",\n \"package:core\"\n ],\n \"references\": [\n \"url:https://docs.github.com/en/apps/oauth-apps/building-oauth-apps\"\n ],\n \"notes\": \"Consider using proven library like passport.js or implement from scratch for learning.\"\n },\n {\n \"id\": \"1752347700-task-fix-memory-leak-indexer\",\n \"title\": \"Fix memory leak in indexer process\",\n \"status\": \"active\",\n \"priority\": \"critical\",\n \"description\": \"Indexer process consuming >2GB RAM after 24h uptime. Profiling shows EventEmitter listeners not being cleaned up properly. Fix leak and add monitoring.\",\n \"cycleIds\": [],\n \"tags\": [\n \"category:bug\",\n \"skill:performance\",\n \"package:core\"\n ],\n \"references\": [\n \"file:packages/core/src/adapters/indexer_adapter/index.ts\",\n \"commit:a1b2c3d4\",\n \"issue:789\"\n ],\n \"notes\": \"Discovered during production monitoring. Affects long-running processes only.\"\n },\n {\n \"id\": \"1752448900-task-add-typescript-linting\",\n \"title\": \"Add TypeScript strict mode and ESLint rules\",\n \"status\": \"done\",\n \"priority\": \"medium\",\n \"description\": \"Enable TypeScript strict mode across all packages. Configure ESLint with recommended rules. Fix all existing violations. Add pre-commit hook.\",\n \"cycleIds\": [\n \"1752440000-cycle-code-quality-q1\"\n ],\n \"tags\": [\n \"category:tooling\",\n \"skill:typescript\",\n \"epic:code-quality\"\n ],\n \"references\": [\n \"pr:123\",\n \"file:.eslintrc.js\",\n \"file:tsconfig.json\"\n ],\n \"notes\": \"Approved by tech lead. All 47 violations fixed in PR #123.\"\n },\n {\n \"id\": \"1752550000-task-research-graphql-migration\",\n \"title\": \"Research GraphQL migration feasibility\",\n \"status\": \"draft\",\n \"priority\": \"low\",\n \"description\": \"Evaluate feasibility of migrating REST API to GraphQL. Document pros/cons, effort estimation, and recommended approach. Focus on developer experience and performance.\",\n \"cycleIds\": [],\n \"tags\": [\n \"category:research\",\n \"skill:graphql\",\n \"skill:backend\"\n ],\n \"references\": []\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"workflow_schema.json\",\n \"title\": \"WorkflowRecord\",\n \"description\": \"Complete schema for workflow methodology configuration files that define state transitions, signatures, and custom rules\",\n \"type\": \"object\",\n \"required\": [\n \"version\",\n \"name\",\n \"state_transitions\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"$schema\": {\n \"type\": \"string\",\n \"description\": \"JSON Schema reference\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$\",\n \"description\": \"Semantic version of the methodology configuration\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100,\n \"description\": \"Human-readable name of the methodology\"\n },\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 500,\n \"description\": \"Brief description of the methodology's purpose and scope\"\n },\n \"state_transitions\": {\n \"type\": \"object\",\n \"description\": \"Defines valid state transitions and their requirements\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"from\",\n \"requires\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"from\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9_]{0,49}$\"\n },\n \"minItems\": 1,\n \"description\": \"Valid source states for this transition\"\n },\n \"requires\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": \"CLI command that triggers this transition\"\n },\n \"event\": {\n \"type\": \"string\",\n \"description\": \"System event that triggers this transition\"\n },\n \"signatures\": {\n \"type\": \"object\",\n \"description\": \"Signature requirements keyed by role (e.g., 'approver:quality', 'developer:backend')\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"role\",\n \"capability_roles\",\n \"min_approvals\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"role\": {\n \"type\": \"string\",\n \"description\": \"Required signature role\"\n },\n \"capability_roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"minItems\": 1,\n \"description\": \"Required capability roles in actor record\"\n },\n \"min_approvals\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Minimum number of required approvals\"\n },\n \"actor_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"human\",\n \"agent\"\n ],\n \"description\": \"Optional: restrict to specific actor type\"\n },\n \"specific_actors\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"Optional: specific actors that can sign\"\n }\n }\n }\n },\n \"custom_rules\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of custom rule identifiers to validate\"\n }\n }\n }\n }\n }\n },\n \"custom_rules\": {\n \"type\": \"object\",\n \"description\": \"Definitions for custom validation rules\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"description\",\n \"validation\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 200,\n \"description\": \"Human-readable description of the rule\"\n },\n \"validation\": {\n \"type\": \"string\",\n \"enum\": [\n \"assignment_required\",\n \"sprint_capacity\",\n \"epic_complexity\",\n \"custom\"\n ],\n \"description\": \"Validation type identifier\"\n },\n \"parameters\": {\n \"type\": \"object\",\n \"description\": \"Optional parameters for the validation rule\"\n },\n \"expression\": {\n \"type\": \"string\",\n \"description\": \"Inline validation expression for 'custom' validation type. Implementation determines the runtime and language. Must return boolean or Promise<boolean>.\"\n },\n \"module_path\": {\n \"type\": \"string\",\n \"description\": \"Path to external module for custom validation (alternative to expression)\"\n }\n }\n }\n },\n \"agent_integration\": {\n \"type\": \"object\",\n \"description\": \"Optional agent automation configuration for methodology\",\n \"additionalProperties\": false,\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 200,\n \"description\": \"Brief description of the agent integration\"\n },\n \"required_agents\": {\n \"type\": \"array\",\n \"description\": \"References to agents required for this methodology. Agent details (engine, knowledge, etc.) live in their AgentRecord.\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"triggers\"\n ],\n \"anyOf\": [\n {\n \"required\": [\n \"id\"\n ]\n },\n {\n \"required\": [\n \"required_roles\"\n ]\n }\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^agent:[a-z0-9:-]+$\",\n \"description\": \"Specific agent ID. References an existing AgentRecord.\"\n },\n \"required_roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"minItems\": 1,\n \"description\": \"Required capability roles. Matches any agent with these roles (from ActorRecord).\"\n },\n \"triggers\": {\n \"type\": \"array\",\n \"description\": \"When this agent activates within this methodology\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"event\",\n \"action\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Event that triggers the agent\"\n },\n \"action\": {\n \"type\": \"string\",\n \"description\": \"Action the agent should perform\"\n },\n \"cron\": {\n \"type\": \"string\",\n \"description\": \"Cron expression for scheduled triggers\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"examples\": [\n {\n \"version\": \"1.0.0\",\n \"name\": \"Simple Kanban\",\n \"description\": \"Basic workflow for small teams\",\n \"state_transitions\": {\n \"review\": {\n \"from\": [\n \"draft\"\n ],\n \"requires\": {\n \"command\": \"gitgov task submit\"\n }\n },\n \"ready\": {\n \"from\": [\n \"review\"\n ],\n \"requires\": {\n \"command\": \"gitgov task approve\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:product\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"active\": {\n \"from\": [\n \"ready\"\n ],\n \"requires\": {\n \"event\": \"first_execution_record_created\"\n }\n },\n \"done\": {\n \"from\": [\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task complete\"\n }\n }\n }\n },\n {\n \"version\": \"1.0.0\",\n \"name\": \"GitGovernance Default Methodology\",\n \"description\": \"Standard GitGovernance workflow with quality gates and agent collaboration\",\n \"state_transitions\": {\n \"review\": {\n \"from\": [\n \"draft\"\n ],\n \"requires\": {\n \"command\": \"gitgov task submit\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"submitter\",\n \"capability_roles\": [\n \"author\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"ready\": {\n \"from\": [\n \"review\"\n ],\n \"requires\": {\n \"command\": \"gitgov task approve\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:product\"\n ],\n \"min_approvals\": 1\n },\n \"design\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:design\"\n ],\n \"min_approvals\": 1\n },\n \"quality\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"active\": {\n \"from\": [\n \"ready\",\n \"paused\"\n ],\n \"requires\": {\n \"event\": \"first_execution_record_created\",\n \"custom_rules\": [\n \"task_must_have_valid_assignment_for_executor\"\n ]\n }\n },\n \"done\": {\n \"from\": [\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task complete\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"archived\": {\n \"from\": [\n \"done\"\n ],\n \"requires\": {\n \"event\": \"changelog_record_created\"\n }\n },\n \"paused\": {\n \"from\": [\n \"active\",\n \"review\"\n ],\n \"requires\": {\n \"event\": \"feedback_blocking_created\"\n }\n },\n \"discarded\": {\n \"from\": [\n \"ready\",\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task cancel\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"canceller\",\n \"capability_roles\": [\n \"approver:product\",\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n }\n },\n \"custom_rules\": {\n \"task_must_have_valid_assignment_for_executor\": {\n \"description\": \"Task must have a valid assignment before execution can begin\",\n \"validation\": \"assignment_required\"\n }\n }\n }\n ]\n}","/**\n * GitGovernance Protocol Schemas\n * \n * Auto-generated from blueprints. Do not edit manually.\n * Run 'pnpm sync:schemas' to update.\n */\n\nimport actorRecordSchema from \"./actor_record_schema.json\";\nimport agentRecordSchema from \"./agent_record_schema.json\";\nimport changelogRecordSchema from \"./changelog_record_schema.json\";\nimport cycleRecordSchema from \"./cycle_record_schema.json\";\nimport embeddedMetadataSchema from \"./embedded_metadata_schema.json\";\nimport executionRecordSchema from \"./execution_record_schema.json\";\nimport feedbackRecordSchema from \"./feedback_record_schema.json\";\nimport taskRecordSchema from \"./task_record_schema.json\";\nimport workflowRecordSchema from \"./workflow_record_schema.json\";\n\n/**\n * All GitGovernance protocol schemas\n */\nexport const Schemas = {\n ActorRecord: actorRecordSchema,\n AgentRecord: agentRecordSchema,\n ChangelogRecord: changelogRecordSchema,\n CycleRecord: cycleRecordSchema,\n EmbeddedMetadata: embeddedMetadataSchema,\n ExecutionRecord: executionRecordSchema,\n FeedbackRecord: feedbackRecordSchema,\n TaskRecord: taskRecordSchema,\n WorkflowRecord: workflowRecordSchema,\n} as const;\n\n/**\n * Schema names for type safety\n */\nexport type SchemaName = \n | \"ActorRecord\"\n | \"AgentRecord\"\n | \"ChangelogRecord\"\n | \"CycleRecord\"\n | \"EmbeddedMetadata\"\n | \"ExecutionRecord\"\n | \"FeedbackRecord\"\n | \"TaskRecord\"\n | \"WorkflowRecord\";\n\n/**\n * Get a schema by name\n */\nexport function getSchema(name: SchemaName) {\n return Schemas[name];\n}\n\n/**\n * Get all schema names\n */\nexport function getSchemaNames(): SchemaName[] {\n return Object.keys(Schemas) as SchemaName[];\n}\n\n/**\n * Check if a schema exists\n */\nexport function hasSchema(name: string): name is SchemaName {\n return name in Schemas;\n}\n","import Ajv from \"ajv\";\nimport type { ValidateFunction } from \"ajv\";\nimport addFormats from \"ajv-formats\";\n\n// Direct import from generated schemas\nimport { Schemas } from \"./generated\";\n\n/**\n * Singleton cache for schema validators to avoid repeated I/O and AJV compilation.\n * Improves performance by caching compiled validators for schema files.\n */\nexport class SchemaValidationCache {\n private static schemaValidators = new Map<string, ValidateFunction>();\n private static ajv: Ajv | null = null;\n\n /**\n * Gets or creates a cached validator for a schema object.\n * @param schema The schema object (already parsed YAML/JSON)\n * @returns Compiled AJV validator function\n */\n static getValidatorFromSchema<T = unknown>(schema: object): ValidateFunction<T> {\n // Create a stable key from the schema object\n const schemaKey = JSON.stringify(schema);\n\n if (!this.schemaValidators.has(schemaKey)) {\n // Initialize AJV instance if not already done\n if (!this.ajv) {\n this.ajv = new Ajv({ allErrors: true });\n addFormats(this.ajv);\n\n // Pre-load all schemas for reference resolution\n this.preloadSchemas();\n }\n\n // Remove $id temporarily to avoid conflicts with preloaded schemas\n // (This doesn't modify the original schema object)\n const { $id, ...schemaWithoutId } = schema as any;\n\n // Compile schema directly - AJV will resolve $ref using preloaded aliases\n const validator = this.ajv.compile(schemaWithoutId);\n this.schemaValidators.set(schemaKey, validator);\n }\n\n return this.schemaValidators.get(schemaKey)! as ValidateFunction<T>;\n }\n\n /**\n * Pre-loads referenced schema files for $ref resolution.\n * Uses direct imports and dynamic iteration.\n */\n private static preloadSchemas(): void {\n if (!this.ajv) return;\n\n try {\n // Map schema names to their expected ref aliases\n const schemaRefMap: Record<string, string> = {\n 'ActorRecord': 'ref:actor_record_schema',\n 'AgentRecord': 'ref:agent_record_schema',\n 'ChangelogRecord': 'ref:changelog_record_schema',\n 'CycleRecord': 'ref:cycle_record_schema',\n 'ExecutionRecord': 'ref:execution_record_schema',\n 'FeedbackRecord': 'ref:feedback_record_schema',\n 'TaskRecord': 'ref:task_record_schema',\n 'WorkflowRecord': 'ref:workflow_record_schema'\n };\n\n // Register schemas with correct aliases\n Object.entries(Schemas).forEach(([name, schema]) => {\n if (name !== 'EmbeddedMetadata' && schemaRefMap[name]) {\n const refName = schemaRefMap[name];\n this.ajv!.addSchema(schema, refName);\n }\n });\n } catch {\n // If preloading fails, continue without it\n }\n }\n\n /**\n * Clears the cache (useful for testing or schema updates).\n */\n static clearCache(): void {\n this.schemaValidators.clear();\n this.ajv = null;\n }\n\n /**\n * Gets cache statistics for monitoring.\n */\n static getCacheStats(): { cachedSchemas: number } {\n return {\n cachedSchemas: this.schemaValidators.size\n };\n }\n}\n","import { generateKeyPair, sign, verify, createHash, randomBytes } from \"crypto\";\nimport { promisify } from \"util\";\nimport { calculatePayloadChecksum } from \"./checksum\";\nimport type { GitGovRecordPayload, Signature } from \"../record_types\";\nimport { createLogger } from \"../logger\";\nconst logger = createLogger(\"[CryptoModule] \");\nconst generateKeyPairAsync = promisify(generateKeyPair);\n\n/**\n * Generates a new Ed25519 key pair.\n * @returns A promise that resolves to an object with publicKey and privateKey in base64 format.\n * \n * The publicKey is the raw Ed25519 key (32 bytes -> 44 chars in base64).\n * The privateKey is stored in PKCS8 PEM format for compatibility.\n * \n * Note: Node.js crypto does not support 'raw' format directly for Ed25519,\n * so we extract the raw 32-byte key from the SPKI DER encoding (RFC 8410).\n * SPKI DER structure: [algorithm identifier (12 bytes)] + [raw public key (32 bytes)]\n */\nexport async function generateKeys(): Promise<{ publicKey: string; privateKey: string; }> {\n const { publicKey, privateKey } = await generateKeyPairAsync('ed25519', {\n publicKeyEncoding: { type: 'spki', format: 'der' },\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n });\n\n // Extract raw Ed25519 public key (last 32 bytes of SPKI DER format)\n const rawPublicKey = publicKey.subarray(-32);\n\n return {\n publicKey: rawPublicKey.toString('base64'), // 32 bytes -> 44 chars\n privateKey: Buffer.from(privateKey).toString('base64'),\n };\n}\n\n/**\n * Creates a signature for a given payload.\n */\nexport function signPayload(\n payload: GitGovRecordPayload,\n privateKey: string,\n keyId: string,\n role: string,\n notes: string,\n): Signature {\n const payloadChecksum = calculatePayloadChecksum(payload);\n const timestamp = Math.floor(Date.now() / 1000);\n const digest = `${payloadChecksum}:${keyId}:${role}:${notes}:${timestamp}`;\n\n // Per the blueprint, sign the SHA-256 hash of the digest\n const digestHash = createHash('sha256').update(digest).digest();\n\n const signature = sign(null, digestHash, {\n key: Buffer.from(privateKey, 'base64'),\n type: 'pkcs8',\n format: 'pem'\n });\n\n return {\n keyId,\n role,\n notes,\n signature: signature.toString('base64'),\n timestamp,\n };\n}\n\n/**\n * Verifies all signatures on a record.\n * \n * Reconstructs SPKI DER format from raw Ed25519 key for verification.\n */\nexport async function verifySignatures(\n record: { header: { payloadChecksum: string, signatures: Signature[] }, payload: GitGovRecordPayload },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<boolean> {\n for (const signature of record.header.signatures) {\n const publicKeyBase64 = await getActorPublicKey(signature.keyId);\n if (!publicKeyBase64) {\n // Use debug level instead of warn to reduce noise during indexer validation\n // The indexer already captures these errors in its integrity report\n logger.debug(`Public key not found for actor: ${signature.keyId}`);\n return false;\n }\n\n const digest = `${record.header.payloadChecksum}:${signature.keyId}:${signature.role}:${signature.notes}:${signature.timestamp}`;\n const digestHash = createHash('sha256').update(digest).digest();\n\n // Reconstruct SPKI DER from raw Ed25519 public key (RFC 8410)\n // SPKI DER structure: [algorithm identifier (12 bytes)] + [raw key (32 bytes)]\n const algorithmIdentifier = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65,\n 0x70, 0x03, 0x21, 0x00\n ]);\n const rawPublicKey = Buffer.from(publicKeyBase64, 'base64');\n const spkiPublicKey = Buffer.concat([algorithmIdentifier, rawPublicKey]);\n\n const isValid = verify(\n null,\n digestHash,\n {\n key: spkiPublicKey,\n type: 'spki',\n format: 'der'\n },\n Buffer.from(signature.signature, 'base64')\n );\n\n if (!isValid) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Generates a mock signature with valid Ed25519 format.\n * Used as fallback when private key is not available.\n *\n * [EARS-7] Returns a base64-encoded string of 64 random bytes (86 chars + ==)\n */\nexport function generateMockSignature(): string {\n return randomBytes(64).toString('base64');\n}\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { EmbeddedMetadataRecord } from '../record_types/embedded.types';\nimport type { GitGovRecordPayload } from '../record_types/common.types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { calculatePayloadChecksum } from '../crypto/checksum';\nimport { verifySignatures } from '../crypto/signatures';\nimport { DetailedValidationError, ChecksumMismatchError, SignatureVerificationError } from './common';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for EmbeddedMetadata wrapper\n */\nexport function validateEmbeddedMetadataSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.EmbeddedMetadata);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid EmbeddedMetadataRecord\n */\nexport function isEmbeddedMetadataRecord<T extends GitGovRecordPayload>(data: unknown): data is EmbeddedMetadataRecord<T> {\n const [isValid] = validateEmbeddedMetadataSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation for EmbeddedMetadataRecord with formatted errors\n */\nexport function validateEmbeddedMetadataDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateEmbeddedMetadataSchema(data);\n\n const formattedErrors = ajvErrors?.map((error: ErrorObject) => ({\n field: error.instancePath || error.schemaPath,\n message: error.message || 'Validation failed',\n value: error.data\n })) || [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n/**\n * Full validation for EmbeddedMetadataRecord including schema, checksum, and signatures\n */\nexport async function validateFullEmbeddedMetadataRecord<T extends GitGovRecordPayload>(\n record: EmbeddedMetadataRecord<T>,\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation - validate the entire record structure\n const [isValidSchema, errors] = validateEmbeddedMetadataSchema(record);\n if (!isValidSchema) {\n const formattedErrors = errors?.map(error => ({\n field: error.instancePath || error.schemaPath,\n message: error.message || 'Validation failed',\n value: error.data\n })) || [];\n\n throw new DetailedValidationError('EmbeddedMetadata', formattedErrors);\n }\n\n // 2. Checksum Validation\n const expectedChecksum = calculatePayloadChecksum(record.payload);\n if (expectedChecksum !== record.header.payloadChecksum) {\n throw new ChecksumMismatchError();\n }\n\n // 3. Signature Verification\n const areSignaturesValid = await verifySignatures(\n record,\n getActorPublicKey\n );\n if (!areSignaturesValid) {\n throw new SignatureVerificationError();\n }\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ActorRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { DetailedValidationError } from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from \"../record_schemas\";\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\n\n// --- Schema Validation ---\nconst actorSchema = Schemas.ActorRecord;\n\nexport function validateActorRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(actorSchema);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\nexport function isActorRecord(data: unknown): data is ActorRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(actorSchema);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates an ActorRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateActorRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateActorRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of an ActorRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the actor payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullActorRecord(\n record: GitGovRecord & { payload: ActorRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateActorRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ActorRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { ActorRecord, GitGovActorRecord } from \"../record_types\";\nimport { validateActorRecordDetailed } from \"../record_validations/actor_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { generateActorId } from \"../utils/id_generator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\n\n/**\n * Creates a new, fully-formed ActorRecord with validation.\n */\nexport function createActorRecord(\n payload: Partial<ActorRecord>\n): ActorRecord {\n // Build actor with defaults for optional fields\n const actor: ActorRecord = {\n id: payload.id || generateActorId(payload.type || 'human', payload.displayName || ''),\n type: payload.type || 'human' as const,\n displayName: payload.displayName || '',\n publicKey: payload.publicKey || '',\n roles: payload.roles || ['author'] as [string, ...string[]],\n status: payload.status || 'active',\n ...payload,\n } as ActorRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateActorRecordDetailed(actor);\n if (!validation.isValid) {\n throw new DetailedValidationError('ActorRecord', validation.errors);\n }\n\n return actor;\n}\n\n/**\n * Loads and validates an existing ActorRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ActorRecord).\n * \n * @param data - Unknown data to validate as GitGovActorRecord\n * @returns GitGovActorRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadActorRecord(data: unknown): GitGovActorRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ActorRecord)', embeddedValidation.errors);\n }\n \n // Then validate specific ActorRecord payload\n const record = data as GitGovActorRecord;\n const payloadValidation = validateActorRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ActorRecord payload', payloadValidation.errors);\n }\n \n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { AgentRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { DetailedValidationError, SchemaValidationError } from \"./common\";\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from '../record_schemas';\nimport type { ActorRecord } from \"../record_types\";\n\n// --- Schema Validation ---\nexport function validateAgentRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.AgentRecord);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\nexport function isAgentRecord(data: unknown): data is AgentRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.AgentRecord);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates an AgentRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateAgentRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateAgentRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of an AgentRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the agent payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullAgentRecord(\n record: GitGovRecord & { payload: AgentRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateAgentRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('AgentRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n\n/**\n * Validates that an AgentRecord has a valid relationship with its corresponding ActorRecord,\n * including succession chain resolution for key rotation scenarios.\n * \n * @param agentRecord The AgentRecord to validate\n * @param getEffectiveActor Function to get the effective ActorRecord (with succession resolution)\n */\nexport async function validateAgentActorRelationship(\n agentRecord: AgentRecord,\n getEffectiveActor: (agentId: string) => Promise<ActorRecord | null>\n): Promise<void> {\n const effectiveActor = await getEffectiveActor(agentRecord.id);\n\n if (!effectiveActor) {\n throw new SchemaValidationError(\n `No active ActorRecord found for AgentRecord ${agentRecord.id}. AgentRecord requires corresponding ActorRecord.`\n );\n }\n\n if (effectiveActor.type !== 'agent') {\n throw new SchemaValidationError(\n `ActorRecord ${effectiveActor.id} must be of type 'agent' to support AgentRecord ${agentRecord.id}.`\n );\n }\n\n if (effectiveActor.status !== 'active') {\n throw new SchemaValidationError(\n `ActorRecord succession chain for ${agentRecord.id} does not resolve to an active actor. Current effective actor: ${effectiveActor.id} (status: ${effectiveActor.status}).`\n );\n }\n}\n","import type { AgentRecord, GitGovAgentRecord } from \"../record_types\";\nimport { validateAgentRecordDetailed } from \"../record_validations/agent_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\n\n/**\n * Creates a new, fully-formed AgentRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial AgentRecord payload with optional typed metadata\n * @returns AgentRecord<TMetadata> - The validated AgentRecord with preserved metadata type\n */\nexport function createAgentRecord<TMetadata extends object = object>(\n payload: Partial<AgentRecord<TMetadata>>\n): AgentRecord<TMetadata> {\n // Build agent with defaults for optional fields\n const agent = {\n id: payload.id || '',\n engine: payload.engine || { type: 'local' as const },\n status: payload.status || 'active',\n triggers: payload.triggers || [],\n knowledge_dependencies: payload.knowledge_dependencies || [],\n prompt_engine_requirements: payload.prompt_engine_requirements || {},\n metadata: payload.metadata,\n ...payload,\n } as AgentRecord<TMetadata>;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateAgentRecordDetailed(agent);\n if (!validation.isValid) {\n throw new DetailedValidationError('AgentRecord', validation.errors);\n }\n\n return agent;\n}\n\n/**\n * Loads and validates an existing AgentRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (AgentRecord).\n * \n * @param data - Unknown data to validate as GitGovAgentRecord\n * @returns GitGovAgentRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadAgentRecord(data: unknown): GitGovAgentRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (AgentRecord)', embeddedValidation.errors);\n }\n \n // Then validate specific AgentRecord payload\n const record = data as GitGovAgentRecord;\n const payloadValidation = validateAgentRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('AgentRecord payload', payloadValidation.errors);\n }\n \n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { TaskRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from '../record_schemas';\nimport {\n DetailedValidationError\n} from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\n\n// --- Schema Validation ---\nexport function validateTaskRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.TaskRecord);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\n/**\n * Type guard to check if data is a valid TaskRecord.\n */\nexport function isTaskRecord(data: unknown): data is TaskRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.TaskRecord);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates a TaskRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateTaskRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateTaskRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of a TaskRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the task payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullTaskRecord(\n record: GitGovRecord & { payload: TaskRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateTaskRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('TaskRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { TaskRecord, GitGovTaskRecord } from \"../record_types\";\nimport { validateTaskRecordDetailed } from \"../record_validations/task_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\nimport { generateTaskId } from \"../utils/id_generator\";\n\n/**\n * Creates a new, fully-formed TaskRecord with validation.\n */\nexport function createTaskRecord(\n payload: Partial<TaskRecord>\n): TaskRecord {\n // Generate timestamp for ID if not provided\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build task with defaults for optional fields\n const task: TaskRecord = {\n id: payload.id || generateTaskId(payload.title || '', timestamp),\n title: payload.title || '',\n status: payload.status || 'draft',\n priority: payload.priority || 'medium',\n description: payload.description || '',\n tags: payload.tags || [],\n cycleIds: payload.cycleIds,\n references: payload.references,\n notes: payload.notes,\n ...payload,\n } as TaskRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateTaskRecordDetailed(task);\n if (!validation.isValid) {\n throw new DetailedValidationError('TaskRecord', validation.errors);\n }\n\n return task;\n}\n\n/**\n * Loads and validates an existing TaskRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (TaskRecord).\n * \n * @param data - Unknown data to validate as GitGovTaskRecord\n * @returns GitGovTaskRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadTaskRecord(data: unknown): GitGovTaskRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (TaskRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific TaskRecord payload\n const record = data as GitGovTaskRecord;\n const payloadValidation = validateTaskRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('TaskRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { CycleRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { DetailedValidationError } from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from \"../record_schemas\";\n\n// --- Schema Validation ---\nconst cycleSchema = Schemas.CycleRecord;\n\nexport function validateCycleRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(cycleSchema);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\n/**\n * Type guard to check if data is a valid CycleRecord.\n */\nexport function isCycleRecord(data: unknown): data is CycleRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(cycleSchema);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates a CycleRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateCycleRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateCycleRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of a CycleRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the cycle payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullCycleRecord(\n record: GitGovRecord & { payload: CycleRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateCycleRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('CycleRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { CycleRecord, GitGovCycleRecord } from \"../record_types\";\nimport { validateCycleRecordDetailed } from \"../record_validations/cycle_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\nimport { generateCycleId } from \"../utils/id_generator\";\n\n/**\n * Creates a new, fully-formed CycleRecord with validation.\n */\nexport function createCycleRecord(\n payload: Partial<CycleRecord>\n): CycleRecord {\n // Generate timestamp for ID if not provided\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build cycle with defaults for optional fields\n const cycle: CycleRecord = {\n id: payload.id || generateCycleId(payload.title || '', timestamp),\n title: payload.title || '',\n status: payload.status || 'planning',\n taskIds: payload.taskIds || [], // EARS-21: Default empty array\n childCycleIds: payload.childCycleIds,\n tags: payload.tags,\n notes: payload.notes,\n ...payload,\n } as CycleRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateCycleRecordDetailed(cycle);\n if (!validation.isValid) {\n throw new DetailedValidationError('CycleRecord', validation.errors);\n }\n\n return cycle;\n}\n\n/**\n * Loads and validates an existing CycleRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (CycleRecord).\n * \n * @param data - Unknown data to validate as GitGovCycleRecord\n * @returns GitGovCycleRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadCycleRecord(data: unknown): GitGovCycleRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (CycleRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific CycleRecord payload\n const record = data as GitGovCycleRecord;\n const payloadValidation = validateCycleRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('CycleRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ExecutionRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for ExecutionRecord payload\n */\nexport function validateExecutionRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.ExecutionRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid ExecutionRecord\n */\nexport function isExecutionRecord(data: unknown): data is ExecutionRecord {\n const [isValid] = validateExecutionRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateExecutionRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateExecutionRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullExecutionRecord(\n record: GitGovRecord & { payload: ExecutionRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateExecutionRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ExecutionRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { ExecutionRecord, GitGovExecutionRecord } from '../record_types';\nimport { generateExecutionId } from '../utils/id_generator';\nimport { validateExecutionRecordDetailed } from '../record_validations/execution_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete ExecutionRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial ExecutionRecord payload with optional typed metadata\n * @returns ExecutionRecord<TMetadata> - The validated ExecutionRecord with preserved metadata type\n *\n * @example\n * interface AuditMetadata { scannedFiles: number; }\n * const record = createExecutionRecord<AuditMetadata>({\n * taskId: '1752274500-task-audit',\n * result: 'Audit complete',\n * metadata: { scannedFiles: 245 }\n * });\n * // record.metadata?.scannedFiles is typed as number\n */\nexport function createExecutionRecord<TMetadata extends object = object>(\n payload: Partial<ExecutionRecord<TMetadata>>\n): ExecutionRecord<TMetadata> {\n const timestamp = Math.floor(Date.now() / 1000);\n\n const execution = {\n id: payload.id || generateExecutionId(payload.title || 'execution', timestamp),\n taskId: payload.taskId || '',\n result: payload.result || '',\n type: payload.type,\n title: payload.title,\n notes: payload.notes,\n references: payload.references,\n metadata: payload.metadata,\n } as ExecutionRecord<TMetadata>;\n\n // Validate the complete execution record\n const validation = validateExecutionRecordDetailed(execution);\n if (!validation.isValid) {\n throw new DetailedValidationError('ExecutionRecord', validation.errors);\n }\n\n return execution;\n}\n\n/**\n * Loads and validates an existing ExecutionRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ExecutionRecord).\n * \n * @param data - Unknown data to validate as GitGovExecutionRecord\n * @returns GitGovExecutionRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadExecutionRecord(data: unknown): GitGovExecutionRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ExecutionRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific ExecutionRecord payload\n const record = data as GitGovExecutionRecord;\n const payloadValidation = validateExecutionRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ExecutionRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ChangelogRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for ChangelogRecord payload\n */\nexport function validateChangelogRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.ChangelogRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid ChangelogRecord\n */\nexport function isChangelogRecord(data: unknown): data is ChangelogRecord {\n const [isValid] = validateChangelogRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateChangelogRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateChangelogRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullChangelogRecord(\n record: GitGovRecord & { payload: ChangelogRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateChangelogRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ChangelogRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { ChangelogRecord, GitGovChangelogRecord } from '../record_types';\nimport { validateChangelogRecordDetailed } from '../record_validations/changelog_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete ChangelogRecord with validation (Protocol v2)\n * \n * @param payload - Partial ChangelogRecord payload\n * @returns ChangelogRecord - The validated ChangelogRecord\n */\nexport function createChangelogRecord(payload: Partial<ChangelogRecord>): ChangelogRecord {\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build changelog with required fields\n const changelog: ChangelogRecord = {\n // Required fields\n id: payload.id || '',\n title: payload.title || '',\n description: payload.description || '',\n relatedTasks: (payload.relatedTasks || []) as [string, ...string[]],\n completedAt: payload.completedAt || timestamp,\n\n // Optional fields (only include if provided)\n ...(payload.relatedCycles && { relatedCycles: payload.relatedCycles }),\n ...(payload.relatedExecutions && { relatedExecutions: payload.relatedExecutions }),\n ...(payload.version && { version: payload.version }),\n ...(payload.tags && { tags: payload.tags }),\n ...(payload.commits && { commits: payload.commits }),\n ...(payload.files && { files: payload.files }),\n ...(payload.notes && { notes: payload.notes })\n };\n\n // Validate the complete changelog record\n const validation = validateChangelogRecordDetailed(changelog);\n if (!validation.isValid) {\n throw new DetailedValidationError('ChangelogRecord', validation.errors);\n }\n\n return changelog;\n}\n\n/**\n * Loads and validates an existing ChangelogRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ChangelogRecord).\n * \n * @param data - Unknown data to validate as GitGovChangelogRecord\n * @returns GitGovChangelogRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadChangelogRecord(data: unknown): GitGovChangelogRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ChangelogRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific ChangelogRecord payload\n const record = data as GitGovChangelogRecord;\n const payloadValidation = validateChangelogRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ChangelogRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { FeedbackRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for FeedbackRecord payload\n */\nexport function validateFeedbackRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.FeedbackRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid FeedbackRecord\n */\nexport function isFeedbackRecord(data: unknown): data is FeedbackRecord {\n const [isValid] = validateFeedbackRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateFeedbackRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateFeedbackRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullFeedbackRecord(\n record: GitGovRecord & { payload: FeedbackRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateFeedbackRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('FeedbackRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { FeedbackRecord, GitGovFeedbackRecord } from '../record_types';\nimport { generateFeedbackId } from '../utils/id_generator';\nimport { validateFeedbackRecordDetailed } from '../record_validations/feedback_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete FeedbackRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial FeedbackRecord payload with optional typed metadata\n * @returns FeedbackRecord<TMetadata> - The validated FeedbackRecord with preserved metadata type\n */\nexport function createFeedbackRecord<TMetadata extends object = object>(\n payload: Partial<FeedbackRecord<TMetadata>>\n): FeedbackRecord<TMetadata> {\n const timestamp = Math.floor(Date.now() / 1000);\n\n const feedback = {\n id: payload.id || generateFeedbackId(payload.content || 'feedback', timestamp),\n entityType: payload.entityType || 'task',\n entityId: payload.entityId || '',\n type: payload.type || 'question',\n status: payload.status || (payload.type === 'assignment' ? 'resolved' : 'open'),\n content: payload.content || '',\n assignee: payload.assignee,\n resolvesFeedbackId: payload.resolvesFeedbackId,\n metadata: payload.metadata,\n } as FeedbackRecord<TMetadata>;\n\n // Validate the complete feedback record\n const validation = validateFeedbackRecordDetailed(feedback);\n if (!validation.isValid) {\n throw new DetailedValidationError('FeedbackRecord', validation.errors);\n }\n\n return feedback;\n}\n\n/**\n * Loads and validates an existing FeedbackRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (FeedbackRecord).\n * \n * @param data - Unknown data to validate as GitGovFeedbackRecord\n * @returns GitGovFeedbackRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadFeedbackRecord(data: unknown): GitGovFeedbackRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (FeedbackRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific FeedbackRecord payload\n const record = data as GitGovFeedbackRecord;\n const payloadValidation = validateFeedbackRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('FeedbackRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","/**\n * FsLintModule - Filesystem-aware Validation\n *\n * This module wraps the pure LintModule and adds filesystem operations:\n * - Directory scanning for record discovery (EARS-A1)\n * - File naming validation (EARS-B1, EARS-B2)\n * - Backup creation and restoration (EARS-C1, EARS-C2)\n * - Delegation to LintModule core (EARS-D1)\n * - Schema version detection (EARS-E1)\n * - Error filtering (EARS-F1)\n *\n * @see fs_lint_module.md for EARS specifications\n * @module lint/fs\n */\n\n/**\n * [EARS-F1] Ajv error message patterns for oneOf/if-then-else schema validation.\n * These are standard messages from Ajv when validating JSON Schema with oneOf + if/then/else.\n *\n * When a record has additionalProperties errors, Ajv also generates redundant errors\n * from all the oneOf branches that don't match. These should be filtered out.\n *\n * @see https://ajv.js.org/api.html#validation-errors\n */\nconst AJV_ONEOF_ERROR_PATTERNS = {\n /** Message from \"else: false\" in if/then/else schema */\n BOOLEAN_SCHEMA_FALSE: 'boolean schema is false',\n /** Message when if condition doesn't match \"else\" */\n MUST_MATCH_ELSE: 'must match \"else\" schema',\n /** Message when if condition doesn't match \"then\" */\n MUST_MATCH_THEN: 'must match \"then\" schema',\n /** Path prefix for oneOf errors */\n ONEOF_PATH: '#/oneOf/',\n} as const;\n\n/**\n * [EARS-F1] Checks if an error message is a redundant oneOf/if-then-else error from Ajv.\n * These errors are noise when the root cause is additionalProperties.\n */\nfunction isRedundantOneOfError(message: string): boolean {\n return (\n message.includes(AJV_ONEOF_ERROR_PATTERNS.BOOLEAN_SCHEMA_FALSE) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.MUST_MATCH_ELSE) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.MUST_MATCH_THEN) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.ONEOF_PATH)\n );\n}\n\nimport { promises as fs } from \"fs\";\nimport { join, dirname, basename } from \"path\";\nimport { readdir } from \"fs/promises\";\nimport type {\n IFsLintModule,\n FsLintModuleDependencies,\n FsLintOptions,\n FsFixOptions,\n FileSystem,\n} from \"./fs_lint.types\";\nimport type {\n LintReport,\n LintResult,\n FixReport,\n FixResult,\n ValidatorType,\n ILintModule,\n LintRecordContext,\n FixRecordOptions,\n} from \"../lint.types\";\n// Note: IIndexerAdapter is in FsLintModuleDependencies but passed to LintModule, not used directly\nimport type {\n GitGovRecord,\n TaskRecord,\n CycleRecord,\n GitGovRecordType\n} from \"../../record_types\";\nimport { isTaskPayload, isCyclePayload } from \"../../record_types/type_guards\";\nimport { extractRecordIdFromPath, getEntityTypeFromPath, inferEntityTypeFromId } from \"../../utils/id_parser\";\nimport { chunkArray } from \"../../utils/array_utils\";\nimport { createLogger } from \"../../logger\";\nimport { calculatePayloadChecksum } from \"../../crypto/checksum\";\nimport {\n loadTaskRecord,\n loadActorRecord,\n loadAgentRecord,\n loadCycleRecord,\n loadExecutionRecord,\n loadChangelogRecord,\n loadFeedbackRecord\n} from \"../../record_factories\";\nimport { DetailedValidationError } from \"../../record_validations/common\";\n\nconst logger = createLogger(\"[FsLint] \");\n\n/**\n * Filesystem-aware lint module.\n * Wraps LintModule (pure) and adds I/O operations.\n *\n * @implements {IFsLintModule}\n */\nexport class FsLintModule implements IFsLintModule {\n private readonly projectRoot: string;\n private readonly lintModule: ILintModule;\n private readonly fileSystem: FileSystem;\n private lastBackupPath: string | null = null;\n\n /**\n * Constructor for FsLintModule.\n *\n * @param dependencies - Module dependencies\n */\n constructor(dependencies: FsLintModuleDependencies) {\n if (!dependencies.projectRoot) {\n throw new Error(\"projectRoot is required for FsLintModule\");\n }\n if (!dependencies.lintModule) {\n throw new Error(\"lintModule is required for FsLintModule\");\n }\n this.projectRoot = dependencies.projectRoot;\n this.lintModule = dependencies.lintModule;\n // Note: indexerAdapter is passed to LintModule, not used directly here\n\n // FileSystem with fallback to Node.js fs\n this.fileSystem = dependencies.fileSystem ?? {\n readFile: async (path: string, encoding: string) => {\n return fs.readFile(path, encoding as BufferEncoding);\n },\n writeFile: async (path: string, content: string) => {\n await fs.writeFile(path, content, \"utf-8\");\n },\n exists: async (path: string) => {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n },\n unlink: async (path: string) => {\n await fs.unlink(path);\n },\n readdir: async (path: string) => {\n return readdir(path);\n }\n };\n }\n\n // ==================== ILintModule Delegation ====================\n\n /**\n * Delegates to LintModule.lintRecord() for pure validation.\n */\n lintRecord(record: GitGovRecord, context: LintRecordContext): LintResult[] {\n return this.lintModule.lintRecord(record, context);\n }\n\n /**\n * Delegates to LintModule.fixRecord() for pure fix.\n */\n fixRecord(record: GitGovRecord, results: LintResult[], options: FixRecordOptions): GitGovRecord {\n return this.lintModule.fixRecord(record, results, options);\n }\n\n // ==================== IFsLintModule Methods ====================\n\n /**\n * [EARS-A1] Scans directories and validates all records.\n *\n * @param options - Configuration options\n * @returns Consolidated lint report\n */\n async lint(options?: Partial<FsLintOptions>): Promise<LintReport> {\n const startTime = Date.now();\n\n const opts: FsLintOptions = {\n path: options?.path ?? \".gitgov/\",\n validateReferences: options?.validateReferences ?? false,\n validateActors: options?.validateActors ?? false,\n validateChecksums: options?.validateChecksums ?? true,\n validateSignatures: options?.validateSignatures ?? true,\n validateTimestamps: options?.validateTimestamps ?? true,\n validateFileNaming: options?.validateFileNaming ?? true,\n failFast: options?.failFast ?? false,\n concurrent: options?.concurrent ?? true,\n concurrencyLimit: options?.concurrencyLimit ?? 10\n };\n\n const results: LintResult[] = [];\n\n // Suppress console.warn during lint\n const originalWarn = console.warn;\n console.warn = () => {};\n\n try {\n // 1. Discovery: Find all records\n const recordsWithTypes = await this.discoverAllRecordsWithTypes(opts.path);\n logger.info(`Starting lint validation for ${recordsWithTypes.length} records`);\n\n // 2. Validation Loop\n if (opts.concurrent) {\n const batches = chunkArray(recordsWithTypes, opts.concurrencyLimit!);\n for (const batch of batches) {\n const batchResults = await Promise.all(\n batch.map(({ id, type }) => this.lintSingleRecord(id, opts, type))\n );\n for (const batchResult of batchResults) {\n results.push(...batchResult);\n if (opts.failFast && batchResult.some(r => r.level === \"error\")) {\n break;\n }\n }\n if (opts.failFast && results.some(r => r.level === \"error\")) {\n break;\n }\n }\n } else {\n for (const { id, type } of recordsWithTypes) {\n const recordResults = await this.lintSingleRecord(id, opts, type);\n results.push(...recordResults);\n if (opts.failFast && recordResults.some(r => r.level === \"error\")) {\n break;\n }\n }\n }\n\n const executionTime = Date.now() - startTime;\n const errors = results.filter(r => r.level === \"error\").length;\n const warnings = results.filter(r => r.level === \"warning\").length;\n const fixable = results.filter(r => r.fixable).length;\n\n logger.info(`Lint completed in ${executionTime}ms: ${recordsWithTypes.length} files, ${errors} errors, ${warnings} warnings`);\n\n return {\n summary: { filesChecked: recordsWithTypes.length, errors, warnings, fixable, executionTime },\n results,\n metadata: { timestamp: new Date().toISOString(), options: opts, version: \"1.0.0\" }\n };\n } finally {\n console.warn = originalWarn;\n }\n }\n\n /**\n * Validates a specific file.\n *\n * @param filePath - Path to the file to validate\n * @param options - Configuration options\n * @returns Lint report for this single file\n */\n async lintFile(filePath: string, options?: Partial<FsLintOptions>): Promise<LintReport> {\n const startTime = Date.now();\n const recordId = extractRecordIdFromPath(filePath);\n const entityType = getEntityTypeFromPath(filePath) || inferEntityTypeFromId(recordId);\n\n const opts: FsLintOptions = {\n path: filePath,\n validateReferences: options?.validateReferences ?? false,\n validateActors: options?.validateActors ?? false,\n validateChecksums: options?.validateChecksums ?? true,\n validateSignatures: options?.validateSignatures ?? true,\n validateTimestamps: options?.validateTimestamps ?? true,\n validateFileNaming: options?.validateFileNaming ?? true,\n failFast: options?.failFast ?? false,\n concurrent: false,\n concurrencyLimit: 1\n };\n\n const originalWarn = console.warn;\n console.warn = () => {};\n\n try {\n const results = await this.lintSingleRecord(recordId, opts, entityType);\n\n const executionTime = Date.now() - startTime;\n const errors = results.filter(r => r.level === \"error\").length;\n const warnings = results.filter(r => r.level === \"warning\").length;\n const fixable = results.filter(r => r.fixable).length;\n\n return {\n summary: { filesChecked: 1, errors, warnings, fixable, executionTime },\n results,\n metadata: { timestamp: new Date().toISOString(), options: opts, version: \"1.0.0\" }\n };\n } finally {\n console.warn = originalWarn;\n }\n }\n\n /**\n * Applies automatic repairs to files, creating backups.\n *\n * @param lintReport - Lint report with detected problems\n * @param fixOptions - Options for the fix operation\n * @returns Report of applied repairs\n */\n async fix(lintReport: LintReport, fixOptions?: Partial<FsFixOptions>): Promise<FixReport> {\n const opts: FsFixOptions = {\n ...(fixOptions?.fixTypes && { fixTypes: fixOptions.fixTypes }),\n createBackups: fixOptions?.createBackups ?? true,\n keyId: fixOptions?.keyId ?? \"system:migrator\",\n dryRun: fixOptions?.dryRun ?? false,\n ...(fixOptions?.privateKey && { privateKey: fixOptions.privateKey })\n };\n\n const fixes: FixResult[] = [];\n\n let fixableResults = lintReport.results.filter(r => r.fixable);\n if (opts.fixTypes && opts.fixTypes.length > 0) {\n fixableResults = fixableResults.filter(r => opts.fixTypes!.includes(r.validator));\n }\n\n logger.info(`Starting fix operation for ${fixableResults.length} fixable problems`);\n\n // Group by file and validator\n const resultsByFile = new Map<string, Map<ValidatorType, LintResult[]>>();\n for (const result of fixableResults) {\n if (!resultsByFile.has(result.filePath)) {\n resultsByFile.set(result.filePath, new Map());\n }\n const fileResults = resultsByFile.get(result.filePath)!;\n if (!fileResults.has(result.validator)) {\n fileResults.set(result.validator, []);\n }\n fileResults.get(result.validator)!.push(result);\n }\n\n for (const [, validatorMap] of resultsByFile) {\n for (const [, results] of validatorMap) {\n const primaryResult = results[0]!;\n let backupPath: string | undefined;\n\n try {\n if (opts.dryRun) {\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Would fix ${primaryResult.validator} (${results.length} error${results.length === 1 ? '' : 's'})`,\n success: true\n });\n continue;\n }\n\n // Create backup\n if (opts.createBackups && !backupPath) {\n backupPath = await this.createBackup(primaryResult.filePath);\n }\n\n // Apply fix\n await this.applyFix(primaryResult, opts, results);\n\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Fixed ${primaryResult.validator} (${results.length} error${results.length === 1 ? '' : 's'})`,\n success: true,\n ...(backupPath && { backupPath })\n });\n\n logger.debug(`Successfully fixed ${primaryResult.filePath}`);\n\n } catch (error) {\n if (opts.createBackups && backupPath) {\n try {\n await this.restoreBackup(primaryResult.filePath);\n logger.warn(`Restored backup for ${primaryResult.filePath}`);\n } catch {\n logger.error(`Failed to restore backup for ${primaryResult.filePath}`);\n }\n }\n\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Failed to fix ${primaryResult.validator}`,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n ...(backupPath && { backupPath })\n });\n }\n }\n }\n\n const summary = {\n fixed: fixes.filter(f => f.success).length,\n failed: fixes.filter(f => !f.success).length,\n backupsCreated: opts.createBackups ? fixes.filter(f => f.backupPath).length : 0\n };\n\n logger.info(`Fix completed: ${summary.fixed} fixed, ${summary.failed} failed`);\n\n return { summary, fixes };\n }\n\n // ==================== Private Methods ====================\n\n /**\n * Validates a single record by reading from filesystem.\n * @private\n */\n private async lintSingleRecord(\n recordId: string,\n options: FsLintOptions,\n entityType: Exclude<GitGovRecordType, 'custom'>\n ): Promise<LintResult[]> {\n const results: LintResult[] = [];\n let filePath: string;\n\n if (options.path && options.path.endsWith('.json')) {\n // Resolve path: absolute paths used directly, relative paths joined with projectRoot\n filePath = options.path.startsWith('/')\n ? options.path\n : join(this.projectRoot, options.path);\n } else {\n filePath = this.getFilePath(recordId, entityType);\n }\n\n try {\n // Read and parse file\n const content = await this.fileSystem.readFile(filePath, 'utf-8');\n const raw = JSON.parse(content);\n\n // Load with appropriate loader\n let record: GitGovRecord;\n switch (entityType) {\n case 'task': record = loadTaskRecord(raw); break;\n case 'actor': record = loadActorRecord(raw); break;\n case 'agent': record = loadAgentRecord(raw); break;\n case 'cycle': record = loadCycleRecord(raw); break;\n case 'execution': record = loadExecutionRecord(raw); break;\n case 'changelog': record = loadChangelogRecord(raw); break;\n case 'feedback': record = loadFeedbackRecord(raw); break;\n default: record = raw as GitGovRecord;\n }\n\n // [EARS-D1] Use pure LintModule for validation\n const lintResults = this.lintModule.lintRecord(record, {\n recordId,\n entityType,\n filePath\n });\n results.push(...lintResults);\n\n // File naming validation (filesystem-specific)\n if (options.validateFileNaming) {\n const namingResults = this.validateFileNaming(record, recordId, filePath, entityType);\n results.push(...namingResults);\n }\n\n } catch (error) {\n if (error instanceof DetailedValidationError) {\n const hasAdditionalProperties = error.errors.some(e =>\n e.message.includes(\"must NOT have additional properties\")\n );\n // [EARS-F1] Filter redundant oneOf/if-then-else errors when the root cause is additionalProperties\n const filteredErrors = hasAdditionalProperties\n ? error.errors.filter(e => !isRedundantOneOfError(e.message))\n : error.errors;\n\n for (const err of filteredErrors) {\n results.push({\n level: \"error\",\n filePath,\n validator: this.detectValidatorType(err.message, err.field),\n message: `${err.field}: ${err.message}`,\n entity: { type: entityType, id: recordId },\n fixable: this.isFixable(err.message),\n context: {\n ...(err.field && { field: err.field }),\n ...(err.value !== undefined && { actual: err.value })\n }\n });\n }\n } else {\n const fsError = error as NodeJS.ErrnoException;\n let message: string;\n if (fsError.code === 'ENOENT') {\n message = `Record file not found: ${recordId}`;\n } else if (error instanceof SyntaxError) {\n message = `Invalid JSON in record file: ${recordId}`;\n } else {\n message = error instanceof Error ? error.message : String(error);\n }\n\n results.push({\n level: \"error\",\n filePath,\n validator: \"SCHEMA_VALIDATION\",\n message,\n entity: { type: entityType, id: recordId },\n fixable: false\n });\n }\n }\n\n return results;\n }\n\n /**\n * [EARS-B1, EARS-B2] Validates file naming conventions.\n * @private\n */\n private validateFileNaming(\n _record: GitGovRecord,\n recordId: string,\n filePath: string,\n entityType: Exclude<GitGovRecordType, 'custom'>\n ): LintResult[] {\n const results: LintResult[] = [];\n\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n\n // [EARS-B1] Validate correct directory\n const expectedDir = `.gitgov/${dirNameMap[entityType]}`;\n if (!filePath.includes(expectedDir)) {\n results.push({\n level: \"error\",\n filePath,\n validator: \"FILE_NAMING_CONVENTION\",\n message: `File should be in ${expectedDir}/ directory`,\n entity: { type: entityType, id: recordId },\n fixable: false,\n context: { field: \"directory\", actual: dirname(filePath), expected: expectedDir }\n });\n }\n\n // [EARS-B2] Validate filename matches ID\n const expectedFilename = `${recordId}.json`;\n const actualFilename = basename(filePath);\n if (actualFilename !== expectedFilename) {\n results.push({\n level: \"error\",\n filePath,\n validator: \"FILE_NAMING_CONVENTION\",\n message: `Filename '${actualFilename}' does not match entity ID`,\n entity: { type: entityType, id: recordId },\n fixable: false,\n context: { field: \"filename\", actual: actualFilename, expected: expectedFilename }\n });\n }\n\n return results;\n }\n\n /**\n * [EARS-A1] Discovers all records with their types by scanning filesystem.\n * @private\n */\n private async discoverAllRecordsWithTypes(_path?: string): Promise<Array<{ id: string; type: Exclude<GitGovRecordType, 'custom'> }>> {\n // Note: _path parameter is deprecated, projectRoot is now injected via constructor\n const recordTypes: Array<Exclude<GitGovRecordType, 'custom'>> = [\n 'actor', 'agent', 'cycle', 'task', 'execution', 'changelog', 'feedback'\n ];\n const allRecords: Array<{ id: string; type: Exclude<GitGovRecordType, 'custom'> }> = [];\n\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n\n for (const recordType of recordTypes) {\n const dirPath = join(this.projectRoot, '.gitgov', dirNameMap[recordType]);\n try {\n const files = await readdir(dirPath);\n const jsonFiles = files.filter(f => f.endsWith('.json'));\n const records = jsonFiles.map(f => ({ id: f.replace('.json', ''), type: recordType }));\n allRecords.push(...records);\n } catch {\n // Directory doesn't exist, skip\n }\n }\n\n return allRecords;\n }\n\n /**\n * Gets file path for a record.\n * @private\n */\n private getFilePath(recordId: string, entityType: Exclude<GitGovRecordType, 'custom'>): string {\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n const dirName = dirNameMap[entityType];\n const safeId = recordId.replace(/:/g, '_');\n\n return join(this.projectRoot, \".gitgov\", dirName, `${safeId}.json`);\n }\n\n /**\n * [EARS-C1] Creates a backup of a file before modification.\n * @private\n */\n private async createBackup(filePath: string): Promise<string> {\n const timestamp = Date.now();\n const backupPath = `${filePath}.backup-${timestamp}`;\n const content = await this.fileSystem.readFile(filePath, \"utf-8\");\n await this.fileSystem.writeFile(backupPath, content);\n this.lastBackupPath = backupPath;\n return backupPath;\n }\n\n /**\n * [EARS-C2] Restores file from backup if fix fails.\n * @private\n */\n private async restoreBackup(filePath: string): Promise<void> {\n if (this.lastBackupPath) {\n const exists = await this.fileSystem.exists(this.lastBackupPath);\n if (exists) {\n const content = await this.fileSystem.readFile(this.lastBackupPath, \"utf-8\");\n await this.fileSystem.writeFile(filePath, content);\n this.lastBackupPath = null;\n return;\n }\n }\n throw new Error(`No backup found for ${filePath}`);\n }\n\n /**\n * Applies a fix to a file.\n * @private\n */\n private async applyFix(result: LintResult, options: FsFixOptions, allErrors: LintResult[]): Promise<void> {\n switch (result.validator) {\n case \"EMBEDDED_METADATA_STRUCTURE\":\n await this.fixLegacyRecord(result, options, allErrors);\n break;\n case \"BIDIRECTIONAL_CONSISTENCY\":\n await this.fixBidirectionalReference(result);\n break;\n case \"CHECKSUM_VERIFICATION\":\n await this.recalculateChecksum(result);\n break;\n case \"SIGNATURE_STRUCTURE\":\n await this.fixSignatureStructure(result, options, allErrors);\n break;\n default:\n throw new Error(`Fix not implemented for validator: ${result.validator}`);\n }\n }\n\n /**\n * Fixes legacy record with embedded metadata issues.\n * @private\n */\n private async fixLegacyRecord(result: LintResult, options: FsFixOptions, allErrors?: LintResult[]): Promise<void> {\n if (!options.privateKey) {\n throw new Error(\"privateKey is required to fix legacy records\");\n }\n\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n // Use pure LintModule to fix\n const fixedRecord = this.lintModule.fixRecord(record, allErrors || [result], {\n fixTypes: ['EMBEDDED_METADATA_STRUCTURE'],\n ...(options.keyId !== undefined && { keyId: options.keyId }),\n privateKey: options.privateKey\n });\n\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(fixedRecord, null, 2));\n logger.info(`Fixed legacy record: ${result.filePath}`);\n }\n\n /**\n * Fixes bidirectional reference inconsistencies.\n * @private\n */\n private async fixBidirectionalReference(result: LintResult): Promise<void> {\n const entityType = result.entity.type;\n const recordId = result.entity.id;\n const filePath = this.getFilePath(recordId, entityType);\n\n const content = await this.fileSystem.readFile(filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n if (entityType === \"task\" && isTaskPayload(record.payload)) {\n const taskPayload = record.payload;\n if (taskPayload.cycleIds) {\n for (const cycleId of taskPayload.cycleIds) {\n const cycleFilePath = this.getFilePath(cycleId, \"cycle\");\n try {\n const cycleContent = await this.fileSystem.readFile(cycleFilePath, \"utf-8\");\n const cycleRecord = JSON.parse(cycleContent) as GitGovRecord;\n const cyclePayload = cycleRecord.payload as CycleRecord;\n\n if (!cyclePayload.taskIds) {\n cyclePayload.taskIds = [];\n }\n if (!cyclePayload.taskIds.includes(recordId)) {\n cyclePayload.taskIds.push(recordId);\n await this.fileSystem.writeFile(cycleFilePath, JSON.stringify(cycleRecord, null, 2));\n logger.info(`Added task ${recordId} to cycle ${cycleId}`);\n }\n } catch {\n // Cycle file doesn't exist, skip\n }\n }\n }\n } else if (entityType === \"cycle\" && isCyclePayload(record.payload)) {\n const cyclePayload = record.payload;\n if (cyclePayload.taskIds) {\n for (const taskId of cyclePayload.taskIds) {\n const taskFilePath = this.getFilePath(taskId, \"task\");\n try {\n const taskContent = await this.fileSystem.readFile(taskFilePath, \"utf-8\");\n const taskRecord = JSON.parse(taskContent) as GitGovRecord;\n const taskPayload = taskRecord.payload as TaskRecord;\n\n if (!taskPayload.cycleIds) {\n taskPayload.cycleIds = [];\n }\n if (!taskPayload.cycleIds.includes(recordId)) {\n taskPayload.cycleIds.push(recordId);\n await this.fileSystem.writeFile(taskFilePath, JSON.stringify(taskRecord, null, 2));\n logger.info(`Added cycle ${recordId} to task ${taskId}`);\n }\n } catch {\n // Task file doesn't exist, skip\n }\n }\n }\n }\n }\n\n /**\n * Recalculates checksum for a record.\n * @private\n */\n private async recalculateChecksum(result: LintResult): Promise<void> {\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n if (!record.header || !record.payload) {\n throw new Error(\"Cannot recalculate checksum: invalid record structure\");\n }\n\n record.header.payloadChecksum = calculatePayloadChecksum(record.payload);\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(record, null, 2));\n logger.info(`Recalculated checksum for: ${result.filePath}`);\n }\n\n /**\n * Fixes signature structure issues.\n * @private\n */\n private async fixSignatureStructure(result: LintResult, options: FsFixOptions, allErrors: LintResult[]): Promise<void> {\n if (!options.privateKey) {\n throw new Error(\"privateKey is required to fix signature\");\n }\n\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n const fixedRecord = this.lintModule.fixRecord(record, allErrors, {\n fixTypes: ['SIGNATURE_STRUCTURE'],\n ...(options.keyId !== undefined && { keyId: options.keyId }),\n privateKey: options.privateKey\n });\n\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(fixedRecord, null, 2));\n logger.info(`Fixed signature structure: ${result.filePath}`);\n }\n\n /**\n * [EARS-E1] Detects validator type from error message.\n * Includes detection of SCHEMA_VERSION_MISMATCH for outdated schemas.\n * @private\n */\n private detectValidatorType(message: string, field?: string): ValidatorType {\n const text = `${message} ${field || ''}`.toLowerCase();\n\n if (text.includes(\"checksum\")) return \"CHECKSUM_VERIFICATION\";\n if (text.includes(\"signature\") || text.includes(\"/signatures/\")) return \"SIGNATURE_STRUCTURE\";\n if (text.includes(\"header\") || text.includes(\"payload\") || text.includes(\"/header/\")) return \"EMBEDDED_METADATA_STRUCTURE\";\n\n // [EARS-E1] Detect schema version mismatch indicators\n const versionMismatchIndicators = [\n 'required in v', 'deprecated', 'obsolete', 'schema version', 'migration'\n ];\n if (versionMismatchIndicators.some(i => text.includes(i)) || /v\\d+|version\\s+\\d+/i.test(text)) {\n return \"SCHEMA_VERSION_MISMATCH\";\n }\n\n return \"SCHEMA_VALIDATION\";\n }\n\n /**\n * Determines if an error is fixable.\n * @private\n */\n private isFixable(message: string): boolean {\n const text = message.toLowerCase();\n if (text.includes(\"header\") || text.includes(\"metadata\")) return true;\n if (text.includes(\"additional properties\")) return true;\n if (text.includes(\"checksum\")) return true;\n if (text.includes(\"signature\") && text.includes(\"format\")) return true;\n return false;\n }\n}\n","/**\n * ESM Helper - Provides access to import.meta for use in ESM contexts\n * \n * This file is separated because import.meta cannot be used in Jest/CommonJS tests.\n * Jest will mock this module when running tests.\n */\n\n/**\n * Get the current module URL (import.meta.url)\n * Returns null in non-ESM contexts (like Jest tests)\n */\nexport function getImportMetaUrl(): string | null {\n try {\n return import.meta.url;\n } catch {\n return null;\n }\n}\n\n","import { promises as fs, existsSync } from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { GitGovConfig } from '../../config_manager';\nimport type { IProjectInitializer, EnvironmentValidation } from '../project_initializer';\nimport { createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { getImportMetaUrl } from '../../utils/esm_helper';\nimport { createLogger } from '../../logger';\n\nconst logger = createLogger('[FsProjectInitializer] ');\n\n/**\n * Canonical directory structure for .gitgov/\n */\nconst GITGOV_DIRECTORIES = [\n 'actors',\n 'cycles',\n 'tasks',\n 'executions',\n 'feedbacks',\n 'changelogs',\n] as const;\n\n/**\n * FsProjectInitializer - Filesystem implementation of IProjectInitializer.\n *\n * Initializes GitGovernance projects on the local filesystem,\n * creating the .gitgov/ directory structure and configuration files.\n *\n * The projectRoot is injected at construction time (DI from CLI/bootstrap).\n *\n * @example\n * ```typescript\n * const initializer = new FsProjectInitializer('/path/to/project');\n *\n * const validation = await initializer.validateEnvironment();\n * if (!validation.isValid) {\n * console.log(validation.warnings);\n * return;\n * }\n *\n * await initializer.createProjectStructure();\n * await initializer.writeConfig(config);\n * await initializer.initializeSession(actorId);\n * await initializer.copyAgentPrompt();\n * await initializer.setupGitIntegration();\n * ```\n */\nexport class FsProjectInitializer implements IProjectInitializer {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n // ==================== IProjectInitializer Interface Methods ====================\n\n /**\n * Creates the .gitgov/ directory structure.\n */\n async createProjectStructure(): Promise<void> {\n const gitgovPath = path.join(this.projectRoot, '.gitgov');\n\n await fs.mkdir(gitgovPath, { recursive: true });\n\n for (const dir of GITGOV_DIRECTORIES) {\n await fs.mkdir(path.join(gitgovPath, dir), { recursive: true });\n }\n }\n\n /**\n * Checks if .gitgov/config.json exists.\n */\n async isInitialized(): Promise<boolean> {\n const configPath = path.join(this.projectRoot, '.gitgov', 'config.json');\n try {\n await fs.access(configPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Writes config.json to .gitgov/\n */\n async writeConfig(config: GitGovConfig): Promise<void> {\n const configPath = path.join(this.projectRoot, '.gitgov', 'config.json');\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Creates .session.json with initial actor state.\n */\n async initializeSession(actorId: string): Promise<void> {\n const sessionPath = path.join(this.projectRoot, '.gitgov', '.session.json');\n const session = {\n lastSession: {\n actorId,\n timestamp: new Date().toISOString(),\n },\n actorState: {\n [actorId]: {\n lastSync: new Date().toISOString(),\n syncStatus: {\n status: 'synced' as const,\n },\n },\n },\n };\n\n await fs.writeFile(sessionPath, JSON.stringify(session, null, 2), 'utf-8');\n }\n\n /**\n * Reads a file from the filesystem.\n */\n async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, 'utf-8');\n }\n\n /**\n * Gets the path for an actor record.\n */\n getActorPath(actorId: string): string {\n return path.join(this.projectRoot, '.gitgov', 'actors', `${actorId}.json`);\n }\n\n /**\n * Validates environment for GitGovernance initialization.\n * Checks: Git repo exists, write permissions, not already initialized.\n */\n async validateEnvironment(): Promise<EnvironmentValidation> {\n const warnings: string[] = [];\n const suggestions: string[] = [];\n\n try {\n // Check if it's a Git repository\n const gitPath = path.join(this.projectRoot, '.git');\n const isGitRepo = existsSync(gitPath);\n\n if (!isGitRepo) {\n warnings.push(`Not a Git repository in directory: ${this.projectRoot}`);\n suggestions.push(\"Run 'git init' to initialize a Git repository first\");\n }\n\n // Check write permissions\n let hasWritePermissions = false;\n try {\n const testFile = path.join(this.projectRoot, '.gitgov-test');\n await fs.writeFile(testFile, 'test');\n await fs.unlink(testFile);\n hasWritePermissions = true;\n } catch {\n warnings.push('No write permissions in target directory');\n suggestions.push('Ensure you have write permissions in the target directory');\n }\n\n // Check if already initialized\n const isAlreadyInitialized = await this.isInitialized();\n if (isAlreadyInitialized) {\n warnings.push(`GitGovernance already initialized in directory: ${this.projectRoot}`);\n suggestions.push(\"Use 'gitgov status' to check current state or choose a different directory\");\n }\n\n // VCS status checks (only if it's a git repo)\n let hasRemote = false;\n let hasCommits = false;\n let currentBranch = '';\n\n if (isGitRepo) {\n try {\n execSync('git remote get-url origin', {\n cwd: this.projectRoot,\n stdio: 'pipe',\n });\n hasRemote = true;\n } catch {\n hasRemote = false;\n }\n\n try {\n currentBranch = execSync('git branch --show-current', {\n cwd: this.projectRoot,\n encoding: 'utf-8',\n stdio: 'pipe',\n }).trim();\n } catch {\n currentBranch = '';\n }\n\n try {\n execSync('git log --oneline -1', {\n cwd: this.projectRoot,\n stdio: 'pipe',\n });\n hasCommits = true;\n } catch {\n hasCommits = false;\n }\n }\n\n const isValid = isGitRepo && hasWritePermissions && !isAlreadyInitialized;\n\n const result: EnvironmentValidation = {\n isValid,\n isGitRepo,\n hasWritePermissions,\n isAlreadyInitialized,\n warnings,\n suggestions,\n hasRemote,\n hasCommits,\n currentBranch,\n };\n\n if (isAlreadyInitialized) {\n result.gitgovPath = path.join(this.projectRoot, '.gitgov');\n }\n\n return result;\n } catch (error) {\n warnings.push(`Environment validation error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n suggestions.push('Check file system permissions and try again');\n\n return {\n isValid: false,\n isGitRepo: false,\n hasWritePermissions: false,\n isAlreadyInitialized: false,\n warnings,\n suggestions,\n };\n }\n }\n\n /**\n * Copies the @gitgov agent prompt to project root for IDE access.\n */\n async copyAgentPrompt(): Promise<void> {\n const targetPrompt = path.join(this.projectRoot, 'gitgov');\n const potentialSources: string[] = [];\n\n // 1. Development scenario: search in src/docs/generated/\n potentialSources.push(\n path.join(process.cwd(), 'src/docs/generated/gitgov_agent.md')\n );\n\n // 2. NPM installation: use require.resolve\n try {\n const metaUrl = getImportMetaUrl();\n if (metaUrl) {\n const require = createRequire(metaUrl);\n const pkgJsonPath = require.resolve('@gitgov/core/package.json');\n const pkgRoot = path.dirname(pkgJsonPath);\n potentialSources.push(path.join(pkgRoot, 'dist/src/docs/generated/gitgov_agent.md'));\n }\n } catch {\n // require.resolve failed - continue\n }\n\n // 3. Build fallback: relative to compiled __dirname\n try {\n const metaUrl = getImportMetaUrl();\n if (metaUrl) {\n const __filename = fileURLToPath(metaUrl);\n const __dirname = path.dirname(__filename);\n potentialSources.push(path.resolve(__dirname, '../../docs/generated/gitgov_agent.md'));\n }\n } catch {\n // import.meta not available - continue\n }\n\n // Find and copy the first accessible file\n for (const source of potentialSources) {\n try {\n await fs.access(source);\n await fs.copyFile(source, targetPrompt);\n logger.debug(`@gitgov agent prompt copied to project root (./gitgov)\\n`);\n return;\n } catch {\n continue;\n }\n }\n\n // Graceful degradation\n console.warn(\n 'Warning: Could not copy @gitgov agent prompt. Project will work but AI assistant may not have local instructions.'\n );\n }\n\n /**\n * Sets up .gitignore for GitGovernance files.\n */\n async setupGitIntegration(): Promise<void> {\n const gitignorePath = path.join(this.projectRoot, '.gitignore');\n const gitignoreContent = `\n# GitGovernance\n# Ignore entire .gitgov/ directory (state lives in gitgov-state branch)\n.gitgov/\n\n# Ignore agent prompt file (project-specific, created by gitgov init)\ngitgov\n`;\n\n try {\n let existingContent = '';\n try {\n existingContent = await fs.readFile(gitignorePath, 'utf-8');\n } catch {\n // File doesn't exist, will create new\n }\n\n if (existingContent && !existingContent.includes('# GitGovernance')) {\n await fs.appendFile(gitignorePath, gitignoreContent);\n } else if (!existingContent) {\n await fs.writeFile(gitignorePath, gitignoreContent);\n }\n } catch (error) {\n console.warn('Failed to setup Git integration:', error);\n }\n }\n\n /**\n * Removes .gitgov/ directory (for rollback on failed init).\n */\n async rollback(): Promise<void> {\n const gitgovPath = path.join(this.projectRoot, '.gitgov');\n try {\n await fs.access(gitgovPath);\n await fs.rm(gitgovPath, { recursive: true, force: true });\n } catch {\n // Directory doesn't exist, nothing to clean up\n }\n }\n}\n","/**\n * Custom Error Classes for GitModule\n * \n * These errors provide typed exceptions for better error handling\n * and diagnostics in the Git module operations.\n */\n\n/**\n * Base error class for all Git-related errors\n */\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n Object.setPrototypeOf(this, GitError.prototype);\n }\n}\n\n/**\n * Error thrown when a Git command fails\n */\nexport class GitCommandError extends GitError {\n public readonly stderr: string;\n public readonly stdout?: string | undefined;\n public readonly command?: string | undefined;\n\n constructor(message: string, stderr: string = '', command?: string | undefined, stdout?: string) {\n super(message);\n this.name = 'GitCommandError';\n this.stderr = stderr;\n this.stdout = stdout;\n this.command = command;\n Object.setPrototypeOf(this, GitCommandError.prototype);\n }\n}\n\n/**\n * Error thrown when a branch does not exist\n */\nexport class BranchNotFoundError extends GitError {\n public readonly branchName: string;\n\n constructor(branchName: string) {\n super(`Branch not found: ${branchName}`);\n this.name = 'BranchNotFoundError';\n this.branchName = branchName;\n Object.setPrototypeOf(this, BranchNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when a file does not exist in a commit\n */\nexport class FileNotFoundError extends GitError {\n public readonly filePath: string;\n public readonly commitHash: string;\n\n constructor(filePath: string, commitHash: string) {\n super(`File not found: ${filePath} in commit ${commitHash}`);\n this.name = 'FileNotFoundError';\n this.filePath = filePath;\n this.commitHash = commitHash;\n Object.setPrototypeOf(this, FileNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when a merge conflict occurs\n */\nexport class MergeConflictError extends GitError {\n public readonly conflictedFiles: string[];\n\n constructor(conflictedFiles: string[]) {\n super(`Merge conflict detected in ${conflictedFiles.length} file(s)`);\n this.name = 'MergeConflictError';\n this.conflictedFiles = conflictedFiles;\n Object.setPrototypeOf(this, MergeConflictError.prototype);\n }\n}\n\n/**\n * Error thrown when a rebase conflict occurs\n */\nexport class RebaseConflictError extends GitError {\n public readonly conflictedFiles: string[];\n\n constructor(conflictedFiles: string[]) {\n super(`Rebase conflict detected in ${conflictedFiles.length} file(s)`);\n this.name = 'RebaseConflictError';\n this.conflictedFiles = conflictedFiles;\n Object.setPrototypeOf(this, RebaseConflictError.prototype);\n }\n}\n\n/**\n * Error thrown when trying to continue/abort a rebase that is not in progress\n */\nexport class RebaseNotInProgressError extends GitError {\n constructor() {\n super('No rebase in progress');\n this.name = 'RebaseNotInProgressError';\n Object.setPrototypeOf(this, RebaseNotInProgressError.prototype);\n }\n}\n\n/**\n * Error thrown when trying to create a branch that already exists\n */\nexport class BranchAlreadyExistsError extends GitError {\n public readonly branchName: string;\n\n constructor(branchName: string) {\n super(`Branch already exists: ${branchName}`);\n this.name = 'BranchAlreadyExistsError';\n this.branchName = branchName;\n Object.setPrototypeOf(this, BranchAlreadyExistsError.prototype);\n }\n}\n\n","/**\n * LocalGitModule - Local Git Operations via CLI\n *\n * This module provides a business-agnostic abstraction layer for interacting\n * with the local Git repository. It exposes semantic methods instead of raw\n * Git commands, with comprehensive error handling and type safety.\n *\n * Uses execCommand (injected) to run git CLI commands.\n *\n * @module git/local\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { IGitModule } from '..';\nimport type {\n GitModuleDependencies,\n ExecOptions,\n ExecResult,\n GetCommitHistoryOptions,\n CommitInfo,\n ChangedFile,\n CommitAuthor,\n} from '../types';\nimport {\n GitCommandError,\n BranchNotFoundError,\n BranchAlreadyExistsError,\n FileNotFoundError,\n MergeConflictError,\n RebaseConflictError,\n RebaseNotInProgressError,\n} from '../errors';\nimport { createLogger } from '../../logger/logger';\n\nconst logger = createLogger('[LocalGitModule] ');\n\n/**\n * LocalGitModule - CLI-based implementation of IGitModule\n *\n * All operations are async and use dependency injection for testability.\n * Errors are transformed into typed exceptions for better handling.\n *\n * For unit tests without git, use MemoryGitModule instead.\n */\nexport class LocalGitModule implements IGitModule {\n private repoRoot: string;\n private execCommand: (\n command: string,\n args: string[],\n options?: ExecOptions\n ) => Promise<ExecResult>;\n\n /**\n * Creates a new LocalGitModule instance\n *\n * @param dependencies - Required dependencies (execCommand) and optional config (repoRoot)\n * @throws Error if execCommand is not provided\n */\n constructor(dependencies: GitModuleDependencies) {\n if (!dependencies.execCommand) {\n throw new Error('execCommand is required for LocalGitModule');\n }\n\n this.execCommand = dependencies.execCommand;\n this.repoRoot = dependencies.repoRoot || '';\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // PRIVATE HELPERS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Ensures that repoRoot is set, auto-detecting it if necessary\n * \n * @returns Path to repository root\n * @throws GitCommandError if not in a Git repository\n */\n private async ensureRepoRoot(): Promise<string> {\n if (!this.repoRoot) {\n const result = await this.execCommand('git', ['rev-parse', '--show-toplevel']);\n if (result.exitCode !== 0) {\n throw new GitCommandError('Not in a Git repository', result.stderr);\n }\n this.repoRoot = result.stdout.trim();\n }\n return this.repoRoot;\n }\n\n /**\n * Executes a Git command with standardized error handling\n * \n * @param args - Git command arguments\n * @param options - Execution options\n * @returns Command result\n * @throws GitCommandError if command fails\n */\n private async execGit(args: string[], options?: ExecOptions): Promise<ExecResult> {\n const cwd = options?.cwd || await this.ensureRepoRoot();\n const result = await this.execCommand('git', args, { ...options, cwd });\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // PUBLIC COMMAND EXECUTION\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Executes an arbitrary shell command with the repository as working directory.\n *\n * This method is intended for advanced use cases where the existing\n * semantic methods don't cover the needed functionality. Use with caution.\n *\n * @param command - The command to execute (e.g., 'git')\n * @param args - Command arguments\n * @param options - Optional execution options\n * @returns Command execution result with exitCode, stdout, stderr\n *\n * @example\n * const result = await gitModule.exec('git', ['diff', '--name-only', 'HEAD~1..HEAD']);\n * if (result.exitCode === 0) {\n * const files = result.stdout.split('\\n');\n * }\n */\n async exec(\n command: string,\n args: string[],\n options?: ExecOptions\n ): Promise<ExecResult> {\n const cwd = options?.cwd || await this.ensureRepoRoot();\n return this.execCommand(command, args, { ...options, cwd });\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // INITIALIZATION\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Initializes a new Git repository in the current directory\n *\n * Creates the `.git/` directory structure and sets up initial configuration.\n * Useful for testing and for commands that require a fresh repository.\n *\n * @throws GitCommandError if directory is already a Git repository\n *\n * @example\n * await gitModule.init();\n * // Repository initialized with default branch (main or master)\n */\n async init(): Promise<void> {\n const cwd = this.repoRoot || process.cwd();\n\n // Check if already in a Git repository\n try {\n const checkResult = await this.execCommand('git', ['rev-parse', '--git-dir'], {\n cwd,\n });\n\n if (checkResult.exitCode === 0) {\n throw new GitCommandError(\n 'Directory is already a Git repository',\n `Git directory exists at ${checkResult.stdout.trim()}`\n );\n }\n } catch (error) {\n // If not a repo, this is what we want - continue with init\n if (error instanceof GitCommandError && error.message === 'Directory is already a Git repository') {\n throw error;\n }\n // Other errors mean it's not a repo, which is good\n }\n\n // Initialize the repository\n const result = await this.execCommand('git', ['init'], {\n cwd,\n });\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to initialize Git repository', result.stderr);\n }\n\n // Update repoRoot if it wasn't set\n if (!this.repoRoot) {\n const rootResult = await this.execCommand('git', ['rev-parse', '--show-toplevel'], { cwd });\n if (rootResult.exitCode === 0) {\n this.repoRoot = rootResult.stdout.trim();\n }\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // READ OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Returns the absolute path to the current Git repository root\n * \n * @returns Repository root path\n * @throws GitCommandError if not in a Git repository\n * \n * @example\n * const repoRoot = await gitModule.getRepoRoot();\n * // => \"/home/user/my-project\"\n */\n async getRepoRoot(): Promise<string> {\n return await this.ensureRepoRoot();\n }\n\n /**\n * Returns the name of the current branch (HEAD)\n * \n * @returns Current branch name\n * @throws GitCommandError if in detached HEAD state or other error\n * \n * @example\n * const branch = await gitModule.getCurrentBranch();\n * // => \"main\"\n */\n async getCurrentBranch(): Promise<string> {\n const result = await this.execGit(['rev-parse', '--abbrev-ref', 'HEAD']);\n\n if (result.exitCode !== 0) {\n // Fallback: Try reading .git/HEAD directly (works for orphan branches)\n try {\n const repoRoot = await this.ensureRepoRoot();\n const headPath = path.join(repoRoot, '.git', 'HEAD');\n const headContent = fs.readFileSync(headPath, 'utf-8').trim();\n\n if (headContent.startsWith('ref: refs/heads/')) {\n return headContent.replace('ref: refs/heads/', '');\n }\n } catch (fallbackError) {\n // Fallback failed, throw original error\n }\n\n throw new GitCommandError('Failed to get current branch', result.stderr);\n }\n\n const branch = result.stdout.trim();\n\n if (branch === 'HEAD') {\n throw new GitCommandError('In detached HEAD state', '');\n }\n\n return branch;\n }\n\n /**\n * Get commit hash for a given reference (branch, tag, HEAD, etc.)\n * \n * Used by test helpers and sync operations to get commit SHAs.\n * Returns the full 40-character SHA-1 hash of the commit.\n * \n * @param ref Git reference (default: \"HEAD\"). Can be:\n * - \"HEAD\" for current commit\n * - Branch name (e.g., \"main\", \"gitgov-state\")\n * - Tag name (e.g., \"v1.0.0\")\n * - Commit hash (returns the same hash)\n * - Relative refs (e.g., \"HEAD~1\", \"main^\")\n * @returns Commit SHA hash (full 40-character hash)\n * @throws GitCommandError if ref does not exist\n * \n * @example\n * const headHash = await git.getCommitHash(\"HEAD\");\n * // => \"a1b2c3d4e5f6...\"\n * \n * const mainHash = await git.getCommitHash(\"main\");\n * // => \"f6e5d4c3b2a1...\"\n * \n * const parentHash = await git.getCommitHash(\"HEAD~1\");\n * // => \"9876543210ab...\"\n */\n async getCommitHash(ref: string = \"HEAD\"): Promise<string> {\n const result = await this.execGit([\"rev-parse\", ref]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to get commit hash for ref \"${ref}\"`,\n result.stderr\n );\n }\n\n const hash = result.stdout.trim();\n logger.debug(`Got commit hash for ${ref}: ${hash.substring(0, 8)}...`);\n return hash;\n }\n\n /**\n * Set a Git configuration value.\n * Used for configuring repository settings like user.name, core.editor, etc.\n *\n * [EARS-F1, EARS-F2]\n *\n * @param key - Configuration key (e.g., \"user.name\", \"core.editor\")\n * @param value - Configuration value\n * @param scope - Configuration scope: \"local\" (default), \"global\", or \"system\"\n * @throws GitCommandError if configuration fails\n *\n * @example\n * ```typescript\n * // Set local config (repository-specific)\n * await git.setConfig('core.editor', 'vim');\n *\n * // Set global config (user-wide)\n * await git.setConfig('user.name', 'John Doe', 'global');\n *\n * // Set system config (machine-wide, requires permissions)\n * await git.setConfig('credential.helper', 'cache', 'system');\n * ```\n */\n async setConfig(\n key: string,\n value: string,\n scope: 'local' | 'global' | 'system' = 'local'\n ): Promise<void> {\n logger.debug(`Setting Git config: ${key} = ${value} (scope: ${scope})`);\n\n const args = ['config'];\n\n // Add scope flag\n if (scope === 'global') {\n args.push('--global');\n } else if (scope === 'system') {\n args.push('--system');\n } else {\n args.push('--local');\n }\n\n args.push(key, value);\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to set Git config ${key} to ${value}`,\n result.stderr\n );\n }\n\n logger.debug(`Git config ${key} set successfully`);\n }\n\n /**\n * Finds the most recent common ancestor between two branches\n * \n * @param branchA - First branch name\n * @param branchB - Second branch name\n * @returns Commit hash of the merge base\n * @throws BranchNotFoundError if either branch does not exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * const mergeBase = await gitModule.getMergeBase(\"main\", \"feature\");\n * // => \"a1b2c3d4e5f6...\"\n */\n async getMergeBase(branchA: string, branchB: string): Promise<string> {\n // Verify both branches exist\n if (!(await this.branchExists(branchA))) {\n throw new BranchNotFoundError(branchA);\n }\n if (!(await this.branchExists(branchB))) {\n throw new BranchNotFoundError(branchB);\n }\n\n const result = await this.execGit(['merge-base', branchA, branchB]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to find merge base between ${branchA} and ${branchB}`,\n result.stderr\n );\n }\n\n return result.stdout.trim();\n }\n\n /**\n * Returns a list of files changed between two commits\n * \n * @param fromCommit - Source commit or reference\n * @param toCommit - Target commit or reference\n * @param pathFilter - Optional path filter (e.g., \".gitgov/\")\n * @returns Array of changed files with their status\n * @throws GitCommandError if operation fails\n * \n * @example\n * const changes = await gitModule.getChangedFiles(\"HEAD~1\", \"HEAD\", \".gitgov/\");\n * // => [{ status: \"M\", file: \".gitgov/tasks/123.json\" }]\n */\n async getChangedFiles(\n fromCommit: string,\n toCommit: string,\n pathFilter: string\n ): Promise<ChangedFile[]> {\n const args = [\n 'diff',\n '--name-status',\n `${fromCommit}..${toCommit}`,\n '--',\n pathFilter,\n ];\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get changed files', result.stderr);\n }\n\n // Parse output: \"M\\tfile.txt\\nA\\tfile2.txt\"\n return result.stdout\n .trim()\n .split('\\n')\n .filter((line) => line.length > 0)\n .map((line) => {\n const parts = line.split('\\t');\n if (parts.length < 2) {\n throw new GitCommandError('Invalid git diff output format', line);\n }\n return {\n status: parts[0]! as 'A' | 'M' | 'D',\n file: parts[1]!,\n };\n });\n }\n\n /**\n * Get list of staged files (in staging area / index)\n * \n * Used during conflict resolution to identify which files the user resolved and staged.\n * \n * @returns Array of file paths that are currently staged\n * @throws GitCommandError if operation fails\n * \n * @example\n * // After user resolves conflict and does: git add .gitgov/tasks/123.json\n * const staged = await gitModule.getStagedFiles();\n * // => [\".gitgov/tasks/123.json\"]\n */\n async getStagedFiles(): Promise<string[]> {\n const args = ['diff', '--cached', '--name-only'];\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get staged files', result.stderr);\n }\n\n // Parse output: \"file1.txt\\nfile2.txt\\n\"\n const files = result.stdout\n .trim()\n .split('\\n')\n .filter((line) => line.length > 0);\n\n return files;\n }\n\n /**\n * Retrieves the content of a file at a specific point in history\n * \n * @param commitHash - Commit hash\n * @param filePath - File path relative to repository root\n * @returns File content as string\n * @throws FileNotFoundError if file doesn't exist in that commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const content = await gitModule.getFileContent(\"abc123\", \".gitgov/config.json\");\n * // => '{\"version\": \"1.0.0\"}'\n */\n async getFileContent(commitHash: string, filePath: string): Promise<string> {\n const result = await this.execGit(['show', `${commitHash}:${filePath}`]);\n\n if (result.exitCode !== 0) {\n // Check if error is due to file not existing\n if (result.stderr.includes('does not exist') || result.stderr.includes('exists on disk, but not in')) {\n throw new FileNotFoundError(filePath, commitHash);\n }\n throw new GitCommandError(`Failed to get file content for ${filePath}`, result.stderr);\n }\n\n return result.stdout;\n }\n\n /**\n * Retrieves the commit history for a branch\n * \n * @param branch - Branch name\n * @param options - Filtering and formatting options\n * @returns Array of commits ordered from newest to oldest\n * @throws GitCommandError if operation fails\n * \n * @example\n * const history = await gitModule.getCommitHistory(\"main\", { maxCount: 10 });\n * // => [{ hash: \"abc123\", message: \"Initial commit\", author: \"User <email>\", date: \"2025-01-01T00:00:00Z\" }]\n */\n async getCommitHistory(\n branch: string,\n options?: GetCommitHistoryOptions\n ): Promise<CommitInfo[]> {\n const args = ['log', branch, '--format=%H|%s|%an <%ae>|%aI'];\n\n if (options?.maxCount) {\n args.push(`--max-count=${options.maxCount}`);\n }\n\n if (options?.pathFilter) {\n args.push('--', options.pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to get commit history for ${branch}`, result.stderr);\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n // Parse output: \"hash|message|author|date\"\n return result.stdout\n .trim()\n .split('\\n')\n .map((line) => {\n const parts = line.split('|');\n if (parts.length < 4) {\n throw new GitCommandError('Invalid git log output format', line);\n }\n return {\n hash: parts[0]!,\n message: parts[1]!,\n author: parts[2]!,\n date: parts[3]!,\n };\n });\n }\n\n /**\n * Retrieves commit history in a specific range\n * \n * @param fromHash - Starting commit hash (exclusive)\n * @param toHash - Ending commit hash (inclusive)\n * @param options - Filtering and formatting options\n * @returns Array of commits in the specified range\n * @throws GitCommandError if either commit doesn't exist\n * \n * @example\n * const commits = await gitModule.getCommitHistoryRange(\"abc123\", \"def456\");\n * // => [{ hash: \"def456\", ... }, { hash: \"cba321\", ... }]\n */\n async getCommitHistoryRange(\n fromHash: string,\n toHash: string,\n options?: GetCommitHistoryOptions\n ): Promise<CommitInfo[]> {\n const args = ['log', `${fromHash}..${toHash}`, '--format=%H|%s|%an <%ae>|%aI'];\n\n if (options?.maxCount) {\n args.push(`--max-count=${options.maxCount}`);\n }\n\n if (options?.pathFilter) {\n args.push('--', options.pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to get commit history range ${fromHash}..${toHash}`,\n result.stderr\n );\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n // Parse output: \"hash|message|author|date\"\n return result.stdout\n .trim()\n .split('\\n')\n .map((line) => {\n const parts = line.split('|');\n if (parts.length < 4) {\n throw new GitCommandError('Invalid git log output format', line);\n }\n return {\n hash: parts[0]!,\n message: parts[1]!,\n author: parts[2]!,\n date: parts[3]!,\n };\n });\n }\n\n /**\n * Retrieves the full commit message for a specific commit\n * \n * @param commitHash - Commit hash\n * @returns Full commit message as string\n * @throws GitCommandError if commit doesn't exist\n * \n * @example\n * const message = await gitModule.getCommitMessage(\"abc123\");\n * // => \"feat: add new feature\\n\\nDetailed description...\"\n */\n async getCommitMessage(commitHash: string): Promise<string> {\n const result = await this.execGit(['show', commitHash, '--format=%B', '--no-patch']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to get commit message for ${commitHash}`, result.stderr);\n }\n\n return result.stdout.trim();\n }\n\n /**\n * Checks if there are uncommitted changes in the working directory\n * \n * @param pathFilter - Optional path filter (e.g., \".gitgov/\")\n * @returns true if there are uncommitted changes, false otherwise\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hasChanges = await gitModule.hasUncommittedChanges(\".gitgov/\");\n * // => true\n */\n async hasUncommittedChanges(pathFilter?: string): Promise<boolean> {\n const args = ['status', '--porcelain'];\n\n if (pathFilter) {\n args.push('--', pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to check for uncommitted changes', result.stderr);\n }\n\n return result.stdout.trim().length > 0;\n }\n\n /**\n * Checks if a rebase operation is currently in progress\n * \n * @returns true if rebase is in progress, false otherwise\n * \n * @example\n * const inRebase = await gitModule.isRebaseInProgress();\n * // => false\n */\n async isRebaseInProgress(): Promise<boolean> {\n const repoRoot = await this.ensureRepoRoot();\n const rebaseMergePath = path.join(repoRoot, '.git', 'rebase-merge');\n const rebaseApplyPath = path.join(repoRoot, '.git', 'rebase-apply');\n\n return fs.existsSync(rebaseMergePath) || fs.existsSync(rebaseApplyPath);\n }\n\n /**\n * Checks if a branch exists locally\n * \n * @param branchName - Branch name to check\n * @returns true if branch exists, false otherwise\n * \n * @example\n * const exists = await gitModule.branchExists(\"feature-branch\");\n * // => true\n */\n async branchExists(branchName: string): Promise<boolean> {\n const result = await this.execGit(['branch', '--list', branchName]);\n\n if (result.exitCode !== 0) {\n return false;\n }\n\n return result.stdout.trim().length > 0;\n }\n\n /**\n * Lists all remote branches for a given remote\n * \n * @param remoteName - Name of the remote (e.g., \"origin\")\n * @returns Array of remote branch names without the remote prefix\n * @throws GitCommandError if operation fails\n * \n * @example\n * const branches = await gitModule.listRemoteBranches(\"origin\");\n * // => [\"main\", \"develop\", \"gitgov-state\"]\n * \n * @note This method only returns the branch names, not the full \"origin/branch\" format\n */\n async listRemoteBranches(remoteName: string): Promise<string[]> {\n const result = await this.execGit(['branch', '-r', '--list', `${remoteName}/*`]);\n\n if (result.exitCode !== 0) {\n // If command fails, return empty array (e.g., remote doesn't exist)\n return [];\n }\n\n const output = result.stdout.trim();\n if (!output) {\n return [];\n }\n\n // Parse output: \" origin/main\\n origin/develop\"\n // Strip \"origin/\" prefix and whitespace\n return output\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0)\n .map(line => {\n // Remove \"remoteName/\" prefix\n const prefix = `${remoteName}/`;\n if (line.startsWith(prefix)) {\n return line.substring(prefix.length);\n }\n return line;\n })\n .filter(branch => branch.length > 0);\n }\n\n /**\n * Checks if a remote is configured in the git repository.\n *\n * @param remoteName - Name of the remote to check (e.g., \"origin\")\n * @returns true if the remote is configured, false otherwise\n *\n * @example\n * const hasOrigin = await gitModule.isRemoteConfigured(\"origin\");\n * // => true\n */\n async isRemoteConfigured(remoteName: string): Promise<boolean> {\n const result = await this.execGit(['remote']);\n\n if (result.exitCode !== 0) {\n return false;\n }\n\n const remotes = result.stdout.trim().split('\\n').filter(Boolean);\n return remotes.includes(remoteName);\n }\n\n /**\n * Retrieves the tracking remote for a branch\n *\n * @param branchName - Branch name\n * @returns Remote name or null if not configured\n * @throws BranchNotFoundError if branch doesn't exist\n *\n * @example\n * const remote = await gitModule.getBranchRemote(\"main\");\n * // => \"origin\"\n */\n async getBranchRemote(branchName: string): Promise<string | null> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit(['config', `branch.${branchName}.remote`]);\n\n if (result.exitCode !== 0) {\n return null;\n }\n\n return result.stdout.trim() || null;\n }\n\n /**\n * Retrieves the list of conflicted files during a rebase or merge\n * \n * @returns Array of file paths in conflict\n * @throws GitCommandError if no rebase/merge in progress\n * \n * @example\n * const conflicts = await gitModule.getConflictedFiles();\n * // => [\".gitgov/tasks/123.json\", \".gitgov/tasks/456.json\"]\n */\n async getConflictedFiles(): Promise<string[]> {\n const result = await this.execGit(['diff', '--name-only', '--diff-filter=U']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get conflicted files', result.stderr);\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n return result.stdout.trim().split('\\n');\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // WRITE OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Switches to the specified branch\n * \n * @param branchName - Branch name to checkout\n * @throws BranchNotFoundError if branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.checkoutBranch(\"feature-branch\");\n */\n async checkoutBranch(branchName: string): Promise<void> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit(['checkout', branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to checkout branch ${branchName}`, result.stderr);\n }\n }\n\n /**\n * Stash uncommitted changes\n * \n * @param message - Optional message for the stash\n * @returns Stash hash if changes were stashed, null if nothing to stash\n */\n async stash(message?: string): Promise<string | null> {\n const hasChanges = await this.hasUncommittedChanges();\n if (!hasChanges) {\n return null; // Nothing to stash\n }\n\n const args = ['stash', 'push'];\n if (message) {\n args.push('-m', message);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to stash changes', result.stderr);\n }\n\n // Get the hash of the stash we just created\n const listResult = await this.execGit(['stash', 'list', '-n', '1', '--format=%H']);\n return listResult.stdout.trim() || null;\n }\n\n /**\n * Pop the most recent stash\n * \n * @returns true if stash was popped successfully, false if no stash exists\n */\n async stashPop(): Promise<boolean> {\n // Check if there are any stashes\n const listResult = await this.execGit(['stash', 'list']);\n if (!listResult.stdout.trim()) {\n return false; // No stashes to pop\n }\n\n const result = await this.execGit(['stash', 'pop']);\n\n if (result.exitCode !== 0) {\n // If pop fails, it might be due to conflicts - this is okay, we'll leave it stashed\n throw new GitCommandError('Failed to pop stash (conflicts may exist)', result.stderr);\n }\n\n return true;\n }\n\n /**\n * Drop a specific stash or the most recent one\n * \n * @param stashHash - Optional stash hash to drop, defaults to most recent\n */\n async stashDrop(stashHash?: string): Promise<void> {\n const args = ['stash', 'drop'];\n if (stashHash) {\n args.push(stashHash);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to drop stash', result.stderr);\n }\n }\n\n /**\n * Creates an orphan branch (no history) and switches to it\n * \n * @param branchName - Orphan branch name to create\n * @throws GitCommandError if branch already exists or operation fails\n * \n * @example\n * await gitModule.checkoutOrphanBranch(\"gitgov-state\");\n */\n async checkoutOrphanBranch(branchName: string): Promise<void> {\n const result = await this.execGit(['checkout', '--orphan', branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to create orphan branch ${branchName}`, result.stderr);\n }\n }\n\n /**\n * Fetches the latest changes from a remote repository\n * \n * @param remote - Remote name (e.g., \"origin\")\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.fetch(\"origin\");\n */\n async fetch(remote: string): Promise<void> {\n const result = await this.execGit(['fetch', remote]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to fetch from ${remote}`, result.stderr);\n }\n }\n\n /**\n * Pulls and merges a remote branch\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws MergeConflictError if merge conflicts occur\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pull(\"origin\", \"main\");\n */\n async pull(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['pull', '--no-rebase', remote, branchName]);\n\n if (result.exitCode !== 0) {\n // Check if conflict occurred (check both stdout and stderr)\n const output = result.stdout + result.stderr;\n if (output.includes('CONFLICT') || output.includes('Automatic merge failed') || output.includes('fix conflicts')) {\n const conflictedFiles = await this.getConflictedFiles();\n throw new MergeConflictError(conflictedFiles);\n }\n throw new GitCommandError(`Failed to pull from ${remote}/${branchName}`, result.stderr);\n }\n }\n\n /**\n * Pulls and rebases a remote branch\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws RebaseConflictError if rebase conflicts occur\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pullRebase(\"origin\", \"main\");\n */\n async pullRebase(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['pull', '--rebase', remote, branchName]);\n\n if (result.exitCode !== 0) {\n // Check if conflict occurred (check both stdout and stderr)\n const output = result.stdout + result.stderr;\n if (output.includes('CONFLICT') || output.includes('could not apply') || output.includes('fix conflicts') || output.includes('Resolve all conflicts')) {\n const conflictedFiles = await this.getConflictedFiles();\n throw new RebaseConflictError(conflictedFiles);\n }\n throw new GitCommandError(`Failed to pull --rebase from ${remote}/${branchName}`, result.stderr);\n }\n }\n\n /**\n * Resets the current branch to a specific commit, discarding all local changes\n * \n * @param target - Commit hash or branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.resetHard(\"HEAD~1\");\n */\n async resetHard(target: string): Promise<void> {\n const result = await this.execGit(['reset', '--hard', target]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to reset --hard to ${target}`, result.stderr);\n }\n }\n\n /**\n * Checks out specific files from another branch into the current staging area\n * \n * @param sourceBranch - Source branch name\n * @param filePaths - Array of file paths to checkout\n * @throws BranchNotFoundError if source branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.checkoutFilesFromBranch(\"main\", [\".gitgov/tasks/123.json\"]);\n */\n async checkoutFilesFromBranch(sourceBranch: string, filePaths: string[]): Promise<void> {\n if (!(await this.branchExists(sourceBranch))) {\n throw new BranchNotFoundError(sourceBranch);\n }\n\n const result = await this.execGit(['checkout', sourceBranch, '--', ...filePaths]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to checkout files from ${sourceBranch}`,\n result.stderr\n );\n }\n }\n\n /**\n * Adds files to the staging area\n *\n * @param filePaths - Array of file paths to add\n * @param options - Optional settings (force: add ignored files)\n * @throws GitCommandError if operation fails\n *\n * @example\n * await gitModule.add([\".gitgov/tasks/123.json\"]);\n * await gitModule.add([\".gitgov\"], { force: true }); // Add ignored files\n */\n async add(filePaths: string[], options?: { force?: boolean }): Promise<void> {\n const args = ['add'];\n if (options?.force) {\n args.push('--force');\n }\n args.push(...filePaths);\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to add files', result.stderr);\n }\n }\n\n /**\n * Removes files from both working directory and staging area\n * \n * @param filePaths - Array of file paths to remove\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.rm([\".gitgov/tasks/123.json\"]);\n */\n async rm(filePaths: string[]): Promise<void> {\n const result = await this.execGit(['rm', ...filePaths]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to remove files', result.stderr);\n }\n }\n\n /**\n * Creates a new commit with staged files\n * \n * @param message - Commit message\n * @param author - Optional commit author\n * @returns Commit hash of the created commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.commit(\"feat: add new task\");\n * // => \"abc123def456...\"\n */\n async commit(message: string, author?: CommitAuthor): Promise<string> {\n // Use multiple -m arguments for multi-line messages\n // Git concatenates them with newlines\n const lines = message.split('\\n');\n const args = ['commit'];\n\n // Add each line as a separate -m argument\n for (const line of lines) {\n args.push('-m', line);\n }\n\n if (author) {\n args.push('--author', `${author.name} <${author.email}>`);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n // Include both stdout and stderr in error for better diagnostics\n // (git commit outputs \"nothing to commit\" to stdout, not stderr)\n throw new GitCommandError('Failed to create commit', result.stderr, undefined, result.stdout);\n }\n\n // Get the commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n return hashResult.stdout.trim();\n }\n\n /**\n * Creates an empty commit (no changes required)\n * \n * @param message - Commit message\n * @param author - Optional commit author\n * @returns Commit hash of the created commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.commitAllowEmpty(\"chore: initialize state branch\");\n * // => \"abc123def456...\"\n */\n async commitAllowEmpty(message: string, author?: CommitAuthor): Promise<string> {\n const args = ['commit', '--allow-empty', '-m', message];\n\n if (author) {\n args.push('--author', `${author.name} <${author.email}>`);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to create empty commit', result.stderr);\n }\n\n // Get the commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n return hashResult.stdout.trim();\n }\n\n /**\n * Pushes a local branch to a remote repository\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.push(\"origin\", \"main\");\n */\n async push(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['push', remote, branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to push ${branchName} to ${remote}`, result.stderr);\n }\n }\n\n /**\n * Pushes a local branch to a remote repository and sets up tracking\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pushWithUpstream(\"origin\", \"feature-branch\");\n */\n async pushWithUpstream(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['push', '-u', remote, branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to push ${branchName} to ${remote} with upstream`,\n result.stderr\n );\n }\n }\n\n /**\n * Configures tracking for a local branch with a remote branch\n * \n * @param branchName - Local branch name\n * @param remote - Remote name\n * @param remoteBranch - Remote branch name\n * @throws BranchNotFoundError if local branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.setUpstream(\"feature-branch\", \"origin\", \"feature-branch\");\n */\n async setUpstream(\n branchName: string,\n remote: string,\n remoteBranch: string\n ): Promise<void> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit([\n 'branch',\n '--set-upstream-to',\n `${remote}/${remoteBranch}`,\n branchName,\n ]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to set upstream for ${branchName}`, result.stderr);\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // REBASE OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Continues a rebase after resolving conflicts\n * \n * @returns Commit hash of the rebased commit\n * @throws RebaseNotInProgressError if no rebase is in progress\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.rebaseContinue();\n * // => \"abc123def456...\"\n */\n async rebaseContinue(): Promise<string> {\n if (!(await this.isRebaseInProgress())) {\n throw new RebaseNotInProgressError();\n }\n\n logger.debug('Continuing rebase...');\n const result = await this.execGit(['rebase', '--continue']);\n\n if (result.exitCode !== 0) {\n logger.error(`Rebase continue failed: ${result.stderr}`);\n throw new GitCommandError('Failed to continue rebase', result.stderr);\n }\n\n // Get the current commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n const commitHash = hashResult.stdout.trim();\n logger.info(`Rebase continued successfully, commit: ${commitHash.substring(0, 8)}...`);\n return commitHash;\n }\n\n /**\n * Aborts an ongoing rebase\n * \n * @throws RebaseNotInProgressError if no rebase is in progress\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.rebaseAbort();\n */\n async rebaseAbort(): Promise<void> {\n if (!(await this.isRebaseInProgress())) {\n throw new RebaseNotInProgressError();\n }\n\n const result = await this.execGit(['rebase', '--abort']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to abort rebase', result.stderr);\n }\n }\n\n /**\n * Creates a new branch and switches to it (git checkout -b)\n * \n * @param branchName - Name of the branch to create\n * @param startPoint - Optional starting point (commit hash or branch name)\n * @throws GitCommandError if branch already exists or operation fails\n * @throws BranchAlreadyExistsError if the branch already exists locally\n */\n async createBranch(branchName: string, startPoint?: string): Promise<void> {\n // Check if branch already exists\n const exists = await this.branchExists(branchName);\n if (exists) {\n throw new BranchAlreadyExistsError(branchName);\n }\n\n const args = ['checkout', '-b', branchName];\n if (startPoint) {\n args.push(startPoint);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to create branch ${branchName}`,\n result.stderr\n );\n }\n\n logger.debug(`Created and checked out branch: ${branchName}`);\n }\n\n /**\n * Rebases current branch onto target branch (git rebase)\n * \n * @param targetBranch - Branch to rebase onto\n * @throws GitCommandError if rebase fails\n * @throws RebaseConflictError if conflicts are detected during rebase\n */\n async rebase(targetBranch: string): Promise<void> {\n const result = await this.execGit(['rebase', targetBranch]);\n\n if (result.exitCode !== 0) {\n // Check if it's a conflict\n if (result.stderr.includes('CONFLICT') || result.stderr.includes('conflict')) {\n // Get conflicted files if possible\n try {\n const conflictedFiles = await this.getConflictedFiles();\n throw new RebaseConflictError(conflictedFiles);\n } catch {\n // If we can't get files, throw with empty array\n throw new RebaseConflictError([]);\n }\n }\n\n throw new GitCommandError(\n `Failed to rebase onto ${targetBranch}`,\n result.stderr\n );\n }\n\n logger.debug(`Rebased onto: ${targetBranch}`);\n }\n}\n\n","/**\n * Project Discovery Utilities\n *\n * Filesystem-based utilities for discovering GitGovernance project roots.\n * Used at CLI bootstrap to resolve projectRoot before injecting it via DI.\n *\n * NOTE: These functions should only be called at the CLI/bootstrap level.\n * Core modules receive projectRoot via constructor injection.\n */\n\nimport * as path from 'path';\nimport { existsSync } from 'fs';\n\n// Project root cache for performance\nlet projectRootCache: string | null = null;\nlet lastSearchPath: string | null = null;\n\n/**\n * Finds the project root by searching upwards for a .git directory.\n * Caches the result for subsequent calls.\n *\n * @param startPath - Starting path (default: process.cwd())\n * @returns Path to project root, or null if not found\n */\nexport function findProjectRoot(startPath: string = process.cwd()): string | null {\n // In test environment, allow cache reset via global\n if (typeof (global as any).projectRoot !== 'undefined' && (global as any).projectRoot === null) {\n projectRootCache = null;\n lastSearchPath = null;\n }\n\n // Reset cache if we're searching from a different directory\n if (lastSearchPath && lastSearchPath !== startPath) {\n projectRootCache = null;\n lastSearchPath = null;\n }\n\n if (projectRootCache && lastSearchPath === startPath) {\n return projectRootCache;\n }\n\n lastSearchPath = startPath;\n\n let currentPath = startPath;\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.git'))) {\n projectRootCache = currentPath;\n return projectRootCache;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at the root directory\n if (existsSync(path.join(currentPath, '.git'))) {\n projectRootCache = currentPath;\n return projectRootCache;\n }\n\n return null;\n}\n\n/**\n * Finds the project root by searching upwards.\n * First looks for .gitgov (initialized project), then .git (for init).\n *\n * @param startPath - Starting path (default: process.cwd())\n * @returns Path to project root, or null if not found\n */\nexport function findGitgovRoot(startPath: string = process.cwd()): string | null {\n let currentPath = startPath;\n\n // First pass: Look for .gitgov (initialized GitGovernance project)\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.gitgov'))) {\n return currentPath;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at root for .gitgov\n if (existsSync(path.join(currentPath, '.gitgov'))) {\n return currentPath;\n }\n\n // Second pass: Look for .git (for init command)\n currentPath = startPath;\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.git'))) {\n return currentPath;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at root for .git\n if (existsSync(path.join(currentPath, '.git'))) {\n return currentPath;\n }\n\n return null;\n}\n\n/**\n * Gets the .gitgov directory path from project root.\n *\n * @throws Error if not inside a GitGovernance project\n */\nexport function getGitgovPath(): string {\n const root = findGitgovRoot();\n if (!root) {\n throw new Error(\"Could not find project root. Make sure you are inside a GitGovernance repository.\");\n }\n return path.join(root, '.gitgov');\n}\n\n/**\n * Checks if current directory is inside a GitGovernance project.\n */\nexport function isGitgovProject(): boolean {\n try {\n const gitgovPath = getGitgovPath();\n return existsSync(gitgovPath);\n } catch {\n return false;\n }\n}\n\n/**\n * Reset the project root cache.\n * Useful for testing when switching between project contexts.\n */\nexport function resetDiscoveryCache(): void {\n projectRootCache = null;\n lastSearchPath = null;\n}\n","/**\n * Base error class for all sync-related errors\n */\nexport class SyncStateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SyncStateError\";\n Object.setPrototypeOf(this, SyncStateError.prototype);\n }\n}\n\n/**\n * Error thrown when attempting to push from gitgov-state branch\n */\nexport class PushFromStateBranchError extends SyncStateError {\n public branch: string;\n\n constructor(branchName: string) {\n super(\n `Cannot push from ${branchName} branch. ` +\n `Please switch to a working branch before pushing state.`\n );\n this.name = \"PushFromStateBranchError\";\n this.branch = branchName;\n Object.setPrototypeOf(this, PushFromStateBranchError.prototype);\n }\n}\n\n/**\n * Error thrown when integrity violations are detected during audit\n */\nexport class IntegrityViolationError extends SyncStateError {\n constructor(\n public violations: Array<{\n type: \"resolution\" | \"signature\" | \"checksum\" | \"missing_file\";\n details: string;\n }>\n ) {\n const violationSummary = violations\n .map((v) => `${v.type}: ${v.details}`)\n .join(\"; \");\n super(`Integrity violations detected: ${violationSummary}`);\n this.name = \"IntegrityViolationError\";\n Object.setPrototypeOf(this, IntegrityViolationError.prototype);\n }\n}\n\n/**\n * Error thrown when conflict markers are still present in files\n */\nexport class ConflictMarkersPresentError extends SyncStateError {\n constructor(public filesWithMarkers: string[]) {\n super(\n `Conflict markers still present in ${filesWithMarkers.length} file(s). ` +\n `Please resolve all conflicts before continuing.`\n );\n this.name = \"ConflictMarkersPresentError\";\n Object.setPrototypeOf(this, ConflictMarkersPresentError.prototype);\n }\n}\n\n/**\n * Error thrown when attempting to resolve conflict without rebase in progress\n */\nexport class NoRebaseInProgressError extends SyncStateError {\n constructor() {\n super(\n `No rebase in progress. Cannot resolve conflict without an active rebase. ` +\n `Use 'pullState' or 'pushState' to trigger synchronization first.`\n );\n this.name = \"NoRebaseInProgressError\";\n Object.setPrototypeOf(this, NoRebaseInProgressError.prototype);\n }\n}\n\n/**\n * Error thrown when CryptoModule is required but not available\n */\nexport class CryptoModuleRequiredError extends SyncStateError {\n constructor(operation: string) {\n super(\n `CryptoModule is required for ${operation} operation. ` +\n `Please provide crypto_module in SyncStateModuleDependencies.`\n );\n this.name = \"CryptoModuleRequiredError\";\n Object.setPrototypeOf(this, CryptoModuleRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when state branch cannot be created or configured\n */\nexport class StateBranchSetupError extends SyncStateError {\n constructor(\n public reason: string,\n public underlyingError?: Error\n ) {\n super(`Failed to setup state branch: ${reason}`);\n this.name = \"StateBranchSetupError\";\n Object.setPrototypeOf(this, StateBranchSetupError.prototype);\n }\n}\n\n/**\n * Error thrown when the provided actorId doesn't match the authenticated identity.\n *\n * This prevents impersonation: you can only push/resolve as the actor whose\n * private key you hold.\n */\nexport class ActorIdentityMismatchError extends SyncStateError {\n public requestedActorId: string;\n public authenticatedActorId: string;\n\n constructor(requestedActorId: string, authenticatedActorId: string) {\n super(\n `Actor identity mismatch: requested '${requestedActorId}' but authenticated as '${authenticatedActorId}'. ` +\n `You can only operate as the actor whose private key you hold.`\n );\n this.name = \"ActorIdentityMismatchError\";\n this.requestedActorId = requestedActorId;\n this.authenticatedActorId = authenticatedActorId;\n Object.setPrototypeOf(this, ActorIdentityMismatchError.prototype);\n }\n}\n\n/**\n * Error thrown when uncommitted changes exist in state branch\n */\nexport class UncommittedChangesError extends SyncStateError {\n public branch: string;\n\n constructor(branchName: string) {\n super(\n `Uncommitted changes detected in ${branchName}. ` +\n `Please commit or stash changes before synchronizing.`\n );\n this.name = \"UncommittedChangesError\";\n this.branch = branchName;\n Object.setPrototypeOf(this, UncommittedChangesError.prototype);\n }\n}\n\n/**\n * Type guards for error handling\n * \n * These functions enable type-safe error handling by narrowing the error type.\n * They are additive and don't break any existing code.\n * \n * Example usage:\n * ```typescript\n * try {\n * await syncModule.pushState(options);\n * } catch (error) {\n * if (isPushFromStateBranchError(error)) {\n * // TypeScript knows error.branch exists here\n * console.log(`Cannot push from ${error.branch}`);\n * }\n * }\n * ```\n */\n\nexport function isSyncStateError(error: unknown): error is SyncStateError {\n return error instanceof SyncStateError;\n}\n\nexport function isPushFromStateBranchError(\n error: unknown\n): error is PushFromStateBranchError {\n return error instanceof PushFromStateBranchError;\n}\n\nexport function isIntegrityViolationError(\n error: unknown\n): error is IntegrityViolationError {\n return error instanceof IntegrityViolationError;\n}\n\nexport function isConflictMarkersPresentError(\n error: unknown\n): error is ConflictMarkersPresentError {\n return error instanceof ConflictMarkersPresentError;\n}\n\nexport function isUncommittedChangesError(\n error: unknown\n): error is UncommittedChangesError {\n return error instanceof UncommittedChangesError;\n}\n\nexport function isNoRebaseInProgressError(\n error: unknown\n): error is NoRebaseInProgressError {\n return error instanceof NoRebaseInProgressError;\n}\n\nexport function isStateBranchSetupError(\n error: unknown\n): error is StateBranchSetupError {\n return error instanceof StateBranchSetupError;\n}\n\nexport function isCryptoModuleRequiredError(\n error: unknown\n): error is CryptoModuleRequiredError {\n return error instanceof CryptoModuleRequiredError;\n}\n\nexport function isActorIdentityMismatchError(\n error: unknown\n): error is ActorIdentityMismatchError {\n return error instanceof ActorIdentityMismatchError;\n}\n\n","import type { IGitModule } from '../git';\nimport type { ConfigManager } from \"../config_manager\";\nimport type { IIdentityAdapter } from \"../adapters/identity_adapter\";\nimport type { LintReport } from \"../lint\";\nimport type { ILintModule } from \"../lint\";\nimport type { IIndexerAdapter } from \"../adapters/indexer_adapter\";\n\n/**\n * SyncStateModule Dependencies\n */\nexport type SyncStateModuleDependencies = {\n /** Low-level Git module (required) */\n git: IGitModule;\n /** Configuration manager (required) */\n config: ConfigManager;\n /** Identity adapter for signature verification and signing (required) */\n identity: IIdentityAdapter;\n /** Lint module for record validation (required) */\n lint: ILintModule;\n /** Indexer adapter for automatic re-indexing after pull/resolve (required) */\n indexer: IIndexerAdapter;\n}\n\n/**\n * Options for pushState operation\n */\nexport type SyncStatePushOptions = {\n /** Branch to push from (default: current branch) */\n sourceBranch?: string;\n /** Actor ID publishing the state (required) */\n actorId: string;\n /** Simulate operation without making real changes */\n dryRun?: boolean;\n /** Force push even if there are unsynced remote changes */\n force?: boolean;\n}\n\n/**\n * Result of pushState operation\n */\nexport type SyncStatePushResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Number of files synced */\n filesSynced: number;\n /** Name of the branch pushed from */\n sourceBranch: string;\n /** Created commit hash (null if no changes or dry-run) */\n commitHash: string | null;\n /** Created commit message */\n commitMessage: string | null;\n /** Indicates if a conflict was detected during reconciliation */\n conflictDetected: boolean;\n /** Conflict information if detected */\n conflictInfo?: ConflictInfo;\n /** Error message if operation failed */\n error?: string;\n /** [EARS-B16] Implicit pull results when push does reconciliation with remote */\n implicitPull?: {\n /** Whether changes were pulled from remote */\n hasChanges: boolean;\n /** Number of files updated from remote */\n filesUpdated: number;\n /** Whether index was regenerated */\n reindexed: boolean;\n };\n}\n\n/**\n * Options for pullState operation\n */\nexport type SyncStatePullOptions = {\n /** Force re-indexing even if there are no new changes */\n forceReindex?: boolean;\n /** [EARS-C11] Force pull even if local changes would be overwritten */\n force?: boolean;\n}\n\n/**\n * Result of pullState operation\n */\nexport type SyncStatePullResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Indicates if there were new remote changes */\n hasChanges: boolean;\n /** Number of files updated */\n filesUpdated: number;\n /** Indicates if re-indexing was executed */\n reindexed: boolean;\n /** Indicates if a conflict was detected during pull */\n conflictDetected: boolean;\n /** Conflict information if detected */\n conflictInfo?: ConflictInfo;\n /** Error message if operation failed */\n error?: string;\n /** [EARS-C11] Files that were forcefully overwritten (when force: true) */\n forcedOverwrites?: string[];\n}\n\n/**\n * Options for resolveConflict operation\n */\nexport type SyncStateResolveOptions = {\n /** Justification for the conflict resolution (required) */\n reason: string;\n /** Actor ID resolving the conflict (required) */\n actorId: string;\n}\n\n/**\n * Result of resolveConflict operation\n */\nexport type SyncStateResolveResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Commit hash of the created rebase commit */\n rebaseCommitHash: string;\n /** Commit hash of the signed resolution commit */\n resolutionCommitHash: string;\n /** Number of conflicts resolved */\n conflictsResolved: number;\n /** Actor ID who resolved the conflict */\n resolvedBy: string;\n /** Reason for resolution */\n reason: string;\n /** Error message if operation failed */\n error?: string;\n}\n\n/**\n * Detailed information about a detected conflict\n */\nexport type ConflictInfo = {\n /** Type of conflict detected */\n type: ConflictType;\n /** Files affected by the conflict */\n affectedFiles: string[];\n /** Descriptive message of the conflict */\n message: string;\n /** Instructions to resolve the conflict */\n resolutionSteps: string[];\n}\n\n/**\n * Auxiliary type to identify the conflict type\n *\n * Git-Native conflict model (post-refactor):\n * - rebase_conflict: Used for all Git-level conflicts during push/pull\n * - local_changes_conflict: Used when pull would overwrite local changes (EARS-C10)\n * - integrity_violation: Used when resolution commits are missing\n */\nexport type ConflictType =\n | \"rebase_conflict\" // Conflict during automatic rebase (Git-native, includes EARS-B23 scenarios)\n | \"integrity_violation\" // Integrity violation (rebase without resolution commit)\n | \"local_changes_conflict\"; // [EARS-C10] Local changes would be overwritten by pull\n\n/**\n * Information about a detected integrity violation\n */\nexport type IntegrityViolation = {\n /** Commit hash of the rebase commit without resolution */\n rebaseCommitHash: string;\n /** Message of the rebase commit */\n commitMessage: string;\n /** Timestamp of the commit */\n timestamp: string;\n /** Author of the commit */\n author: string;\n}\n\n/**\n * Verification scope for state audit\n */\nexport type AuditScope =\n | \"current\" // Only verify Records in the current branch (useful for pre-push)\n | \"state-branch\" // Only verify Records in gitgov-state (useful for remote audit)\n | \"all\"; // Verify both (useful for complete audit)\n\n/**\n * Scope for expected files verification\n */\nexport type ExpectedFilesScope =\n | \"head\" // Only verify in HEAD of gitgov-state (default, faster)\n | \"all-commits\"; // Verify in all commits (more exhaustive, slower)\n\n/**\n * Options for state audit\n */\nexport type AuditStateOptions = {\n /** Verification scope: which Records to verify (default: \"all\") */\n scope?: AuditScope;\n /** Verify signatures in Records (default: true) */\n verifySignatures?: boolean;\n /** Verify checksums of Records (default: true) */\n verifyChecksums?: boolean;\n /** Verify that expected files exist (default: true) */\n verifyExpectedFiles?: boolean;\n /** Scope for expected files verification (default: \"head\") */\n expectedFilesScope?: ExpectedFilesScope;\n /** Path of specific files to audit (default: all in .gitgov/) */\n filePaths?: string[];\n}\n\n/**\n * Conflict diff information for a file\n */\nexport type ConflictFileDiff = {\n /** Path of the conflicted file */\n filePath: string;\n /** Content of the local version (ours) */\n localContent: string;\n /** Content of the remote version (theirs) */\n remoteContent: string;\n /** Base content (common ancestor) */\n baseContent: string | null;\n /** Lines with conflict markers (if they still exist) */\n conflictMarkers?: Array<{\n line: number;\n marker: string; // \"<<<<<\", \"=====\", \">>>>>\"\n }>;\n}\n\n/**\n * Structured conflict diff\n */\nexport type ConflictDiff = {\n /** Conflicted files with their diff */\n files: ConflictFileDiff[];\n /** Descriptive message of the conflict */\n message: string;\n /** Instructions to resolve */\n resolutionSteps: string[];\n}\n\n/**\n * Complete state audit report\n * \n * This report combines SyncStateModule-specific audits (rebase integrity, commits)\n * with structural validation from LintModule (signatures, checksums, schemas).\n */\nexport type AuditStateReport = {\n /** Indicates if the audit passed without violations */\n passed: boolean;\n /** Scope used for the audit */\n scope: AuditScope;\n /** Total commits analyzed */\n totalCommits: number;\n /** Rebase commits found */\n rebaseCommits: number;\n /** Resolution commits found */\n resolutionCommits: number;\n /** Integrity violations of resolutions (SyncStateModule-specific) */\n integrityViolations: IntegrityViolation[];\n /** Summary message of the audit */\n summary: string;\n /** Complete LintModule report for structural validation (signatures, checksums, schemas, etc.) */\n lintReport?: LintReport;\n}\n\n/**\n * Information of a changed file in the delta\n */\nexport type StateDeltaFile = {\n /** File status: Added, Modified, Deleted */\n status: \"A\" | \"M\" | \"D\";\n /** File path */\n file: string;\n}\n\n/**\n * Whitelist of files and directories allowed for synchronization.\n * Only these paths will be copied from .gitgov/ to gitgov-state.\n * \n * [EARS-B9] Explicitly defines what gets synced, avoiding temporary files,\n * builds, scripts, and local configurations like .gitignore\n * \n * Excluded (not in whitelist):\n * - builds/ (local build artifacts)\n * - scripts/ (local helper scripts)\n * - .gitignore (per-branch file, should not be synced)\n * - *.backup-* (backup files)\n * - *.tmp (temporary files)\n * - .DS_Store (macOS metadata)\n */\n/**\n * Directories to SYNC to gitgov-state branch (shared state)\n * Only *.json files within these directories will be synced\n */\nexport const SYNC_DIRECTORIES = [\n 'tasks',\n 'cycles',\n 'actors',\n 'agents',\n 'feedbacks',\n 'executions',\n 'changelogs',\n 'workflows',\n] as const;\n\n/**\n * Root-level files to SYNC to gitgov-state\n */\nexport const SYNC_ROOT_FILES = [\n 'config.json',\n] as const;\n\n/**\n * File extensions that are ALLOWED to be synced\n * Only these extensions will be copied to gitgov-state\n */\nexport const SYNC_ALLOWED_EXTENSIONS = ['.json'] as const;\n\n/**\n * File patterns that are NEVER synced (even if they match allowed extensions)\n * These are excluded from gitgov-state branch\n */\nexport const SYNC_EXCLUDED_PATTERNS = [\n /\\.key$/, // Private keys (e.g., actors/*.key)\n /\\.backup$/, // Backup files from lint\n /\\.backup-\\d+$/, // Numbered backup files\n /\\.tmp$/, // Temporary files\n /\\.bak$/, // Backup files\n] as const;\n\n/**\n * Files/directories that are LOCAL-ONLY (never synced to gitgov-state)\n * These are regenerated or machine-specific\n */\nexport const LOCAL_ONLY_FILES = [\n 'index.json', // Generated index, rebuilt on each machine\n '.session.json', // Local session state for current user/agent\n 'gitgov', // Local binary/script\n] as const;\n\n","import type { IGitModule } from '../../git';\nimport type { ConfigManager } from \"../../config_manager\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\nimport type { ILintModule } from \"../../lint\";\nimport type { IIndexerAdapter } from \"../../adapters/indexer_adapter\";\nimport { createLogger } from \"../../logger/logger\";\nimport type { EmbeddedMetadataRecord, GitGovRecordPayload } from \"../../record_types\";\nimport {\n SyncStateError,\n PushFromStateBranchError,\n ConflictMarkersPresentError,\n NoRebaseInProgressError,\n StateBranchSetupError,\n UncommittedChangesError,\n ActorIdentityMismatchError,\n} from \"../sync_state.errors\";\nimport type { ISyncStateModule } from \"../sync_state\";\nimport type {\n SyncStateModuleDependencies,\n SyncStatePushOptions,\n SyncStatePushResult,\n SyncStatePullOptions,\n SyncStatePullResult,\n SyncStateResolveOptions,\n SyncStateResolveResult,\n IntegrityViolation,\n AuditStateOptions,\n AuditStateReport,\n ConflictDiff,\n ConflictFileDiff,\n StateDeltaFile,\n} from \"../sync_state.types\";\nimport { readFileSync, existsSync, promises as fs, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport path from \"path\";\nimport { exec } from \"child_process\";\nimport { promisify } from \"util\";\nimport os from \"os\";\nimport { SYNC_DIRECTORIES, SYNC_ROOT_FILES, SYNC_ALLOWED_EXTENSIONS, SYNC_EXCLUDED_PATTERNS, LOCAL_ONLY_FILES } from \"../sync_state.types\";\n\n// Create reusable helper\nconst execAsync = promisify(exec);\n\nconst logger = createLogger(\"[SyncStateModule] \");\n\n/**\n * Helper: Check if a file should be synced to gitgov-state\n * Returns true only for allowed *.json files in SYNC_DIRECTORIES or SYNC_ROOT_FILES\n *\n * Accepts paths in multiple formats:\n * - .gitgov/tasks/foo.json (git ls-files output)\n * - /absolute/path/.gitgov/tasks/foo.json\n * - /tmp/tempdir/tasks/foo.json (tempDir copy without .gitgov)\n * - tasks/foo.json (relative to .gitgov)\n */\nfunction shouldSyncFile(filePath: string): boolean {\n const fileName = path.basename(filePath);\n const ext = path.extname(filePath);\n\n // Check if extension is allowed\n if (!SYNC_ALLOWED_EXTENSIONS.includes(ext as typeof SYNC_ALLOWED_EXTENSIONS[number])) {\n return false;\n }\n\n // Check if file matches any excluded pattern (.key, .backup, etc.)\n for (const pattern of SYNC_EXCLUDED_PATTERNS) {\n if (pattern.test(fileName)) {\n return false;\n }\n }\n\n // Check if it's a local-only file (.session.json, index.json, gitgov)\n if (LOCAL_ONLY_FILES.includes(fileName as typeof LOCAL_ONLY_FILES[number])) {\n return false;\n }\n\n // CRITICAL: Verify file is in an allowed sync directory or is a root sync file\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n const parts = normalizedPath.split('/');\n\n // Find .gitgov in path and get the part after it\n const gitgovIndex = parts.findIndex(p => p === '.gitgov');\n\n let relativeParts: string[];\n if (gitgovIndex !== -1) {\n // Path contains .gitgov: .gitgov/tasks/foo.json or /path/.gitgov/tasks/foo.json\n relativeParts = parts.slice(gitgovIndex + 1);\n } else {\n // Path is relative to .gitgov or from tempDir: tasks/foo.json or /tmp/tempdir/tasks/foo.json\n // Check if any part matches a sync directory\n const syncDirIndex = parts.findIndex(p =>\n SYNC_DIRECTORIES.includes(p as typeof SYNC_DIRECTORIES[number])\n );\n if (syncDirIndex !== -1) {\n relativeParts = parts.slice(syncDirIndex);\n } else if (SYNC_ROOT_FILES.includes(fileName as typeof SYNC_ROOT_FILES[number])) {\n // It's a root sync file like config.json\n return true;\n } else {\n return false;\n }\n }\n\n if (relativeParts.length === 1) {\n // Root file: config.json\n return SYNC_ROOT_FILES.includes(relativeParts[0] as typeof SYNC_ROOT_FILES[number]);\n } else if (relativeParts.length >= 2) {\n // Directory file: tasks/foo.json\n const dirName = relativeParts[0];\n return SYNC_DIRECTORIES.includes(dirName as typeof SYNC_DIRECTORIES[number]);\n }\n\n return false;\n}\n\n/**\n * Helper: Recursively get all files in a directory\n */\nasync function getAllFiles(dir: string, baseDir: string = dir): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n const subFiles = await getAllFiles(fullPath, baseDir);\n files.push(...subFiles);\n } else if (entry.isFile()) {\n files.push(path.relative(baseDir, fullPath));\n }\n }\n } catch {\n // Directory doesn't exist\n }\n\n return files;\n}\n\n/**\n * Helper: Copy only syncable files from source directory to destination\n * Filters to only copy *.json files, excluding keys, backups, etc.\n *\n * @param sourceDir - Source directory (tempDir with user's local files)\n * @param destDir - Destination directory (.gitgov in gitgov-state)\n * @param log - Logging function\n * @param excludeFiles - [EARS-B23] Files to exclude from copying (remote-only changes to preserve)\n */\nasync function copySyncableFiles(\n sourceDir: string,\n destDir: string,\n log: (msg: string) => void,\n excludeFiles: Set<string> = new Set()\n): Promise<number> {\n let copiedCount = 0;\n\n // Copy sync directories (only *.json files)\n for (const dirName of SYNC_DIRECTORIES) {\n const sourcePath = path.join(sourceDir, dirName);\n const destPath = path.join(destDir, dirName);\n\n try {\n const stat = await fs.stat(sourcePath);\n if (!stat.isDirectory()) continue;\n\n // Get all files recursively\n const allFiles = await getAllFiles(sourcePath);\n\n for (const relativePath of allFiles) {\n const fullSourcePath = path.join(sourcePath, relativePath);\n const fullDestPath = path.join(destPath, relativePath);\n // [EARS-B23] Check if this file should be excluded (remote-only change)\n const gitgovRelativePath = `.gitgov/${dirName}/${relativePath}`;\n\n if (excludeFiles.has(gitgovRelativePath)) {\n log(`[EARS-B23] Skipped (remote-only change preserved): ${gitgovRelativePath}`);\n continue;\n }\n\n if (shouldSyncFile(fullSourcePath)) {\n await fs.mkdir(path.dirname(fullDestPath), { recursive: true });\n await fs.copyFile(fullSourcePath, fullDestPath);\n log(`Copied: ${dirName}/${relativePath}`);\n copiedCount++;\n } else {\n log(`Skipped (not syncable): ${dirName}/${relativePath}`);\n }\n }\n } catch (error) {\n const errCode = (error as NodeJS.ErrnoException).code;\n if (errCode !== 'ENOENT') {\n log(`Error processing ${dirName}: ${error}`);\n }\n }\n }\n\n // Copy root-level sync files\n for (const fileName of SYNC_ROOT_FILES) {\n const sourcePath = path.join(sourceDir, fileName);\n const destPath = path.join(destDir, fileName);\n // [EARS-B23] Check if this file should be excluded\n const gitgovRelativePath = `.gitgov/${fileName}`;\n\n if (excludeFiles.has(gitgovRelativePath)) {\n log(`[EARS-B23] Skipped (remote-only change preserved): ${gitgovRelativePath}`);\n continue;\n }\n\n try {\n await fs.copyFile(sourcePath, destPath);\n log(`Copied root file: ${fileName}`);\n copiedCount++;\n } catch (error) {\n const errCode = (error as NodeJS.ErrnoException).code;\n if (errCode !== 'ENOENT') {\n log(`Error copying ${fileName}: ${error}`);\n }\n }\n }\n\n return copiedCount;\n}\n\n/**\n * FsSyncStateModule - Manages state synchronization between local environment and gitgov-state branch\n *\n * Responsibilities:\n * - Create and maintain the gitgov-state branch (local and remote)\n * - Publish local changes (pushState)\n * - Pull remote changes (pullState)\n * - Resolve conflicts in a governed manner (resolveConflict)\n * - Audit state integrity (auditState)\n *\n * Philosophy:\n * - Pipeline Pattern: Sequential operations with validation at each phase\n * - Fail-Fast: Early verifications to avoid costly operations\n * - Strict Dependencies: All dependencies (git, config, identity, lint, indexer) are required for robust operations\n */\nexport class FsSyncStateModule implements ISyncStateModule {\n private git: IGitModule;\n private config: ConfigManager;\n private identity: IIdentityAdapter;\n private lint: ILintModule;\n private indexer: IIndexerAdapter;\n\n /**\n * Constructor with dependency injection\n */\n constructor(dependencies: SyncStateModuleDependencies) {\n // Validate required dependencies\n if (!dependencies.git) {\n throw new Error('IGitModule is required for SyncStateModule');\n }\n if (!dependencies.config) {\n throw new Error(\"ConfigManager is required for SyncStateModule\");\n }\n if (!dependencies.identity) {\n throw new Error(\"IdentityAdapter is required for SyncStateModule\");\n }\n if (!dependencies.lint) {\n throw new Error(\"LintModule is required for SyncStateModule\");\n }\n if (!dependencies.indexer) {\n throw new Error(\"IndexerAdapter is required for SyncStateModule\");\n }\n\n this.git = dependencies.git;\n this.config = dependencies.config;\n this.identity = dependencies.identity;\n this.lint = dependencies.lint;\n this.indexer = dependencies.indexer;\n }\n\n /**\n * Static method to bootstrap .gitgov/ from gitgov-state branch.\n * Used when cloning a repo that has gitgov-state but .gitgov/ is not in the work branch.\n *\n * This method only requires GitModule and can be called before full SyncStateModule initialization.\n *\n * @param gitModule - GitModule instance for git operations\n * @param stateBranch - Name of the state branch (default: \"gitgov-state\")\n * @returns Promise<{ success: boolean; error?: string }>\n */\n static async bootstrapFromStateBranch(\n gitModule: IGitModule,\n stateBranch: string = \"gitgov-state\"\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const repoRoot = await gitModule.getRepoRoot();\n\n // 1. Check if gitgov-state branch exists (local or remote)\n const hasLocalBranch = await gitModule.branchExists(stateBranch);\n\n let hasRemoteBranch = false;\n try {\n const remoteBranches = await gitModule.listRemoteBranches(\"origin\");\n hasRemoteBranch = remoteBranches.includes(stateBranch);\n } catch {\n // Remote might not be configured, continue with local check\n }\n\n if (!hasLocalBranch && !hasRemoteBranch) {\n return {\n success: false,\n error: `State branch '${stateBranch}' does not exist locally or remotely`,\n };\n }\n\n // 2. If only remote exists, fetch it\n if (!hasLocalBranch && hasRemoteBranch) {\n try {\n const currentBranch = await gitModule.getCurrentBranch();\n await gitModule.fetch(\"origin\");\n await execAsync(`git checkout -b ${stateBranch} origin/${stateBranch}`, { cwd: repoRoot });\n // Return to previous branch\n if (currentBranch && currentBranch !== stateBranch) {\n await gitModule.checkoutBranch(currentBranch);\n }\n } catch (error) {\n return {\n success: false,\n error: `Failed to fetch state branch: ${(error as Error).message}`,\n };\n }\n }\n\n // 3. Check if .gitgov/ exists in gitgov-state\n try {\n const { stdout } = await execAsync(`git ls-tree -r ${stateBranch} --name-only .gitgov/`, { cwd: repoRoot });\n if (!stdout.trim()) {\n return {\n success: false,\n error: `No .gitgov/ directory found in '${stateBranch}' branch`,\n };\n }\n } catch {\n return {\n success: false,\n error: `Failed to check .gitgov/ in '${stateBranch}' branch`,\n };\n }\n\n // 4. Copy .gitgov/ from gitgov-state to filesystem\n try {\n await execAsync(`git checkout ${stateBranch} -- .gitgov/`, { cwd: repoRoot });\n // Unstage the files (keep them untracked if .gitgov/ is ignored)\n await execAsync(\"git reset HEAD .gitgov/\", { cwd: repoRoot });\n logger.info(`[bootstrapFromStateBranch] Successfully restored .gitgov/ from ${stateBranch}`);\n } catch (error) {\n return {\n success: false,\n error: `Failed to copy .gitgov/ from state branch: ${(error as Error).message}`,\n };\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: `Bootstrap failed: ${(error as Error).message}`,\n };\n }\n }\n\n /**\n * Gets the state branch name from configuration.\n * Default: \"gitgov-state\"\n *\n * [EARS-A4]\n */\n async getStateBranchName(): Promise<string> {\n try {\n const config = await this.config.loadConfig();\n return config?.state?.branch ?? \"gitgov-state\";\n } catch {\n // If config loading fails, use default\n return \"gitgov-state\";\n }\n }\n\n /**\n * Ensures that the gitgov-state branch exists both locally and remotely.\n * If it doesn't exist, creates it as an orphan branch.\n *\n * Use cases (4 edge cases):\n * 1. Doesn't exist locally or remotely → Create orphan branch + initial commit + push\n * 2. Exists remotely, not locally → Fetch + create local + set tracking\n * 3. Exists locally, not remotely → Push + set tracking\n * 4. Exists both → Verify tracking\n *\n * [EARS-A1, EARS-A2, EARS-A3]\n */\n async ensureStateBranch(): Promise<void> {\n const stateBranch = await this.getStateBranchName();\n const remoteName = \"origin\";\n\n try {\n // Check local and remote existence\n const existsLocal = await this.git.branchExists(stateBranch);\n\n // Fetch to update remote references\n try {\n await this.git.fetch(remoteName);\n } catch {\n // If fetch fails (e.g., no remote configured), continue with local logic\n }\n\n // Check remote branch existence using GitModule\n const remoteBranches = await this.git.listRemoteBranches(remoteName);\n const existsRemote = remoteBranches.includes(stateBranch);\n\n // CASE 1: Doesn't exist locally or remotely → Create orphan branch + initial commit + push\n if (!existsLocal && !existsRemote) {\n await this.createOrphanStateBranch(stateBranch, remoteName);\n return;\n }\n\n // CASE 2: Exists remotely, not locally → Create local tracking remote\n if (!existsLocal && existsRemote) {\n const currentBranch = await this.git.getCurrentBranch();\n\n // Create local branch tracking remote\n // Use git checkout -b instead of checkoutOrphanBranch to create a tracking branch\n const repoRoot = await this.git.getRepoRoot();\n\n try {\n // Create local branch tracking the remote branch\n await execAsync(`git checkout -b ${stateBranch} ${remoteName}/${stateBranch}`, { cwd: repoRoot });\n\n // Branch is now created and tracking remote, return to original branch\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(currentBranch);\n }\n } catch (checkoutError) {\n // If checkout fails, try to return to original branch\n try {\n await this.git.checkoutBranch(currentBranch);\n } catch {\n // Ignore rollback error\n }\n throw checkoutError;\n }\n\n return;\n }\n\n // CASE 3: Exists locally, not remotely → Push + set tracking\n if (existsLocal && !existsRemote) {\n // Checkout to the branch to be able to push\n const currentBranch = await this.git.getCurrentBranch();\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(stateBranch);\n }\n\n try {\n await this.git.pushWithUpstream(remoteName, stateBranch);\n } catch {\n // If push fails (e.g., no remote configured), continue without error\n // Local branch remains available for local use\n }\n\n // Return to the original branch if it was different\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(currentBranch);\n }\n return;\n }\n\n // CASE 4: Exists both → Verify tracking\n if (existsLocal && existsRemote) {\n const upstreamBranch = await this.git.getBranchRemote(stateBranch);\n if (!upstreamBranch || upstreamBranch !== `${remoteName}/${stateBranch}`) {\n await this.git.setUpstream(stateBranch, remoteName, stateBranch);\n }\n return;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new StateBranchSetupError(\n `Failed to ensure state branch ${stateBranch}: ${errorMessage}`,\n error as Error\n );\n }\n }\n\n /**\n * Creates the gitgov-state orphan branch with an empty initial commit.\n * Used by ensureStateBranch when the branch doesn't exist locally or remotely.\n *\n * [EARS-A1]\n */\n private async createOrphanStateBranch(\n stateBranch: string,\n remoteName: string\n ): Promise<void> {\n const currentBranch = await this.git.getCurrentBranch();\n const repoRoot = await this.git.getRepoRoot();\n\n // Check if current branch has any commits (required to return after creating orphan)\n const currentBranchHasCommits = await this.git.branchExists(currentBranch);\n if (!currentBranchHasCommits) {\n throw new Error(\n `Cannot initialize GitGovernance: branch '${currentBranch}' has no commits. ` +\n `Please create an initial commit first (e.g., 'git commit --allow-empty -m \"Initial commit\"').`\n );\n }\n\n try {\n // 1. Create orphan branch\n await this.git.checkoutOrphanBranch(stateBranch);\n\n // 2. Clean staging area and create initial commit\n // After `git checkout --orphan`, all files from previous branch are staged\n // We need to clear them and create an empty initial commit\n\n try {\n // Remove all staged files\n await execAsync(\"git rm -rf . 2>/dev/null || true\", { cwd: repoRoot });\n\n // [EARS-C10] Create .gitignore for LOCAL_ONLY_FILES and SYNC_EXCLUDED_PATTERNS\n // This prevents these files from appearing as untracked in gitgov-state\n const gitignoreContent = `# GitGovernance State Branch .gitignore\n# This file is auto-generated during gitgov init\n# These files are machine-specific and should NOT be synced\n\n# Local-only files (regenerated/machine-specific)\nindex.json\n.session.json\ngitgov\n\n# Private keys (never synced for security)\n*.key\n\n# Backup and temporary files\n*.backup\n*.backup-*\n*.tmp\n*.bak\n`;\n const gitignorePath = path.join(repoRoot, '.gitignore');\n await fs.writeFile(gitignorePath, gitignoreContent, 'utf-8');\n await execAsync('git add .gitignore', { cwd: repoRoot });\n\n // Create initial commit directly with exec (more reliable than GitModule methods for orphan branch)\n await execAsync('git commit -m \"Initialize state branch with .gitignore\"', { cwd: repoRoot });\n } catch (commitError) {\n const error = commitError as { stderr?: string; message?: string };\n throw new Error(`Failed to create initial commit on orphan branch: ${error.stderr || error.message}`);\n }\n\n // 5. Push with upstream (if remote is configured)\n // First check if the remote is actually configured\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n\n if (hasRemote) {\n try {\n await this.git.pushWithUpstream(remoteName, stateBranch);\n } catch (pushError) {\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n // Only ignore error if it's a remote connectivity issue\n // All other errors should be investigated/thrown\n const isRemoteError =\n pushErrorMsg.includes(\"does not appear to be\") ||\n pushErrorMsg.includes(\"Could not read from remote\") ||\n pushErrorMsg.includes(\"repository not found\");\n\n if (!isRemoteError) {\n // For other errors, propagate them (something went wrong)\n throw new Error(`Failed to push state branch to remote: ${pushErrorMsg}`);\n }\n // If remote connectivity issue, continue - local branch is functional\n logger.info(`Remote '${remoteName}' not reachable, gitgov-state branch created locally only`);\n }\n } else {\n // No remote configured, continue - local branch is functional\n logger.info(`No remote '${remoteName}' configured, gitgov-state branch created locally only`);\n }\n\n // 6. Return to original branch\n await this.git.checkoutBranch(currentBranch);\n } catch (error) {\n // Rollback: try to return to original branch\n try {\n await this.git.checkoutBranch(currentBranch);\n } catch {\n // Ignore rollback error\n }\n throw error;\n }\n }\n\n /**\n * Calculates the file delta in .gitgov/ between the current branch and gitgov-state.\n *\n * [EARS-A5]\n */\n async calculateStateDelta(sourceBranch: string): Promise<StateDeltaFile[]> {\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n\n try {\n // Get changes between stateBranch and sourceBranch, filtering only .gitgov/\n const changedFiles = await this.git.getChangedFiles(\n stateBranch,\n sourceBranch,\n \".gitgov/\"\n );\n\n return changedFiles.map((file) => ({\n status: file.status,\n file: file.file,\n }));\n } catch (error) {\n throw new SyncStateError(\n `Failed to calculate state delta: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * [EARS-B23] Detect file-level conflicts and identify remote-only changes.\n *\n * A conflict exists when:\n * 1. A file was modified by the remote during implicit pull\n * 2. AND the LOCAL USER also modified that same file (content in tempDir differs from what was in git before pull)\n *\n * This catches conflicts that git rebase can't detect because we copy files AFTER the pull.\n *\n * @param tempDir - Directory containing local .gitgov/ files (preserved before checkout)\n * @param repoRoot - Repository root path\n /**\n * Checks if a rebase is in progress.\n *\n * [EARS-D6]\n */\n async isRebaseInProgress(): Promise<boolean> {\n return await this.git.isRebaseInProgress();\n }\n\n /**\n * Checks for absence of conflict markers in specified files.\n * Returns list of files that still have markers.\n *\n * [EARS-D7]\n */\n async checkConflictMarkers(filePaths: string[]): Promise<string[]> {\n const repoRoot = await this.git.getRepoRoot();\n const filesWithMarkers: string[] = [];\n\n for (const filePath of filePaths) {\n try {\n const fullPath = join(repoRoot, filePath);\n if (!existsSync(fullPath)) {\n continue;\n }\n\n const content = readFileSync(fullPath, \"utf-8\");\n const hasMarkers =\n content.includes(\"<<<<<<<\") ||\n content.includes(\"=======\") ||\n content.includes(\">>>>>>>\");\n\n if (hasMarkers) {\n filesWithMarkers.push(filePath);\n }\n } catch {\n // If read fails, assume no markers\n continue;\n }\n }\n\n return filesWithMarkers;\n }\n\n /**\n * Gets the diff of conflicted files for manual analysis.\n * Useful so the actor can analyze conflicted changes before resolving.\n *\n * [EARS-E8]\n */\n async getConflictDiff(filePaths?: string[]): Promise<ConflictDiff> {\n try {\n // Get conflicted files\n let conflictedFiles: string[];\n if (filePaths && filePaths.length > 0) {\n conflictedFiles = filePaths;\n } else {\n conflictedFiles = await this.git.getConflictedFiles();\n }\n\n if (conflictedFiles.length === 0) {\n return {\n files: [],\n message: \"No conflicted files found\",\n resolutionSteps: [],\n };\n }\n\n const repoRoot = await this.git.getRepoRoot();\n const files: ConflictFileDiff[] = [];\n\n for (const filePath of conflictedFiles) {\n const fullPath = join(repoRoot, filePath);\n\n try {\n // Read current content (with conflict markers)\n const localContent = existsSync(fullPath)\n ? readFileSync(fullPath, \"utf-8\")\n : \"\";\n\n // For simplicity, remote and base content are left empty\n // In a complete implementation, git show :1:path and :3:path would be used\n const remoteContent = \"\";\n const baseContent: string | null = null;\n\n // Detect lines with markers\n const conflictMarkers: Array<{ line: number; marker: string }> = [];\n const lines = localContent.split(\"\\n\");\n lines.forEach((line, index) => {\n if (line.startsWith(\"<<<<<<<\")) {\n conflictMarkers.push({ line: index + 1, marker: \"<<<<<<\" });\n } else if (line.startsWith(\"=======\")) {\n conflictMarkers.push({ line: index + 1, marker: \"=======\" });\n } else if (line.startsWith(\">>>>>>>\")) {\n conflictMarkers.push({ line: index + 1, marker: \">>>>>>>\" });\n }\n });\n\n const fileDiff: ConflictFileDiff = {\n filePath,\n localContent,\n remoteContent,\n baseContent,\n };\n\n if (conflictMarkers.length > 0) {\n fileDiff.conflictMarkers = conflictMarkers;\n }\n\n files.push(fileDiff);\n } catch {\n // If reading a file fails, continue with the rest\n continue;\n }\n }\n\n return {\n files,\n message: `${files.length} file(s) in conflict`,\n resolutionSteps: [\n \"1. Review the conflict diff for each file\",\n \"2. Manually edit conflicted files to resolve conflicts\",\n \"3. Remove all conflict markers (<<<<<<<, =======, >>>>>>>)\",\n \"4. Run 'gitgov sync resolve' to complete the resolution\",\n ],\n };\n } catch (error) {\n throw new SyncStateError(\n `Failed to get conflict diff: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * Verifies integrity of previous resolutions in gitgov-state history.\n * Returns list of violations if any exist.\n *\n * [EARS-E1, EARS-E2, EARS-E3]\n */\n async verifyResolutionIntegrity(): Promise<IntegrityViolation[]> {\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n const violations: IntegrityViolation[] = [];\n\n try {\n // Check if state branch exists\n const branchExists = await this.git.branchExists(stateBranch);\n if (!branchExists) {\n // Branch doesn't exist yet - no violations\n return violations;\n }\n\n // Get commit history from gitgov-state\n let commits;\n try {\n commits = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1000, // Analyze last 1000 commits\n });\n } catch (error) {\n // If branch has no commits or getCommitHistory fails, return no violations\n return violations;\n }\n\n // Analyze history to detect rebase commits without resolution\n // A \"rebase commit\" is one created by git during rebase (contains conflict markers that were resolved)\n // A \"resolution commit\" is one created by gitgov sync resolve (starts with \"resolution:\")\n for (let i = 0; i < commits.length; i++) {\n const commit = commits[i];\n if (!commit) continue;\n\n const message = commit.message.toLowerCase();\n\n // Skip resolution commits - these are NOT rebase commits, they ARE the resolution\n if (message.startsWith(\"resolution:\")) {\n continue;\n }\n\n // Skip sync commits - these are normal sync operations\n if (message.startsWith(\"sync:\")) {\n continue;\n }\n\n // Detect explicit rebase-related commits (not our own commits)\n // Only flag commits that explicitly mention rebase operations\n const isExplicitRebaseCommit =\n message.includes(\"rebase\") ||\n message.includes(\"pick \");\n\n if (isExplicitRebaseCommit) {\n // Check if the next commit is a resolution\n const nextCommit = commits[i + 1];\n const isResolutionNext =\n nextCommit && nextCommit.message.toLowerCase().startsWith(\"resolution:\");\n\n if (!isResolutionNext) {\n violations.push({\n rebaseCommitHash: commit.hash,\n commitMessage: commit.message,\n timestamp: commit.date,\n author: commit.author,\n });\n }\n }\n }\n\n return violations;\n } catch (error) {\n // If verification fails for any reason, return empty violations\n // This prevents audit from blocking operations due to verification errors\n return violations;\n }\n }\n\n /**\n * Complete audit of gitgov-state status.\n * Verifies integrity of resolutions, signatures in Records, checksums and expected files.\n *\n * [EARS-E4, EARS-E5, EARS-E6, EARS-E7]\n */\n async auditState(\n options: AuditStateOptions = {}\n ): Promise<AuditStateReport> {\n const scope = options.scope ?? \"all\";\n const verifySignatures = options.verifySignatures ?? true;\n const verifyChecksums = options.verifyChecksums ?? true;\n\n const report: AuditStateReport = {\n passed: true,\n scope,\n totalCommits: 0,\n rebaseCommits: 0,\n resolutionCommits: 0,\n integrityViolations: [],\n summary: \"\",\n };\n\n try {\n // 1. Verify resolution integrity\n const integrityViolations = await this.verifyResolutionIntegrity();\n report.integrityViolations = integrityViolations;\n\n if (integrityViolations.length > 0) {\n report.passed = false;\n }\n\n // 2. Count rebase and resolution commits\n const stateBranch = await this.getStateBranchName();\n const branchExists = await this.git.branchExists(stateBranch);\n\n if (branchExists) {\n try {\n const commits = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1000,\n });\n\n report.totalCommits = commits.length;\n report.rebaseCommits = commits.filter((c) =>\n c.message.toLowerCase().includes(\"rebase\")\n ).length;\n report.resolutionCommits = commits.filter((c) =>\n c.message.toLowerCase().startsWith(\"resolution:\")\n ).length;\n } catch {\n // If getCommitHistory fails, use defaults (0)\n report.totalCommits = 0;\n report.rebaseCommits = 0;\n report.resolutionCommits = 0;\n }\n }\n\n // 3. Verify signatures and checksums using LintModule\n if (verifySignatures || verifyChecksums) {\n const lintReport = await this.lint.lint({\n validateChecksums: verifyChecksums,\n validateSignatures: verifySignatures,\n validateReferences: false,\n concurrent: true,\n });\n\n // Store complete LintReport for consumers to access detailed validation results\n report.lintReport = lintReport;\n\n // Update audit passed status based on lint errors\n if (lintReport.summary.errors > 0) {\n report.passed = false;\n }\n }\n\n // Note: Signature/checksum/file validation is delegated to LintModule\n\n // Generate summary\n const lintErrorCount = report.lintReport?.summary.errors || 0;\n const violationCount = report.integrityViolations.length + lintErrorCount;\n\n report.summary = report.passed\n ? `Audit passed. No violations found (scope: ${scope}).`\n : `Audit failed. Found ${violationCount} violation(s): ${report.integrityViolations.length} integrity + ${lintErrorCount} structural (scope: ${scope}).`;\n\n return report;\n } catch (error) {\n throw new SyncStateError(\n `Failed to audit state: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * Publishes local state changes to gitgov-state.\n * Implements 3 phases: verification, reconciliation, publication.\n *\n * [EARS-B1 through EARS-B7]\n */\n async pushState(options: SyncStatePushOptions): Promise<SyncStatePushResult> {\n const { actorId, dryRun = false } = options;\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n let sourceBranch = options.sourceBranch;\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[pushState] ${msg}`);\n\n // Initialize result\n const result: SyncStatePushResult = {\n success: false,\n filesSynced: 0,\n sourceBranch: \"\",\n commitHash: null,\n commitMessage: null,\n conflictDetected: false,\n };\n\n // [EARS-B10] Declare stash tracking variables in outer scope for error handling\n let stashHash: string | null = null;\n let savedBranch: string = sourceBranch || \"\";\n\n try {\n log('=== STARTING pushState ===');\n\n // PRE-CHECK: Get current branch if not specified\n if (!sourceBranch) {\n sourceBranch = await this.git.getCurrentBranch();\n log(`Got current branch: ${sourceBranch}`);\n }\n result.sourceBranch = sourceBranch;\n\n // PRE-CHECK: Verify we're not on gitgov-state (EARS-B3)\n // This check must be FIRST, before audit\n if (sourceBranch === stateBranch) {\n log(`ERROR: Attempting to push from state branch ${stateBranch}`);\n throw new PushFromStateBranchError(stateBranch);\n }\n log(`Pre-check passed: pushing from ${sourceBranch} to ${stateBranch}`);\n\n // PRE-CHECK: Verify actorId matches authenticated identity\n // Prevents impersonation — you can only push as the actor whose key you hold\n const currentActor = await this.identity.getCurrentActor();\n if (currentActor.id !== actorId) {\n log(`ERROR: Actor identity mismatch: requested '${actorId}' but authenticated as '${currentActor.id}'`);\n throw new ActorIdentityMismatchError(actorId, currentActor.id);\n }\n log(`Pre-check passed: actorId '${actorId}' matches authenticated identity`);\n\n // [EARS-B11] PRE-CHECK 1: Verify remote is configured for push (FIRST!)\n // This must be checked first because without remote, sync makes no sense\n const remoteName = \"origin\";\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n if (!hasRemote) {\n log(`ERROR: No remote '${remoteName}' configured`);\n throw new SyncStateError(\n `No remote repository configured. ` +\n `State sync requires a remote for multi-machine collaboration.\\n` +\n `Add a remote with: git remote add origin <url>\\n` +\n `Then push your changes: git push -u origin ${sourceBranch}`\n );\n }\n log(`Pre-check passed: remote '${remoteName}' configured`);\n\n // [EARS-B11] PRE-CHECK 2: Verify current branch has commits\n // This is required for creating gitgov-state orphan branch and returning to original branch\n const hasCommits = await this.git.branchExists(sourceBranch);\n if (!hasCommits) {\n log(`ERROR: Branch '${sourceBranch}' has no commits`);\n throw new SyncStateError(\n `Cannot sync: branch '${sourceBranch}' has no commits. ` +\n `Please create an initial commit first (e.g., 'git commit --allow-empty -m \"Initial commit\"').`\n );\n }\n log(`Pre-check passed: branch '${sourceBranch}' has commits`);\n\n // PHASE 0: Integrity Verification and Audit (EARS-B1, EARS-B2)\n log('Phase 0: Starting audit...');\n const auditReport = await this.auditState({ scope: \"current\" });\n log(`Audit result: ${auditReport.passed ? 'PASSED' : 'FAILED'}`);\n\n if (!auditReport.passed) {\n log(`Audit violations: ${auditReport.summary}`);\n\n // Extract affected files from lint errors and integrity violations\n const affectedFiles: string[] = [];\n const detailedErrors: string[] = [];\n\n // Add files from lintReport errors\n if (auditReport.lintReport?.results) {\n for (const r of auditReport.lintReport.results) {\n if (r.level === 'error') {\n if (!affectedFiles.includes(r.filePath)) {\n affectedFiles.push(r.filePath);\n }\n detailedErrors.push(` • ${r.filePath}: [${r.validator}] ${r.message}`);\n }\n }\n }\n\n // Add info from integrity violations (commit-level)\n for (const v of auditReport.integrityViolations) {\n detailedErrors.push(` • Commit ${v.rebaseCommitHash.slice(0, 8)}: ${v.commitMessage} (by ${v.author})`);\n }\n\n // Build detailed message\n const detailSection = detailedErrors.length > 0\n ? `\\n\\nDetails:\\n${detailedErrors.join('\\n')}`\n : '';\n\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"integrity_violation\",\n affectedFiles,\n message: auditReport.summary + detailSection,\n resolutionSteps: [\n \"Run 'gitgov lint --fix' to auto-fix signature/checksum issues\",\n \"If issues persist, manually review the affected files\",\n \"Then retry: gitgov sync push\",\n ],\n };\n result.error = \"Integrity violations detected. Cannot push.\";\n return result;\n }\n\n // Ensure state branch exists\n log('Ensuring state branch exists...');\n await this.ensureStateBranch();\n log('State branch confirmed');\n\n // PHASE 1: Automatic Reconciliation (EARS-B4, EARS-B5)\n log('=== Phase 1: Reconciliation ===');\n savedBranch = sourceBranch;\n log(`Saved branch: ${savedBranch}`);\n\n // [EARS-B10] Check if current branch has untracked .gitgov/ files BEFORE stashing\n const isCurrentBranch = sourceBranch === (await this.git.getCurrentBranch());\n let hasUntrackedGitgovFiles = false;\n let tempDir: string | null = null;\n\n if (isCurrentBranch) {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovPath = path.join(repoRoot, '.gitgov');\n\n // Check if .gitgov/ EXISTS ON FILESYSTEM (not git status)\n // This is critical because .gitgov/ may be in .gitignore and git status won't show it\n hasUntrackedGitgovFiles = existsSync(gitgovPath);\n log(`[EARS-B10] .gitgov/ exists on filesystem: ${hasUntrackedGitgovFiles}`);\n\n // If untracked files exist, copy ENTIRE .gitgov/ to temp directory BEFORE stashing\n // This preserves ALL local files (not just SYNC_WHITELIST) for restoration after branch switch\n if (hasUntrackedGitgovFiles) {\n log('[EARS-B10] Copying ENTIRE .gitgov/ to temp directory for preservation...');\n\n tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gitgov-sync-'));\n log(`[EARS-B10] Created temp directory: ${tempDir}`);\n\n // Copy entire .gitgov/ directory to preserve ALL files (including local-only files)\n await fs.cp(gitgovPath, tempDir, { recursive: true });\n log('[EARS-B10] Entire .gitgov/ copied to temp');\n }\n }\n\n // [EARS-B10] Stash uncommitted changes before checkout to allow sync from dirty working tree\n // This is safe because:\n // 1. Stash preserves all local changes including .gitgov/\n // 2. We restore the stash when returning to original branch\n // 3. Enables seamless workflow: dev can work + sync without committing\n log('[EARS-B10] Checking for uncommitted changes before checkout...');\n const hasUncommittedBeforeCheckout = await this.git.hasUncommittedChanges();\n\n if (hasUncommittedBeforeCheckout) {\n log('[EARS-B10] Uncommitted changes detected, stashing before checkout...');\n stashHash = await this.git.stash('gitgov-sync-temp-stash');\n log(`[EARS-B10] Changes stashed: ${stashHash || 'none'}`);\n }\n\n // Helper function to restore stash AND tempDir when returning early\n const restoreStashAndReturn = async (returnResult: SyncStatePushResult): Promise<SyncStatePushResult> => {\n await this.git.checkoutBranch(savedBranch);\n\n // [EARS-B14] CRITICAL: Always restore tempDir FIRST to preserve local files (keys, etc.)\n if (tempDir) {\n try {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n // [EARS-B21] If implicit pull occurred, preserve new files from gitgov-state\n if (returnResult.implicitPull?.hasChanges) {\n log('[EARS-B21] Implicit pull detected in early return - preserving new files from gitgov-state...');\n // First checkout synced files from gitgov-state\n try {\n await this.git.checkoutFilesFromBranch(stateBranch, ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('[EARS-B21] Synced files copied from gitgov-state (unstaged)');\n } catch (checkoutError) {\n log(`[EARS-B21] Warning: Failed to checkout from gitgov-state: ${checkoutError}`);\n }\n // Then restore LOCAL_ONLY_FILES and EXCLUDED files from tempDir\n // [EARS-B22] This includes .key files which are excluded from sync but must be preserved\n for (const fileName of LOCAL_ONLY_FILES) {\n const tempFilePath = path.join(tempDir, fileName);\n const destFilePath = path.join(gitgovDir, fileName);\n try {\n await fs.access(tempFilePath);\n await fs.cp(tempFilePath, destFilePath, { force: true });\n log(`[EARS-B21] Restored LOCAL_ONLY_FILE: ${fileName}`);\n } catch {\n // File doesn't exist in temp, that's ok\n }\n }\n\n // [EARS-B22] Restore files matching SYNC_EXCLUDED_PATTERNS (e.g., .key files)\n const restoreExcludedFilesEarly = async (dir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(dir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcludedFilesEarly(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`[EARS-B22] Restored excluded file (early return): ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcludedFilesEarly(tempDir, gitgovDir);\n } else {\n // No implicit pull - restore everything from temp (original behavior)\n log('[EARS-B14] Restoring .gitgov/ from temp directory (early return)...');\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B14] .gitgov/ restored from temp (early return)');\n }\n\n // Cleanup temp\n await fs.rm(tempDir, { recursive: true, force: true });\n log('[EARS-B14] Temp directory cleaned up (early return)');\n } catch (tempRestoreError) {\n log(`[EARS-B14] WARNING: Failed to restore tempDir: ${tempRestoreError}`);\n returnResult.error = returnResult.error\n ? `${returnResult.error}. Failed to restore .gitgov/ from temp.`\n : `Failed to restore .gitgov/ from temp. Check /tmp for gitgov-sync-* directory.`;\n }\n }\n\n if (stashHash) {\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored');\n } catch (stashError) {\n log(`[EARS-B10] Failed to restore stash: ${stashError}`);\n returnResult.error = returnResult.error\n ? `${returnResult.error}. Failed to restore stashed changes.`\n : 'Failed to restore stashed changes. Run \\'git stash pop\\' manually.';\n }\n }\n\n // [EARS-B21] Regenerate index if implicit pull brought changes (even on early return)\n if (returnResult.implicitPull?.hasChanges) {\n log('[EARS-B21] Regenerating index after implicit pull (early return)...');\n try {\n await this.indexer.generateIndex();\n returnResult.implicitPull.reindexed = true;\n log('[EARS-B21] Index regenerated successfully');\n } catch (indexError) {\n log(`[EARS-B21] Warning: Failed to regenerate index: ${indexError}`);\n returnResult.implicitPull.reindexed = false;\n }\n }\n\n return returnResult;\n };\n\n // Checkout to gitgov-state\n log(`Checking out to ${stateBranch}...`);\n await this.git.checkoutBranch(stateBranch);\n log(`Now on branch: ${await this.git.getCurrentBranch()}`);\n\n // Note: We don't check for uncommitted changes here because:\n // 1. Untracked files from working tree (like .gitgov/) are expected and harmless\n // 2. If there are actual staged changes, git commit will detect them\n // 3. This allows seamless workflow without false positives from untracked files\n\n // [EARS-B19] Capture files in gitgov-state BEFORE any changes to distinguish user deletions vs new remote files\n let filesBeforeChanges: Set<string> = new Set();\n try {\n const repoRoot = await this.git.getRepoRoot();\n const { stdout: filesOutput } = await execAsync(\n `git ls-files \".gitgov\" 2>/dev/null || true`,\n { cwd: repoRoot }\n );\n filesBeforeChanges = new Set(filesOutput.trim().split('\\n').filter(f => f && shouldSyncFile(f)));\n log(`[EARS-B19] Files in gitgov-state before changes: ${filesBeforeChanges.size}`);\n } catch {\n // Ignore - might be first commit\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // GIT-NATIVE SYNC FLOW\n // Order: Copy files → Commit locally → Pull --rebase → Push\n // This allows Git to detect conflicts naturally (modify/modify, delete/modify)\n // ═══════════════════════════════════════════════════════════════════════════\n\n // PHASE 2: Stage Local Changes (EARS-B6, EARS-B7, EARS-B8, EARS-B9)\n log('=== Phase 2: Publication ===');\n\n // [EARS-B8] Detect first push: check if .gitgov/ exists in gitgov-state\n log('Checking if .gitgov/ exists in gitgov-state...');\n let isFirstPush = false;\n try {\n const repoRoot = await this.git.getRepoRoot();\n\n // Check if .gitgov/ directory exists in gitgov-state branch\n const { stdout } = await execAsync(\n `git ls-tree -d ${stateBranch} .gitgov`,\n { cwd: repoRoot }\n );\n\n isFirstPush = !stdout.trim(); // If empty, .gitgov/ doesn't exist\n log(`First push detected: ${isFirstPush}`);\n } catch (error) {\n // If command fails, assume first push\n log('Error checking .gitgov/ existence, assuming first push');\n isFirstPush = true;\n }\n\n // Calculate change delta (skip for first push, will copy everything from whitelist)\n let delta: StateDeltaFile[] = [];\n if (!isFirstPush) {\n log('Calculating state delta...');\n delta = await this.calculateStateDelta(sourceBranch);\n log(`Delta: ${delta.length} file(s) changed`);\n\n // If no changes, return without commit (EARS-B6)\n if (delta.length === 0) {\n log('No changes detected, returning without commit');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n } else {\n log('First push: will copy all whitelisted files');\n }\n\n // [EARS-B9] & [EARS-B10] Copy ONLY syncable files (*.json, no keys, no backups)\n log(`Copying syncable .gitgov/ files from ${sourceBranch}...`);\n log(`Sync directories: ${SYNC_DIRECTORIES.join(', ')}`);\n log(`Sync root files: ${SYNC_ROOT_FILES.join(', ')}`);\n\n const repoRoot = await this.git.getRepoRoot();\n\n // Note: untracked file detection was moved earlier, before stashing\n\n // If we have temp directory with untracked files, copy from there\n // Otherwise, use git checkout from source branch\n if (tempDir) {\n log('[EARS-B10] Copying ONLY syncable files from temp directory...');\n\n // Create .gitgov/ directory if it doesn't exist (first push to orphan branch)\n const gitgovDir = path.join(repoRoot, '.gitgov');\n await fs.mkdir(gitgovDir, { recursive: true });\n log(`[EARS-B10] Ensured .gitgov/ directory exists: ${gitgovDir}`);\n\n // Copy only syncable files (*.json, no keys, no backups)\n // Git-native flow: we copy ALL local files, then commit, then pull --rebase\n // Git will detect conflicts during rebase if same file was modified remotely\n const copiedCount = await copySyncableFiles(tempDir, gitgovDir, log);\n log(`[EARS-B10] Syncable files copy complete: ${copiedCount} files copied`);\n } else {\n // Use git checkout for tracked files\n log('Copying syncable files from git...');\n\n // Build list of paths that exist in source branch AND are syncable\n const existingPaths: string[] = [];\n\n // Check sync directories\n for (const dirName of SYNC_DIRECTORIES) {\n const fullPath = `.gitgov/${dirName}`;\n try {\n const { stdout } = await execAsync(\n `git ls-tree -r ${sourceBranch} -- ${fullPath}`,\n { cwd: repoRoot }\n );\n // Filter to only include syncable files (*.json, no keys, no backups)\n const lines = stdout.trim().split('\\n').filter(l => l);\n for (const line of lines) {\n const parts = line.split('\\t');\n const filePath = parts[1];\n if (filePath && shouldSyncFile(filePath)) {\n existingPaths.push(filePath);\n } else if (filePath) {\n log(`Skipped (not syncable): ${filePath}`);\n }\n }\n } catch {\n log(`Directory ${dirName} does not exist in ${sourceBranch}, skipping`);\n }\n }\n\n // Check root sync files\n for (const fileName of SYNC_ROOT_FILES) {\n const fullPath = `.gitgov/${fileName}`;\n try {\n const { stdout } = await execAsync(\n `git ls-tree ${sourceBranch} -- ${fullPath}`,\n { cwd: repoRoot }\n );\n if (stdout.trim()) {\n existingPaths.push(fullPath);\n }\n } catch {\n log(`File ${fileName} does not exist in ${sourceBranch}, skipping`);\n }\n }\n\n log(`Syncable paths found: ${existingPaths.length}`);\n\n if (existingPaths.length === 0) {\n log('No syncable files to sync, aborting');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Copy only syncable files\n await this.git.checkoutFilesFromBranch(sourceBranch, existingPaths);\n log('Syncable files checked out successfully');\n }\n\n // Create structured commit message\n const timestamp = new Date().toISOString();\n\n // For first push, we need to recalculate delta now that files are staged\n if (isFirstPush) {\n // Stage the copied files first\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n\n // Get list of staged files for commit message\n const repoRoot = await this.git.getRepoRoot();\n\n try {\n const { stdout } = await execAsync(\n 'git diff --cached --name-status',\n { cwd: repoRoot }\n );\n\n const lines = stdout.trim().split('\\n').filter(l => l);\n delta = lines\n .map(line => {\n const [status, file] = line.split('\\t');\n if (!file) return null; // Skip invalid lines\n return {\n status: status as 'A' | 'M' | 'D',\n file\n };\n })\n .filter((item): item is StateDeltaFile => item !== null);\n log(`First push delta calculated: ${delta.length} file(s)`);\n } catch (error) {\n log('Error calculating first push delta, using empty delta');\n delta = [];\n }\n }\n\n const commitMessage =\n `sync: ${isFirstPush ? 'Initial state' : 'Publish state'} from ${sourceBranch}\\n\\n` +\n `Actor: ${actorId}\\n` +\n `Timestamp: ${timestamp}\\n` +\n `Files: ${delta.length} file(s) ${isFirstPush ? 'synced (initial)' : 'changed'}\\n\\n` +\n delta.map((d) => `${d.status} ${d.file}`).join(\"\\n\");\n\n result.commitMessage = commitMessage;\n\n if (!dryRun) {\n // IMPORTANT: Stage ALL files FIRST, then cleanup non-syncable files\n // This ensures EARS-B14 can detect and remove untracked files from worktree\n // that shouldn't be synced (like .session.json, gitgov binary)\n if (!isFirstPush) {\n log('Staging all .gitgov/ files before cleanup...');\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n log('All files staged, proceeding to cleanup');\n }\n\n // [EARS-B14] Remove ALL non-syncable files from gitgov-state\n // This ensures only files that pass shouldSyncFile() remain in shared state\n // MUST run AFTER git add so we can detect and remove untracked files\n log('[EARS-B14] Scanning for non-syncable files in gitgov-state...');\n\n // Get ALL files currently in staging area for .gitgov/\n try {\n const { stdout: trackedFiles } = await execAsync(\n `git ls-files \".gitgov\" 2>/dev/null || true`,\n { cwd: repoRoot }\n );\n const allTrackedFiles = trackedFiles.trim().split('\\n').filter(f => f);\n log(`[EARS-B14] Found ${allTrackedFiles.length} staged/tracked files in .gitgov/`);\n\n // Remove any file that should NOT be synced (using the same shouldSyncFile() logic)\n for (const trackedFile of allTrackedFiles) {\n if (!shouldSyncFile(trackedFile)) {\n try {\n await execAsync(`git rm -f \"${trackedFile}\"`, { cwd: repoRoot });\n log(`[EARS-B14] Removed non-syncable file: ${trackedFile}`);\n } catch {\n // File might not exist or not be tracked anymore\n }\n }\n }\n } catch {\n // No tracked files, that's fine (first push)\n }\n\n log('[EARS-B14] Non-syncable files cleanup complete');\n\n // [EARS-B19] Sync deleted files: remove files from gitgov-state that no longer exist in source\n // This handles the case where a user deletes a record locally and pushes\n // In Git-native flow, deleted files will be detected during rebase if there's a conflict\n log('[EARS-B19] Checking for deleted files to sync...');\n\n try {\n // Get all syncable files in source (tempDir = user's local state)\n const sourceFiles = new Set<string>();\n\n // Recursively find all files in source\n const findSourceFiles = async (dir: string, prefix: string = '.gitgov') => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = `${prefix}/${entry.name}`;\n if (entry.isDirectory()) {\n await findSourceFiles(fullPath, relativePath);\n } else if (shouldSyncFile(relativePath)) {\n sourceFiles.add(relativePath);\n }\n }\n } catch {\n // Directory doesn't exist, that's ok\n }\n };\n\n // Use tempDir if available (untracked files case), otherwise working tree\n const sourceDir = tempDir || path.join(repoRoot, '.gitgov');\n await findSourceFiles(sourceDir);\n log(`[EARS-B19] Found ${sourceFiles.size} syncable files in source (user's local state)`);\n log(`[EARS-B19] Files that existed before changes: ${filesBeforeChanges.size}`);\n\n // Delete files that:\n // 1. Existed in gitgov-state BEFORE our changes (filesBeforeChanges)\n // 2. Are NOT in user's local state (sourceFiles/tempDir)\n // This ensures we only delete files the user intentionally removed\n let deletedCount = 0;\n for (const fileBeforeChange of filesBeforeChanges) {\n if (!sourceFiles.has(fileBeforeChange)) {\n try {\n await execAsync(`git rm -f \"${fileBeforeChange}\"`, { cwd: repoRoot });\n log(`[EARS-B19] Deleted (user removed): ${fileBeforeChange}`);\n deletedCount++;\n } catch {\n // File might already be removed or not tracked\n }\n }\n }\n log(`[EARS-B19] Deleted ${deletedCount} files that user removed locally`);\n } catch (err) {\n log(`[EARS-B19] Warning: Failed to sync deleted files: ${err}`);\n }\n\n // Verify there are staged changes\n const hasStaged = await this.git.hasUncommittedChanges();\n log(`Has staged changes: ${hasStaged}`);\n\n if (!hasStaged) {\n log('No staged changes detected, returning without commit');\n // No changes to commit - return early\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Create commit\n log('Creating local commit...');\n try {\n const commitHash = await this.git.commit(commitMessage);\n log(`Local commit created: ${commitHash}`);\n result.commitHash = commitHash;\n } catch (commitError) {\n // Check if this is a \"nothing to commit\" error (common on second push with identical files)\n const errorMsg = commitError instanceof Error ? commitError.message : String(commitError);\n const stdout = (commitError as any).stdout || '';\n const stderr = (commitError as any).stderr || '';\n\n log(`Commit attempt output - stdout: ${stdout}, stderr: ${stderr}`);\n\n // Git returns exit code 1 with \"nothing to commit\" in stdout when there are no changes\n const isNothingToCommit =\n stdout.includes('nothing to commit') ||\n stderr.includes('nothing to commit') ||\n stdout.includes('nothing added to commit') ||\n stderr.includes('nothing added to commit');\n\n if (isNothingToCommit) {\n log('Nothing to commit - files are identical to gitgov-state HEAD');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Otherwise, it's a real error\n log(`ERROR: Commit failed: ${errorMsg}`);\n log(`ERROR: Git stderr: ${stderr}`);\n throw new Error(`Failed to create commit: ${errorMsg} | stderr: ${stderr}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // GIT-NATIVE CONFLICT DETECTION: Pull --rebase AFTER local commit\n // This is the key change: Git can now detect conflicts naturally because\n // we have a local commit to rebase onto the remote changes\n // ═══════════════════════════════════════════════════════════════════════════\n log('=== Phase 3: Reconcile with Remote (Git-Native) ===');\n\n // Capture hash before pull to detect if remote had changes\n let hashBeforePull: string | null = null;\n try {\n const { stdout: beforeHash } = await execAsync(`git rev-parse HEAD`, { cwd: repoRoot });\n hashBeforePull = beforeHash.trim();\n log(`Hash before pull: ${hashBeforePull}`);\n } catch {\n // Ignore\n }\n\n // Attempt pull --rebase to reconcile with remote\n log('Attempting git pull --rebase origin gitgov-state...');\n try {\n await this.git.pullRebase(\"origin\", stateBranch);\n log('Pull rebase successful - no conflicts');\n\n // [EARS-B16] Check if remote had changes (implicit pull)\n if (hashBeforePull) {\n try {\n const { stdout: afterHash } = await execAsync(`git rev-parse HEAD`, { cwd: repoRoot });\n const hashAfterPull = afterHash.trim();\n\n if (hashAfterPull !== hashBeforePull) {\n // Our commit was rebased on top of remote changes\n const pulledChangedFiles = await this.git.getChangedFiles(hashBeforePull, hashAfterPull, \".gitgov/\");\n result.implicitPull = {\n hasChanges: true,\n filesUpdated: pulledChangedFiles.length,\n reindexed: false // Will be set to true after actual reindex\n };\n log(`[EARS-B16] Implicit pull: ${pulledChangedFiles.length} files from remote were rebased`);\n }\n } catch (e) {\n log(`[EARS-B16] Could not capture implicit pull details: ${e}`);\n }\n }\n } catch (pullError) {\n const errorMsg = pullError instanceof Error ? pullError.message : String(pullError);\n log(`Pull rebase result: ${errorMsg}`);\n\n const isAlreadyUpToDate = errorMsg.includes(\"up to date\") || errorMsg.includes(\"up-to-date\");\n const isNoRemote = errorMsg.includes(\"does not appear to be\") || errorMsg.includes(\"Could not read from remote\");\n const isNoUpstream = errorMsg.includes(\"no tracking information\") || errorMsg.includes(\"There is no tracking information\");\n\n if (isAlreadyUpToDate || isNoRemote || isNoUpstream) {\n log('Pull not needed or no remote - continuing to push');\n // Continue - we'll just push our local commit\n } else {\n // Check if it's a conflict - THIS IS THE GIT-NATIVE CONFLICT DETECTION\n const isRebaseInProgress = await this.isRebaseInProgress();\n const conflictedFiles = await this.git.getConflictedFiles();\n\n if (isRebaseInProgress || conflictedFiles.length > 0) {\n log(`[GIT-NATIVE] Conflict detected! Files: ${conflictedFiles.join(', ')}`);\n\n // DO NOT abort - leave rebase in progress for user to resolve with git tools\n result.conflictDetected = true;\n // Build dynamic resolution steps based on number of conflicted files\n const fileWord = conflictedFiles.length === 1 ? \"file\" : \"files\";\n const stageCommand = conflictedFiles.length === 1\n ? `git add ${conflictedFiles[0]}`\n : \"git add .gitgov/\";\n\n result.conflictInfo = {\n type: \"rebase_conflict\",\n affectedFiles: conflictedFiles,\n message: \"Conflict detected during sync - Git has paused the rebase for manual resolution\",\n resolutionSteps: [\n `1. Edit the conflicted ${fileWord} to resolve conflicts (remove <<<<<<, ======, >>>>>> markers)`,\n `2. Stage resolved ${fileWord}: ${stageCommand}`,\n \"3. Complete sync: gitgov sync resolve --reason 'your reason'\",\n \"(This will continue the rebase, re-sign the record, and return you to your original branch)\"\n ]\n };\n result.error = `Conflict detected: ${conflictedFiles.length} file(s) need manual resolution. Use 'git status' to see details.`;\n\n // DO NOT restore to original branch - user must resolve in gitgov-state\n // But restore stash to original branch if there was one\n if (stashHash) {\n try {\n await this.git.checkoutBranch(sourceBranch);\n await execAsync('git stash pop', { cwd: repoRoot });\n await this.git.checkoutBranch(stateBranch);\n log('Restored stash to original branch during conflict');\n } catch (stashErr) {\n log(`Warning: Could not restore stash: ${stashErr}`);\n }\n }\n\n // CRITICAL: Restore LOCAL_ONLY_FILES and EXCLUDED files (.key) to gitgov-state\n // These are needed for signing during conflict resolution\n if (tempDir) {\n log('Restoring local files (.key, .session.json, etc.) for conflict resolution...');\n const gitgovInState = path.join(repoRoot, '.gitgov');\n\n // Restore LOCAL_ONLY_FILES\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(tempDir, fileName);\n const destPath = path.join(gitgovInState, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Restored LOCAL_ONLY_FILE for conflict resolution: ${fileName}`);\n } catch {\n // File doesn't exist in temp, ok\n }\n }\n\n // Restore EXCLUDED files (like .key) recursively\n const restoreExcluded = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcluded(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Restored EXCLUDED file for conflict resolution: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcluded(tempDir, gitgovInState);\n log('Local files restored for conflict resolution');\n }\n\n return result;\n }\n\n // Not a conflict, propagate the error\n throw pullError;\n }\n }\n\n // Push\n log('=== Phase 4: Push to Remote ===');\n log('Pushing to remote...');\n try {\n await this.git.push(\"origin\", stateBranch);\n log('Push successful');\n } catch (pushError) {\n // If push fails, check if it's a \"no remote\" error\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n log(`Push failed: ${pushErrorMsg}`);\n\n const isNoRemote = pushErrorMsg.includes(\"does not appear to be\") || pushErrorMsg.includes(\"Could not read from remote\");\n\n if (!isNoRemote) {\n log('ERROR: Push failed with non-remote error');\n // If it's not a \"no remote\" error, propagate it\n throw pushError;\n }\n log('Push failed due to no remote, continuing (local commit succeeded)');\n // Otherwise, continue - commit succeeded locally even if push failed\n }\n }\n\n // Return to original branch\n log(`Returning to ${savedBranch}...`);\n await this.git.checkoutBranch(savedBranch);\n log(`Back on ${await this.git.getCurrentBranch()}`);\n\n // [EARS-B10] Restore stashed changes\n if (stashHash) {\n log('[EARS-B10] Restoring stashed changes...');\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored successfully');\n } catch (stashError) {\n log(`[EARS-B10] Warning: Failed to restore stashed changes: ${stashError}`);\n // Don't fail the push if stash pop fails, but warn the user\n result.error = `Push succeeded but failed to restore stashed changes. Run 'git stash pop' manually. Error: ${stashError}`;\n }\n }\n\n // [EARS-B10] Restore files from temp directory back to working tree\n // [EARS-B18] If implicit pull occurred, we must keep the NEW synced files from gitgov-state,\n // only restoring LOCAL_ONLY_FILES from tempDir\n if (tempDir) {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n if (result.implicitPull?.hasChanges) {\n // [EARS-B18] Implicit pull occurred - we need to preserve the new files from remote\n log('[EARS-B18] Implicit pull detected - copying synced files from gitgov-state first...');\n\n // First, checkout the synced directories/files from gitgov-state to work branch\n // This brings the newly pulled files to the work tree\n try {\n await this.git.checkoutFilesFromBranch(stateBranch, ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('[EARS-B18] Synced files copied from gitgov-state to work branch (unstaged)');\n } catch (checkoutError) {\n log(`[EARS-B18] Warning: Failed to checkout from gitgov-state: ${checkoutError}`);\n // Fall back to restoring everything from temp\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B18] Fallback: Entire .gitgov/ restored from temp');\n }\n\n // Then, restore LOCAL_ONLY_FILES and EXCLUDED files from tempDir (they're not in gitgov-state)\n // [EARS-B22] This includes .key files which are excluded from sync but must be preserved\n log('[EARS-B18] Restoring local-only files from temp directory...');\n\n // Restore LOCAL_ONLY_FILES (root level: .session.json, index.json, gitgov)\n for (const fileName of LOCAL_ONLY_FILES) {\n const tempFilePath = path.join(tempDir, fileName);\n const destFilePath = path.join(gitgovDir, fileName);\n try {\n await fs.access(tempFilePath);\n await fs.cp(tempFilePath, destFilePath, { force: true });\n log(`[EARS-B18] Restored LOCAL_ONLY_FILE: ${fileName}`);\n } catch {\n // File doesn't exist in temp, that's ok\n }\n }\n\n // [EARS-B22] Restore files matching SYNC_EXCLUDED_PATTERNS (e.g., .key files in actors/)\n // These are local-only files that exist in subdirectories\n const restoreExcludedFiles = async (dir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(dir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n\n if (entry.isDirectory()) {\n await restoreExcludedFiles(srcPath, dstPath);\n } else {\n // Check if this file matches any excluded pattern\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`[EARS-B22] Restored excluded file: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist, that's ok\n }\n };\n\n await restoreExcludedFiles(tempDir, gitgovDir);\n log('[EARS-B22] Local-only and excluded files restored from temp');\n } else {\n // No implicit pull - restore everything from temp (original behavior)\n log('[EARS-B10] Restoring ENTIRE .gitgov/ from temp directory to working tree...');\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B10] Entire .gitgov/ restored from temp');\n }\n\n // Cleanup temp directory\n log('[EARS-B10] Cleaning up temp directory...');\n try {\n await fs.rm(tempDir, { recursive: true, force: true });\n log('[EARS-B10] Temp directory cleaned up');\n } catch (cleanupError) {\n log(`[EARS-B10] Warning: Failed to cleanup temp directory: ${cleanupError}`);\n }\n }\n\n // [EARS-B17] If implicit pull occurred, regenerate index NOW (after returning to work branch)\n // Previously, reindexed: true was just a flag but indexer was never called - BUG!\n if (result.implicitPull?.hasChanges) {\n log('[EARS-B16] Regenerating index after implicit pull...');\n try {\n await this.indexer.generateIndex();\n result.implicitPull.reindexed = true;\n log('[EARS-B16] Index regenerated successfully after implicit pull');\n } catch (indexError) {\n log(`[EARS-B16] Warning: Failed to regenerate index after implicit pull: ${indexError}`);\n result.implicitPull.reindexed = false;\n }\n }\n\n result.success = true;\n result.filesSynced = delta.length;\n log(`=== pushState COMPLETED SUCCESSFULLY: ${delta.length} files synced ===`);\n return result;\n } catch (error) {\n log(`=== pushState FAILED: ${(error as Error).message} ===`);\n\n // [EARS-B10] Try to restore original branch even on error (ALWAYS, not just with stash)\n try {\n const currentBranch = await this.git.getCurrentBranch();\n if (currentBranch !== savedBranch && savedBranch) {\n log(`[EARS-B10] Restoring original branch: ${savedBranch}...`);\n await this.git.checkoutBranch(savedBranch);\n log(`[EARS-B10] Restored to ${savedBranch}`);\n }\n } catch (branchError) {\n log(`[EARS-B10] Failed to restore original branch: ${branchError}`);\n }\n\n // [EARS-B10] Try to restore stashed changes if any\n if (stashHash) {\n log('[EARS-B10] Attempting to restore stashed changes after error...');\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored after error');\n } catch (stashError) {\n log(`[EARS-B10] Failed to restore stashed changes after error: ${stashError}`);\n // Add to error message\n const originalError = (error as Error).message;\n (error as Error).message = `${originalError}. Additionally, failed to restore stashed changes. Run 'git stash pop' manually.`;\n }\n }\n\n // Re-throw critical errors that should fail fast\n if (\n error instanceof PushFromStateBranchError ||\n error instanceof UncommittedChangesError\n ) {\n throw error;\n }\n\n // For other errors, return result with error message\n result.error = (error as Error).message;\n return result;\n }\n }\n\n /**\n * Pulls remote changes from gitgov-state to the local environment.\n * Includes automatic re-indexing if there are new changes.\n *\n * [EARS-C1 through EARS-C4]\n * [EARS-C5] Requires remote to be configured (pull without remote makes no sense)\n */\n async pullState(\n options: SyncStatePullOptions = {}\n ): Promise<SyncStatePullResult> {\n const { forceReindex = false, force = false } = options;\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[pullState] ${msg}`);\n\n // Initialize result\n const result: SyncStatePullResult = {\n success: false,\n hasChanges: false,\n filesUpdated: 0,\n reindexed: false,\n conflictDetected: false,\n };\n\n try {\n log('=== STARTING pullState ===');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 0: Pre-flight Checks (EARS-C5)\n // ═══════════════════════════════════════════════════════════\n log('Phase 0: Pre-flight checks...');\n\n // [EARS-C5] PRE-CHECK: Verify remote is configured (pull without remote is meaningless)\n const remoteName = \"origin\";\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n\n if (!hasRemote) {\n throw new SyncStateError(\n `No remote '${remoteName}' configured. Pull requires a remote repository. ` +\n `Add a remote with: git remote add origin <url>`\n );\n }\n\n // [EARS-C5] PRE-CHECK: Verify gitgov-state exists remotely\n // Fetch first to get latest remote refs\n await this.git.fetch(remoteName);\n const remoteBranches = await this.git.listRemoteBranches(remoteName);\n const existsRemote = remoteBranches.includes(stateBranch);\n\n if (!existsRemote) {\n // Check if local branch exists (maybe not pushed yet)\n const existsLocal = await this.git.branchExists(stateBranch);\n\n if (!existsLocal) {\n // Check if .gitgov/ exists - if so, user already ran init and just needs to push\n const repoRoot = await this.git.getRepoRoot();\n const gitgovPath = path.join(repoRoot, \".gitgov\");\n const gitgovExists = existsSync(gitgovPath);\n\n if (gitgovExists) {\n // User has .gitgov/ but hasn't pushed yet - suggest sync push\n throw new SyncStateError(\n `State branch '${stateBranch}' does not exist remotely yet. ` +\n `Run 'gitgov sync push' to publish your local state to the remote.`\n );\n } else {\n // User hasn't initialized at all\n throw new SyncStateError(\n `State branch '${stateBranch}' does not exist locally or remotely. ` +\n `Run 'gitgov init' first to initialize GitGovernance, then 'gitgov sync push' to publish.`\n );\n }\n }\n\n // Local exists but remote doesn't - nothing to pull\n result.success = true;\n result.hasChanges = false;\n result.filesUpdated = 0;\n logger.info(`[pullState] State branch exists locally but not remotely. Nothing to pull.`);\n return result;\n }\n\n log('Pre-flight checks complete');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 1: Branch Setup and Verification\n // ═══════════════════════════════════════════════════════════\n log('Phase 1: Setting up branches...');\n\n // Get repoRoot early for use throughout this function\n const pullRepoRoot = await this.git.getRepoRoot();\n\n // 1. Pre-checks - ensure local branch tracks remote\n await this.ensureStateBranch();\n\n const savedBranch = await this.git.getCurrentBranch();\n\n // [EARS-C8] Save LOCAL_ONLY_FILES before checkout\n // When .gitgov/ is untracked on work branch but tracked on gitgov-state,\n // git checkout will fail or overwrite files. We save local-only files first.\n const savedLocalFiles: Map<string, string> = new Map();\n try {\n for (const fileName of LOCAL_ONLY_FILES) {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n savedLocalFiles.set(fileName, content);\n log(`[EARS-C8] Saved local-only file: ${fileName}`);\n } catch {\n // File doesn't exist, that's fine\n }\n }\n } catch (error) {\n log(`[EARS-C8] Warning: Could not save local files: ${(error as Error).message}`);\n }\n\n // [EARS-C10] Save ALL syncable files BEFORE checkout for conflict detection\n // We need to compare local changes vs remote changes BEFORE checkout overwrites them\n const savedSyncableFiles: Map<string, string> = new Map();\n try {\n const gitgovPath = path.join(pullRepoRoot, \".gitgov\");\n const gitgovExists = await fs.access(gitgovPath).then(() => true).catch(() => false);\n\n if (gitgovExists) {\n // Recursively read all syncable files\n const readSyncableFilesRecursive = async (dir: string, baseDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(baseDir, fullPath);\n const gitgovRelativePath = `.gitgov/${relativePath}`;\n\n if (entry.isDirectory()) {\n await readSyncableFilesRecursive(fullPath, baseDir);\n } else if (shouldSyncFile(gitgovRelativePath)) {\n try {\n const content = await fs.readFile(fullPath, 'utf-8');\n savedSyncableFiles.set(gitgovRelativePath, content);\n } catch {\n // Ignore read errors\n }\n }\n }\n } catch {\n // Ignore directory read errors\n }\n };\n\n await readSyncableFilesRecursive(gitgovPath, gitgovPath);\n log(`[EARS-C10] Saved ${savedSyncableFiles.size} syncable files before checkout for conflict detection`);\n }\n } catch (error) {\n log(`[EARS-C10] Warning: Could not save syncable files: ${(error as Error).message}`);\n }\n\n // Checkout to gitgov-state\n // Use force to handle case where .gitgov/ is untracked on work branch\n // but tracked on gitgov-state (would otherwise fail with \"would be overwritten\")\n try {\n await this.git.checkoutBranch(stateBranch);\n } catch (checkoutError) {\n // If normal checkout fails, try with force\n log(`[EARS-C8] Normal checkout failed, trying with force: ${(checkoutError as Error).message}`);\n try {\n await execAsync(`git checkout -f ${stateBranch}`, { cwd: pullRepoRoot });\n log(`[EARS-C8] Force checkout successful`);\n } catch (forceError) {\n // Still failed - rethrow original error\n throw checkoutError;\n }\n }\n\n // Verify no staged or modified changes (ignore untracked files)\n // Untracked files from work branch are expected and harmless in gitgov-state\n try {\n // Check only for staged (A, M, D) or modified (M) files, NOT untracked (??)\n const { stdout } = await execAsync('git status --porcelain', { cwd: pullRepoRoot });\n const lines = stdout.trim().split('\\n').filter(l => l);\n const hasStagedOrModified = lines.some(line => {\n const status = line.substring(0, 2);\n // Ignore untracked files (??), only check for staged/modified\n return status !== '??' && status.trim().length > 0;\n });\n\n if (hasStagedOrModified) {\n await this.git.checkoutBranch(savedBranch);\n throw new UncommittedChangesError(stateBranch);\n }\n } catch (error) {\n if (error instanceof UncommittedChangesError) {\n throw error;\n }\n // If git status fails, continue (branch might be clean)\n }\n\n log('Branch setup complete');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 2: Pull Remote Changes (EARS-C1, EARS-C2)\n // ═══════════════════════════════════════════════════════════\n log('Phase 2: Pulling remote changes...');\n\n // 2. Save current commit to compare later\n const commitBefore = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1,\n });\n const hashBefore = commitBefore[0]?.hash;\n\n // 3. Fetch to get remote refs\n await this.git.fetch(\"origin\");\n\n // ═══════════════════════════════════════════════════════════\n // [EARS-C10] CONFLICT DETECTION: Detect if local changes would be overwritten\n // Compare: savedSyncableFiles (captured BEFORE checkout) vs gitgov-state vs origin/gitgov-state\n // If same file modified locally AND remotely → abort like git pull does\n // ═══════════════════════════════════════════════════════════\n log('[EARS-C10] Checking for local changes that would be overwritten...');\n\n // Step 1: Get files that changed in remote (origin/gitgov-state vs local gitgov-state)\n let remoteChangedFiles: string[] = [];\n try {\n const { stdout: remoteChanges } = await execAsync(\n `git diff --name-only ${stateBranch} origin/${stateBranch} -- .gitgov/ 2>/dev/null || true`,\n { cwd: pullRepoRoot }\n );\n remoteChangedFiles = remoteChanges.trim().split('\\n').filter(f => f && shouldSyncFile(f));\n log(`[EARS-C10] Remote changed files: ${remoteChangedFiles.length} - ${remoteChangedFiles.join(', ')}`);\n } catch {\n log('[EARS-C10] Could not determine remote changes, continuing...');\n }\n\n // Step 2: Check if local files (saved BEFORE checkout) differ from gitgov-state HEAD\n // This detects: user edited file locally that was also edited remotely\n let localModifiedFiles: string[] = [];\n if (remoteChangedFiles.length > 0 && savedSyncableFiles.size > 0) {\n try {\n for (const remoteFile of remoteChangedFiles) {\n // Check if we have a saved version of this file (from before checkout)\n const savedContent = savedSyncableFiles.get(remoteFile);\n\n if (savedContent !== undefined) {\n // Get content from gitgov-state HEAD (what was synced last time)\n try {\n const { stdout: gitStateContent } = await execAsync(\n `git show HEAD:${remoteFile} 2>/dev/null`,\n { cwd: pullRepoRoot }\n );\n\n // Compare saved local content vs last synced content\n // If different, user modified this file locally since last sync\n if (savedContent !== gitStateContent) {\n localModifiedFiles.push(remoteFile);\n log(`[EARS-C10] Local file was modified since last sync: ${remoteFile}`);\n }\n } catch {\n // File doesn't exist in gitgov-state HEAD (new file locally)\n // This is also a local modification\n localModifiedFiles.push(remoteFile);\n log(`[EARS-C10] Local file is new (not in gitgov-state): ${remoteFile}`);\n }\n }\n }\n log(`[EARS-C10] Local modified files that overlap with remote: ${localModifiedFiles.length}`);\n } catch (error) {\n log(`[EARS-C10] Warning: Could not check local modifications: ${(error as Error).message}`);\n }\n }\n\n // Step 3: If there's overlap (same file modified locally AND remotely)\n if (localModifiedFiles.length > 0) {\n // [EARS-C11] If force flag is set, continue and overwrite local changes\n if (force) {\n log(`[EARS-C11] Force flag set - will overwrite ${localModifiedFiles.length} local file(s)`);\n logger.warn(`[pullState] Force pull: overwriting local changes to ${localModifiedFiles.length} file(s)`);\n result.forcedOverwrites = localModifiedFiles;\n } else {\n // [EARS-C10] Abort and restore local changes\n log(`[EARS-C10] CONFLICT: Local changes would be overwritten by pull`);\n\n // Return to original branch before aborting\n await this.git.checkoutBranch(savedBranch);\n\n // Restore ALL saved syncable files (user's local changes that would be overwritten)\n for (const [filePath, content] of savedSyncableFiles) {\n const fullPath = path.join(pullRepoRoot, filePath);\n try {\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, \"utf-8\");\n log(`[EARS-C10] Restored syncable file: ${filePath}`);\n } catch {\n // Ignore restore errors\n }\n }\n\n // Also restore LOCAL_ONLY_FILES\n for (const [fileName, content] of savedLocalFiles) {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n try {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n log(`[EARS-C10] Restored local-only file: ${fileName}`);\n } catch {\n // Ignore restore errors\n }\n }\n\n result.success = false;\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"local_changes_conflict\",\n affectedFiles: localModifiedFiles,\n message: `Your local changes to the following files would be overwritten by pull.\\nYou have modified these files locally, and they were also modified remotely.\\nTo avoid losing your changes, push first or use --force to overwrite.`,\n resolutionSteps: [\n \"1. Run 'gitgov sync push' to push your local changes first\",\n \" → This will trigger a rebase and let you resolve conflicts properly\",\n \"2. Or run 'gitgov sync pull --force' to discard your local changes\",\n ],\n };\n result.error = \"Aborting pull: local changes would be overwritten by remote changes\";\n\n logger.warn(`[pullState] Aborting: local changes to ${localModifiedFiles.length} file(s) would be overwritten by pull`);\n return result;\n }\n }\n\n log('[EARS-C10] No conflicting local changes (or force enabled), proceeding with pull...');\n\n // 4. Pull --rebase (EARS-C1, EARS-C2)\n try {\n await this.git.pullRebase(\"origin\", stateBranch);\n } catch (error) {\n // Detect conflict\n const conflictedFiles = await this.git.getConflictedFiles();\n if (conflictedFiles.length > 0) {\n // Pause rebase (DO NOT abort) and return conflict\n await this.git.checkoutBranch(savedBranch);\n\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"rebase_conflict\",\n affectedFiles: conflictedFiles,\n message: \"Conflict detected during pull\",\n resolutionSteps: [\n \"Review conflicted files\",\n \"Manually resolve conflicts\",\n \"Run 'gitgov sync resolve' to complete\",\n ],\n };\n result.error = \"Conflict detected during pull\";\n return result;\n }\n\n // If not a conflict, propagate error\n throw error;\n }\n\n log('Pull rebase successful');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 3: Re-indexing and File Updates (EARS-C3, EARS-C4)\n // ═══════════════════════════════════════════════════════════\n log('Phase 3: Checking for changes and re-indexing...');\n\n // 4. Check if there are new changes (EARS-C3)\n const commitAfter = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1,\n });\n const hashAfter = commitAfter[0]?.hash;\n\n const hasNewChanges = hashBefore !== hashAfter;\n result.hasChanges = hasNewChanges;\n\n // 5. Calculate if reindex is needed (EARS-C3, EARS-C4, EARS-C9)\n // NOTE: Actual reindex happens AFTER file restoration in Phase 4\n // [EARS-C9] Also reindex if index.json doesn't exist (bootstrap scenario)\n const indexPath = path.join(pullRepoRoot, '.gitgov', 'index.json');\n const indexExists = await fs.access(indexPath).then(() => true).catch(() => false);\n const shouldReindex = hasNewChanges || forceReindex || !indexExists;\n if (shouldReindex) {\n result.reindexed = true;\n\n // Calculate number of changed files\n if (hasNewChanges && hashBefore && hashAfter) {\n const changedFiles = await this.git.getChangedFiles(\n hashBefore,\n hashAfter,\n \".gitgov/\"\n );\n result.filesUpdated = changedFiles.length;\n }\n }\n\n // 6. Copy .gitgov/ to filesystem in work branch (EARS-B10 complement)\n // When .gitgov/ is ignored in work branch, we need to manually copy files\n // from gitgov-state to the filesystem so they're available for CLI commands\n const gitgovPath = path.join(pullRepoRoot, \".gitgov\");\n\n // Check if .gitgov/ exists in gitgov-state\n const gitgovExists = await fs.access(gitgovPath).then(() => true).catch(() => false);\n\n if (gitgovExists && hasNewChanges) {\n logger.debug(\"[pullState] Copying .gitgov/ to filesystem for work branch access\");\n // Files will be copied when we return to savedBranch\n // Git will preserve .gitgov/ in the filesystem even though it's ignored\n }\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 4: Restore Working Branch and Cleanup\n // ═══════════════════════════════════════════════════════════\n log('Phase 4: Restoring working branch...');\n\n // 7. Return to original branch\n await this.git.checkoutBranch(savedBranch);\n\n // After returning to work branch, ALWAYS restore .gitgov/ from gitgov-state\n // This is necessary because switching branches may have modified/deleted files\n // even if there are no \"new changes\" from the remote.\n // IMPORTANT: Only checkout SYNC_DIRECTORIES and SYNC_ROOT_FILES, preserving LOCAL_ONLY_FILES\n if (gitgovExists) {\n try {\n logger.debug(\"[pullState] Restoring .gitgov/ to filesystem from gitgov-state (preserving local-only files)\");\n\n // Build list of paths to checkout (SYNC_DIRECTORIES + SYNC_ROOT_FILES)\n // This preserves LOCAL_ONLY_FILES like .session.json, index.json, gitgov binary\n const pathsToCheckout: string[] = [];\n\n // Add sync directories\n for (const dirName of SYNC_DIRECTORIES) {\n pathsToCheckout.push(`.gitgov/${dirName}`);\n }\n\n // Add root-level sync files\n for (const fileName of SYNC_ROOT_FILES) {\n pathsToCheckout.push(`.gitgov/${fileName}`);\n }\n\n // Checkout only syncable paths, one at a time (some may not exist)\n for (const checkoutPath of pathsToCheckout) {\n try {\n await execAsync(`git checkout ${stateBranch} -- \"${checkoutPath}\"`, { cwd: pullRepoRoot });\n logger.debug(`[pullState] Checked out: ${checkoutPath}`);\n } catch {\n // Path might not exist in gitgov-state, that's fine\n logger.debug(`[pullState] Skipped (not in gitgov-state): ${checkoutPath}`);\n }\n }\n\n // Unstage the files (keep them untracked if .gitgov/ is ignored)\n try {\n await execAsync('git reset HEAD .gitgov/', { cwd: pullRepoRoot });\n } catch {\n // Nothing staged, that's fine\n }\n\n // [EARS-C8] Restore saved LOCAL_ONLY_FILES (they may have been lost during checkout)\n for (const [fileName, content] of savedLocalFiles) {\n try {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n await fs.writeFile(filePath, content, \"utf-8\");\n logger.debug(`[EARS-C8] Restored local-only file: ${fileName}`);\n } catch (writeError) {\n logger.warn(`[EARS-C8] Failed to restore ${fileName}: ${(writeError as Error).message}`);\n }\n }\n\n logger.debug(\"[pullState] .gitgov/ restored to filesystem successfully (local-only files preserved)\");\n } catch (error) {\n logger.warn(`[pullState] Failed to restore .gitgov/ to filesystem: ${(error as Error).message}`);\n // Non-critical: user can manually restore with 'git checkout gitgov-state -- .gitgov/'\n }\n }\n\n // [EARS-C3, EARS-C4, EARS-C9] Invoke indexer AFTER file restoration is complete\n // This ensures the index reflects the latest pulled files, not the old saved index.json\n if (shouldReindex) {\n logger.info(\"Invoking IndexerAdapter.generateIndex() after pull...\");\n try {\n await this.indexer.generateIndex();\n logger.info(\"Index regenerated successfully\");\n } catch (error) {\n logger.warn(`Failed to regenerate index: ${(error as Error).message}`);\n // Non-critical: index regeneration failure doesn't fail the pull\n }\n }\n\n result.success = true;\n log(`=== pullState COMPLETED: ${hasNewChanges ? 'new changes pulled' : 'no changes'}, reindexed: ${result.reindexed} ===`);\n return result;\n } catch (error) {\n log(`=== pullState FAILED: ${(error as Error).message} ===`);\n // Re-throw critical errors that should fail fast\n if (error instanceof UncommittedChangesError) {\n throw error;\n }\n\n // For other errors, return result with error message\n result.error = (error as Error).message;\n return result;\n }\n }\n\n /**\n * Resolves state conflicts in a governed manner (Git-Native).\n *\n * Git-Native Flow:\n * 1. User resolves conflicts using standard Git tools (edit files, remove markers)\n * 2. User stages resolved files: git add .gitgov/\n * 3. User runs: gitgov sync resolve --reason \"reason\"\n *\n * This method:\n * - Verifies that a rebase is in progress\n * - Checks that no conflict markers remain in staged files\n * - Updates resolved Records with new checksums and signatures\n * - Continues the git rebase (git rebase --continue)\n * - Creates a signed resolution commit\n * - Regenerates the index\n *\n * [EARS-D1 through EARS-D7]\n */\n async resolveConflict(\n options: SyncStateResolveOptions\n ): Promise<SyncStateResolveResult> {\n const { reason, actorId } = options;\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[resolveConflict] ${msg}`);\n log('=== STARTING resolveConflict (Git-Native) ===');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 0: Pre-flight Checks (EARS-D1, EARS-D2)\n // Git-Native: Only rebase conflicts exist now\n // ═══════════════════════════════════════════════════════════\n log('Phase 0: Verifying rebase in progress...');\n\n // 1. Check if rebase is in progress (EARS-D1)\n const rebaseInProgress = await this.isRebaseInProgress();\n\n if (!rebaseInProgress) {\n throw new NoRebaseInProgressError();\n }\n\n // PRE-CHECK: Verify actorId matches authenticated identity\n // Prevents impersonation — you can only resolve as the actor whose key you hold\n const authenticatedActor = await this.identity.getCurrentActor();\n if (authenticatedActor.id !== actorId) {\n log(`ERROR: Actor identity mismatch: requested '${actorId}' but authenticated as '${authenticatedActor.id}'`);\n throw new ActorIdentityMismatchError(actorId, authenticatedActor.id);\n }\n log(`Pre-check passed: actorId '${actorId}' matches authenticated identity`);\n\n log('Conflict mode: rebase_conflict (Git-Native)');\n\n // 2. Get STAGED files (user already resolved and added them)\n console.log(\"[resolveConflict] Getting staged files...\");\n const allStagedFiles = await this.git.getStagedFiles();\n console.log(\"[resolveConflict] All staged files:\", allStagedFiles);\n\n // Filter to only .gitgov/*.json files (Records)\n let resolvedRecords = allStagedFiles.filter(f =>\n f.startsWith('.gitgov/') && f.endsWith('.json')\n );\n console.log(\"[resolveConflict] Resolved Records (staged .gitgov/*.json):\", resolvedRecords);\n\n // 3. Verify conflict markers (EARS-D2)\n console.log(\"[resolveConflict] Checking for conflict markers...\");\n const filesWithMarkers = await this.checkConflictMarkers(resolvedRecords);\n console.log(\"[resolveConflict] Files with markers:\", filesWithMarkers);\n if (filesWithMarkers.length > 0) {\n throw new ConflictMarkersPresentError(filesWithMarkers);\n }\n\n let rebaseCommitHash = \"\";\n\n // 4. Continue git rebase FIRST (EARS-D4) - Git-Native flow\n // This completes the rebase with user's resolved files\n console.log(\"[resolveConflict] Step 4: Calling git.rebaseContinue()...\");\n await this.git.rebaseContinue();\n console.log(\"[resolveConflict] rebaseContinue completed successfully\");\n\n // Get rebase commit hash\n const currentBranch = await this.git.getCurrentBranch();\n const rebaseCommit = await this.git.getCommitHistory(currentBranch, {\n maxCount: 1,\n });\n rebaseCommitHash = rebaseCommit[0]?.hash ?? \"\";\n\n // 4b. Get resolved files from the rebase commit (since getStagedFiles doesn't work during rebase)\n // The files that were modified in the rebase commit are the ones that had conflicts\n if (resolvedRecords.length === 0 && rebaseCommitHash) {\n console.log(\"[resolveConflict] No staged files detected, getting files from rebase commit...\");\n const repoRoot = await this.git.getRepoRoot();\n try {\n // Get files changed in the rebase commit\n const { stdout } = await execAsync(\n `git diff-tree --no-commit-id --name-only -r ${rebaseCommitHash}`,\n { cwd: repoRoot }\n );\n const commitFiles = stdout.trim().split('\\n').filter(f => f);\n // Filter to .gitgov/*.json files\n resolvedRecords = commitFiles.filter(f =>\n f.startsWith('.gitgov/') && f.endsWith('.json')\n );\n console.log(\"[resolveConflict] Files from rebase commit:\", resolvedRecords);\n } catch (e) {\n console.log(\"[resolveConflict] Could not get files from rebase commit:\", e);\n }\n }\n\n // 5. NOW update resolved Records with new checksums and signatures (EARS-D3)\n // This happens AFTER rebase so we can create a separate signed resolution commit\n console.log(\"[resolveConflict] Updating resolved Records with signatures...\");\n if (resolvedRecords.length > 0) {\n // Get current actor for signing\n const currentActor = await this.identity.getCurrentActor();\n console.log(\"[resolveConflict] Current actor:\", currentActor);\n\n // Process each resolved Record\n console.log(\"[resolveConflict] Processing\", resolvedRecords.length, \"resolved Records\");\n for (const filePath of resolvedRecords) {\n console.log(\"[resolveConflict] Processing Record:\", filePath);\n\n try {\n const repoRoot = await this.git.getRepoRoot();\n const fullPath = join(repoRoot, filePath);\n\n // Read the resolved Record\n const content = readFileSync(fullPath, 'utf-8');\n const record = JSON.parse(content) as EmbeddedMetadataRecord<GitGovRecordPayload>;\n\n // Skip if not a valid EmbeddedMetadataRecord structure\n if (!record.header || !record.payload) {\n continue;\n }\n\n // Re-sign the record (this recalculates checksum AND adds new signature)\n // Pass the reason as notes for the signature\n const signedRecord = await this.identity.signRecord(\n record,\n currentActor.id,\n 'resolver',\n `Conflict resolved: ${reason}`\n );\n\n // Write back the updated Record\n writeFileSync(fullPath, JSON.stringify(signedRecord, null, 2) + '\\n', 'utf-8');\n\n logger.info(`Updated Record: ${filePath} (new checksum + resolver signature)`);\n console.log(\"[resolveConflict] Successfully updated Record:\", filePath);\n } catch (error) {\n // Log but don't fail - some files might not be Records\n logger.debug(`Skipping file ${filePath}: ${(error as Error).message}`);\n console.log(\"[resolveConflict] Error updating Record:\", filePath, error);\n }\n }\n\n console.log(\"[resolveConflict] All Records updated, staging...\");\n }\n\n // 6. Stage updated files with new checksums/signatures\n console.log(\"[resolveConflict] Staging .gitgov/ with updated metadata...\");\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n\n // 7. Create signed resolution commit (EARS-D5)\n const timestamp = new Date().toISOString();\n const resolutionMessage =\n `resolution: conflict resolved by ${actorId}\\n\\n` +\n `Actor: ${actorId}\\n` +\n `Timestamp: ${timestamp}\\n` +\n `Reason: ${reason}\\n` +\n `Files: ${resolvedRecords.length} file(s) resolved\\n\\n` +\n `Signed-off-by: ${actorId}`;\n\n // Create resolution commit (may have signature updates or be empty if no records to sign)\n let resolutionCommitHash = \"\";\n try {\n resolutionCommitHash = await this.git.commit(resolutionMessage);\n } catch (commitError) {\n // If nothing to commit (no records needed re-signing), that's OK\n const stdout = (commitError as any).stdout || '';\n const stderr = (commitError as any).stderr || '';\n\n const isNothingToCommit =\n stdout.includes('nothing to commit') ||\n stderr.includes('nothing to commit') ||\n stdout.includes('nothing added to commit') ||\n stderr.includes('nothing added to commit');\n\n if (isNothingToCommit) {\n log('No additional changes to commit (no records needed re-signing)');\n // Use the rebase commit hash as the resolution hash\n resolutionCommitHash = rebaseCommitHash;\n } else {\n throw commitError;\n }\n }\n\n // 8. Push to remote (best effort - don't fail if no remote)\n log('Pushing resolved state to remote...');\n try {\n await this.git.push(\"origin\", \"gitgov-state\");\n log('Push successful');\n } catch (pushError) {\n // Don't fail resolution just because push failed - local commit is enough\n // This handles: no remote, no network, permission denied, etc.\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n log(`Push failed (non-fatal): ${pushErrorMsg}`);\n }\n\n // 9. Return to original branch and restore .gitgov/ files\n // This is complex because:\n // - In main branch, .gitgov/ is in .gitignore (untracked)\n // - When we checkout from gitgov-state to main, Git doesn't preserve untracked files\n // - We need to: save local-only files, checkout, restore from gitgov-state, restore local-only\n log('Returning to original branch and restoring .gitgov/ files...');\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n // 9a. Save LOCAL_ONLY_FILES and EXCLUDED files to temp BEFORE checkout\n const tempDir = path.join(os.tmpdir(), `gitgov-resolve-${Date.now()}`);\n await fs.mkdir(tempDir, { recursive: true });\n log(`Created temp directory for local files: ${tempDir}`);\n\n // Save LOCAL_ONLY_FILES\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(gitgovDir, fileName);\n const destPath = path.join(tempDir, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Saved LOCAL_ONLY_FILE to temp: ${fileName}`);\n } catch {\n // File doesn't exist, ok\n }\n }\n\n // Save EXCLUDED files (like .key files) recursively\n const saveExcludedFiles = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await fs.mkdir(dstPath, { recursive: true });\n await saveExcludedFiles(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Saved EXCLUDED file to temp: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await saveExcludedFiles(gitgovDir, tempDir);\n\n // 9b. Checkout to original branch\n try {\n await execAsync('git checkout -', { cwd: repoRoot });\n log('Returned to original branch');\n } catch (checkoutError) {\n log(`Warning: Could not return to original branch: ${checkoutError}`);\n }\n\n // 9c. Restore .gitgov/ from gitgov-state branch\n log('Restoring .gitgov/ from gitgov-state...');\n try {\n await this.git.checkoutFilesFromBranch('gitgov-state', ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('Restored .gitgov/ from gitgov-state (unstaged)');\n } catch (checkoutFilesError) {\n log(`Warning: Could not restore .gitgov/ from gitgov-state: ${checkoutFilesError}`);\n }\n\n // 9d. Restore LOCAL_ONLY_FILES from temp\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(tempDir, fileName);\n const destPath = path.join(gitgovDir, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Restored LOCAL_ONLY_FILE from temp: ${fileName}`);\n } catch {\n // File wasn't saved, ok\n }\n }\n\n // 9e. Restore EXCLUDED files from temp\n const restoreExcludedFiles = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcludedFiles(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Restored EXCLUDED file from temp: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcludedFiles(tempDir, gitgovDir);\n\n // 9f. Cleanup temp\n try {\n await fs.rm(tempDir, { recursive: true, force: true });\n log('Temp directory cleaned up');\n } catch {\n // Cleanup failure is not critical\n }\n\n // 10. Re-index after conflict resolution (EARS-D4)\n logger.info(\"Invoking IndexerAdapter.generateIndex() after conflict resolution...\");\n try {\n await this.indexer.generateIndex();\n logger.info(\"Index regenerated successfully after conflict resolution\");\n } catch (error) {\n logger.warn(`Failed to regenerate index after resolution: ${(error as Error).message}`);\n // Non-critical: index regeneration failure doesn't fail the resolution\n }\n\n log(`=== resolveConflict COMPLETED: ${resolvedRecords.length} conflicts resolved ===`);\n\n return {\n success: true,\n rebaseCommitHash,\n resolutionCommitHash,\n conflictsResolved: resolvedRecords.length,\n resolvedBy: actorId,\n reason,\n };\n }\n}\n","export class WatcherStateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WatcherStateError\";\n Object.setPrototypeOf(this, WatcherStateError.prototype);\n }\n}\n\nexport class ProjectNotInitializedError extends WatcherStateError {\n constructor(gitgovPath: string) {\n super(`Directory ${gitgovPath} not found. Run 'gitgov init' first.`);\n this.name = \"ProjectNotInitializedError\";\n Object.setPrototypeOf(this, ProjectNotInitializedError.prototype);\n }\n}\n\nexport class WatcherSetupError extends WatcherStateError {\n constructor(directory: string, cause: Error) {\n super(`Failed to create watcher for ${directory}: ${cause.message}`);\n this.name = \"WatcherSetupError\";\n this.cause = cause;\n Object.setPrototypeOf(this, WatcherSetupError.prototype);\n }\n}\n\nexport class ChecksumMismatchError extends WatcherStateError {\n public expected: string;\n public actual: string;\n\n constructor(filePath: string, expected: string, actual: string) {\n super(\n `Checksum mismatch in ${filePath}: expected ${expected}, got ${actual}`\n );\n this.name = \"ChecksumMismatchError\";\n this.expected = expected;\n this.actual = actual;\n Object.setPrototypeOf(this, ChecksumMismatchError.prototype);\n }\n}\n\n// Type guards\nexport function isWatcherStateError(\n error: unknown\n): error is WatcherStateError {\n return error instanceof WatcherStateError;\n}\n\nexport function isProjectNotInitializedError(\n error: unknown\n): error is ProjectNotInitializedError {\n return error instanceof ProjectNotInitializedError;\n}\n\nexport function isWatcherSetupError(\n error: unknown\n): error is WatcherSetupError {\n return error instanceof WatcherSetupError;\n}\n\nexport function isChecksumMismatchError(\n error: unknown\n): error is ChecksumMismatchError {\n return error instanceof ChecksumMismatchError;\n}\n","/**\n * FsWatcherStateModule — Filesystem watcher for .gitgov/ changes\n *\n * Watches .gitgov/ subdirectories using chokidar and emits events\n * to the EventBus after debounce + checksum validation.\n */\n\nimport chokidar from \"chokidar\";\nimport { readFile } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { basename, dirname, join, relative } from \"path\";\nimport { SYNC_DIRECTORIES } from \"../../sync_state/sync_state.types\";\nimport { calculatePayloadChecksum } from \"../../crypto/checksum\";\nimport { createLogger } from \"../../logger/logger\";\nimport type { IWatcherStateModule } from \"../watcher_state\";\nimport type {\n WatcherStateModuleDependencies,\n WatcherStateStatus,\n} from \"../watcher_state.types\";\nimport type { IEventStream } from \"../../event_bus\";\nimport {\n ProjectNotInitializedError,\n ChecksumMismatchError,\n} from \"../watcher_state.errors\";\n\n// --- Constants ---\n\nconst DEFAULT_DEBOUNCE_MS = 300;\n\nconst EVENT_TYPE_MAP = {\n add: \"watcher.record.added\",\n change: \"watcher.record.changed\",\n unlink: \"watcher.record.deleted\",\n} as const;\n\n// --- Implementation ---\n\nexport class FsWatcherStateModule implements IWatcherStateModule {\n private eventBus: IEventStream;\n private gitgovPath: string;\n private debounceMs: number;\n private logger = createLogger(\"[FsWatcherStateModule] \");\n private watchers: chokidar.FSWatcher[] = [];\n private watchedDirectories: string[] = [];\n private running = false;\n private debounceTimers = new Map<string, NodeJS.Timeout>();\n private checksums = new Map<string, string>();\n private eventsEmitted = 0;\n private lastError?: Error;\n\n constructor(deps: WatcherStateModuleDependencies) {\n this.eventBus = deps.eventBus;\n this.gitgovPath = deps.options.gitgovPath;\n this.debounceMs = deps.options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n }\n\n /**\n * EARS-1: Creates watchers for existing directories in .gitgov/\n * EARS-2: Throws ProjectNotInitializedError if .gitgov/ doesn't exist\n */\n async start(): Promise<void> {\n if (!existsSync(this.gitgovPath)) {\n throw new ProjectNotInitializedError(this.gitgovPath);\n }\n\n for (const dir of SYNC_DIRECTORIES) {\n const dirPath = join(this.gitgovPath, dir);\n if (!existsSync(dirPath)) continue;\n\n const watcher = chokidar.watch(dirPath, {\n ignoreInitial: true,\n depth: 0,\n });\n\n watcher.on(\"add\", (fp) => this.onFileChange(fp, \"add\"));\n watcher.on(\"change\", (fp) => this.onFileChange(fp, \"change\"));\n watcher.on(\"unlink\", (fp) => this.onFileChange(fp, \"unlink\"));\n\n this.watchers.push(watcher);\n this.watchedDirectories.push(dir);\n }\n\n this.running = true;\n }\n\n /** EARS-5: Closes watchers + cancels timers */\n async stop(): Promise<void> {\n for (const timer of this.debounceTimers.values()) {\n clearTimeout(timer);\n }\n this.debounceTimers.clear();\n\n await Promise.all(this.watchers.map((w) => w.close()));\n this.watchers = [];\n this.watchedDirectories = [];\n\n this.running = false;\n }\n\n isRunning(): boolean {\n return this.running;\n }\n\n getStatus(): WatcherStateStatus {\n return {\n isRunning: this.running,\n watchedDirectories: [...this.watchedDirectories],\n eventsEmitted: this.eventsEmitted,\n lastError: this.lastError,\n };\n }\n\n /**\n * EARS-3: Emits event after debounce\n * EARS-6: Debounce — N rapid changes → 1 event\n */\n private onFileChange(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): void {\n const existing = this.debounceTimers.get(filePath);\n if (existing) clearTimeout(existing);\n\n const timer = setTimeout(() => {\n this.debounceTimers.delete(filePath);\n void this.processFileChange(filePath, changeType);\n }, this.debounceMs);\n\n this.debounceTimers.set(filePath, timer);\n }\n\n /**\n * EARS-3: Emit event to EventBus\n * EARS-4: Skip event on checksum mismatch\n * EARS-7: Handle errors gracefully\n */\n private async processFileChange(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): Promise<void> {\n try {\n if (changeType === \"unlink\") {\n this.checksums.delete(filePath);\n this.emitEvent(filePath, changeType);\n return;\n }\n\n const content = await readFile(filePath, \"utf-8\");\n const record = JSON.parse(content);\n\n if (record?.header?.payloadChecksum && record?.payload) {\n const calculated = calculatePayloadChecksum(record.payload);\n if (calculated !== record.header.payloadChecksum) {\n this.lastError = new ChecksumMismatchError(\n filePath,\n record.header.payloadChecksum,\n calculated\n );\n this.logger.error(this.lastError.message);\n return;\n }\n }\n\n const newChecksum = record?.header?.payloadChecksum as\n | string\n | undefined;\n if (newChecksum && newChecksum === this.checksums.get(filePath)) {\n return;\n }\n if (newChecksum) this.checksums.set(filePath, newChecksum);\n\n this.emitEvent(filePath, changeType);\n } catch (error) {\n this.lastError =\n error instanceof Error ? error : new Error(String(error));\n this.logger.error(\n `Error processing ${filePath}: ${this.lastError.message}`\n );\n }\n }\n\n private emitEvent(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): void {\n const recordType = this.extractRecordType(filePath);\n const recordId = this.extractRecordId(filePath);\n const relPath = relative(join(this.gitgovPath, \"..\"), filePath);\n\n this.eventBus.publish({\n type: EVENT_TYPE_MAP[changeType],\n timestamp: Date.now(),\n source: \"watcher\",\n payload: { recordType, recordId, filePath: relPath },\n });\n this.eventsEmitted++;\n }\n\n private extractRecordType(filePath: string): string {\n return basename(dirname(filePath));\n }\n\n private extractRecordId(filePath: string): string {\n return basename(filePath, \".json\");\n }\n}\n","/**\n * Custom Error Classes for AgentRunnerModule\n *\n * These errors provide typed exceptions for better error handling\n * and diagnostics in the agent runner operations.\n */\n\n/**\n * Base error class for all Runner-related errors\n */\nexport class RunnerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RunnerError\";\n Object.setPrototypeOf(this, RunnerError.prototype);\n }\n}\n\n/**\n * Error thrown when an agent file is not found in .gitgov/agents/\n */\nexport class AgentNotFoundError extends RunnerError {\n public readonly agentId: string;\n\n constructor(agentId: string) {\n super(`AgentNotFound: ${agentId}`);\n this.name = \"AgentNotFoundError\";\n this.agentId = agentId;\n Object.setPrototypeOf(this, AgentNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when the specified function is not exported from entrypoint\n */\nexport class FunctionNotExportedError extends RunnerError {\n public readonly functionName: string;\n public readonly entrypoint: string;\n\n constructor(functionName: string, entrypoint: string) {\n super(`FunctionNotExported: ${functionName} not found in ${entrypoint}`);\n this.name = \"FunctionNotExportedError\";\n this.functionName = functionName;\n this.entrypoint = entrypoint;\n Object.setPrototypeOf(this, FunctionNotExportedError.prototype);\n }\n}\n\n/**\n * Error thrown when local engine has neither entrypoint nor runtime\n */\nexport class LocalEngineConfigError extends RunnerError {\n constructor() {\n super(\"LocalEngineConfigError: entrypoint or runtime required for execution\");\n this.name = \"LocalEngineConfigError\";\n Object.setPrototypeOf(this, LocalEngineConfigError.prototype);\n }\n}\n\n/**\n * Error thrown when engine.type is not supported\n */\nexport class UnsupportedEngineTypeError extends RunnerError {\n public readonly engineType: string;\n\n constructor(engineType: string) {\n super(`UnsupportedEngineType: ${engineType}`);\n this.name = \"UnsupportedEngineTypeError\";\n this.engineType = engineType;\n Object.setPrototypeOf(this, UnsupportedEngineTypeError.prototype);\n }\n}\n\n/**\n * Error thrown when engine configuration is invalid\n */\nexport class EngineConfigError extends RunnerError {\n public readonly engineType: string;\n public readonly missingField: string;\n\n constructor(engineType: string, missingField: string) {\n super(`EngineConfigError: ${missingField} required for ${engineType}`);\n this.name = \"EngineConfigError\";\n this.engineType = engineType;\n this.missingField = missingField;\n Object.setPrototypeOf(this, EngineConfigError.prototype);\n }\n}\n\n/**\n * Error thrown when a required dependency is missing\n */\nexport class MissingDependencyError extends RunnerError {\n public readonly dependency: string;\n public readonly reason: string;\n\n constructor(dependency: string, reason: string) {\n super(`MissingDependency: ${dependency} ${reason}`);\n this.name = \"MissingDependencyError\";\n this.dependency = dependency;\n this.reason = reason;\n Object.setPrototypeOf(this, MissingDependencyError.prototype);\n }\n}\n\n/**\n * Error thrown when runtime handler is not found in registry\n */\nexport class RuntimeNotFoundError extends RunnerError {\n public readonly runtime: string;\n\n constructor(runtime: string) {\n super(`RuntimeNotFound: ${runtime}`);\n this.name = \"RuntimeNotFoundError\";\n this.runtime = runtime;\n Object.setPrototypeOf(this, RuntimeNotFoundError.prototype);\n }\n}\n","import path from \"node:path\";\nimport {\n LocalEngineConfigError,\n FunctionNotExportedError,\n RuntimeNotFoundError,\n} from \"../agent_runner.errors\";\nimport type { RuntimeHandlerRegistry } from \"../agent_runner\";\nimport type {\n LocalEngine,\n AgentExecutionContext,\n AgentOutput,\n} from \"../agent_runner.types\";\n\n/**\n * Backend for executing local agents (engine.type: \"local\").\n * Supports entrypoint (dynamic import) and runtime (registered handler).\n * RETURNS AgentOutput captured from the agent function.\n *\n * Note: This is called \"LocalBackend\" because it handles engine.type: \"local\",\n * not because of filesystem usage. The FsAgentRunner loads AgentRecords from\n * filesystem, but this backend executes code locally via dynamic import.\n */\nexport class LocalBackend {\n constructor(\n private projectRoot: string,\n private runtimeRegistry?: RuntimeHandlerRegistry\n ) {}\n\n /**\n * Executes a local agent and captures its output.\n */\n async execute(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-B3] Validate that at least entrypoint or runtime is defined\n if (!engine.entrypoint && !engine.runtime) {\n throw new LocalEngineConfigError();\n }\n\n // [EARS-B2] If runtime defined, use runtime handler\n if (engine.runtime) {\n return this.executeRuntime(engine, ctx);\n }\n\n // [EARS-B1, B4, B5, B6, B7] If entrypoint defined, use dynamic import\n return this.executeEntrypoint(engine, ctx);\n }\n\n /**\n * Executes via entrypoint (dynamic import) and captures output.\n */\n private async executeEntrypoint(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-B1] Resolve absolute path\n const absolutePath = path.join(this.projectRoot, engine.entrypoint!);\n\n // [EARS-B4] Dynamic import\n const mod = await import(absolutePath);\n\n // [EARS-B5] Get function (default: \"runAgent\")\n const fnName = engine.function || \"runAgent\";\n const fn = mod[fnName];\n\n // [EARS-B6] Error if function not exported\n if (typeof fn !== \"function\") {\n throw new FunctionNotExportedError(fnName, engine.entrypoint!);\n }\n\n // [EARS-B7] Invoke with context and capture output\n const result = await fn(ctx);\n\n return this.normalizeOutput(result);\n }\n\n /**\n * Executes via runtime handler.\n */\n private async executeRuntime(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n if (!this.runtimeRegistry) {\n throw new RuntimeNotFoundError(engine.runtime!);\n }\n\n const handler = this.runtimeRegistry.get(engine.runtime!);\n if (!handler) {\n throw new RuntimeNotFoundError(engine.runtime!);\n }\n\n return handler(engine, ctx);\n }\n\n /**\n * Normalizes any result to AgentOutput.\n * If agent returns void/undefined, uses empty object.\n * If returns object with known fields, extracts them.\n */\n private normalizeOutput(result: unknown): AgentOutput {\n if (result === undefined || result === null) {\n return {};\n }\n\n if (typeof result === \"object\") {\n const obj = result as Record<string, unknown>;\n const output: AgentOutput = {};\n\n // Only include data if explicitly returned\n if (obj[\"data\"] !== undefined) {\n output.data = obj[\"data\"];\n }\n\n const message = obj[\"message\"];\n if (typeof message === \"string\") {\n output.message = message;\n }\n\n const artifacts = obj[\"artifacts\"];\n if (Array.isArray(artifacts)) {\n output.artifacts = artifacts;\n }\n\n const metadata = obj[\"metadata\"];\n if (typeof metadata === \"object\" && metadata !== null) {\n output.metadata = metadata as Record<string, unknown>;\n }\n\n return output;\n }\n\n // For primitives, wrap in data\n return { data: result };\n }\n}\n","/**\n * Backend for executing agents via HTTP API (engine.type: \"api\").\n *\n * EARS Coverage:\n * - [EARS-D1] Prepare HTTP request for API engine\n * - [EARS-D2] Read auth token from environment\n * - [EARS-D3] Sign request for actor-signature auth\n * - [EARS-D4] Capture response body as AgentOutput\n * - [EARS-D5] Throw ApiBackendError on non-2xx response\n *\n * Reference: agent_protocol.md §5.1.2\n */\n\nimport type {\n ApiEngine,\n AgentExecutionContext,\n AgentOutput,\n AuthConfig,\n} from \"../agent_runner.types\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\n\n/**\n * Error thrown when API backend request fails.\n * [EARS-D5]\n */\nexport class ApiBackendError extends Error {\n public readonly statusCode: number | undefined;\n public readonly statusText: string | undefined;\n\n constructor(message: string, statusCode?: number, statusText?: string) {\n super(`ApiBackendError: ${message}`);\n this.name = \"ApiBackendError\";\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n}\n\n/**\n * Backend for executing agents via HTTP API.\n *\n * Supports multiple authentication types:\n * - bearer: Bearer token from environment variable\n * - api-key: API key from environment variable\n * - actor-signature: Cryptographic signature using ActorRecord\n *\n * Reference: agent_protocol.md §5.1.2, §5.5, §5.6\n */\nexport class ApiBackend {\n constructor(private identityAdapter?: IIdentityAdapter) {}\n\n /**\n * Executes an agent via API and captures the response.\n *\n * @param engine - API engine configuration\n * @param ctx - Execution context\n * @returns AgentOutput with parsed response body\n *\n * @throws ApiBackendError - When request fails or non-2xx response [EARS-D5]\n */\n async execute(\n engine: ApiEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-D1] Prepare HTTP request\n const method = engine.method ?? \"POST\";\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // [EARS-D2, D3] Apply authentication\n if (engine.auth) {\n await this.applyAuth(headers, engine.auth, ctx);\n }\n\n // Prepare request body with context\n const body = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n input: ctx.input,\n });\n\n try {\n // Execute HTTP request\n const response = await fetch(engine.url, {\n method,\n headers,\n ...(method !== \"GET\" ? { body } : {}),\n });\n\n // [EARS-D5] Error on non-2xx response\n if (!response.ok) {\n throw new ApiBackendError(\n response.statusText || `HTTP ${response.status}`,\n response.status,\n response.statusText\n );\n }\n\n // [EARS-D4] Parse response body as JSON and return as AgentOutput\n const responseBody = await response.json();\n\n return this.normalizeOutput(responseBody);\n } catch (error) {\n // Re-throw ApiBackendError as-is\n if (error instanceof ApiBackendError) {\n throw error;\n }\n\n // Wrap other errors\n throw new ApiBackendError(\n error instanceof Error ? error.message : \"Unknown error\"\n );\n }\n }\n\n /**\n * Apply authentication headers based on auth config.\n * [EARS-D2] Read token from environment\n * [EARS-D3] Sign request for actor-signature\n */\n private async applyAuth(\n headers: Record<string, string>,\n auth: AuthConfig,\n ctx: AgentExecutionContext\n ): Promise<void> {\n switch (auth.type) {\n case \"bearer\": {\n // [EARS-D2] Read token from env var or use direct token\n const token = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n break;\n }\n\n case \"api-key\": {\n // [EARS-D2] Read API key from env var or use direct token\n const apiKey = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (apiKey) {\n headers[\"X-API-Key\"] = apiKey;\n }\n break;\n }\n\n case \"actor-signature\": {\n // [EARS-D3] Sign context using IdentityAdapter\n if (!this.identityAdapter) {\n throw new ApiBackendError(\n \"IdentityAdapter required for actor-signature auth\"\n );\n }\n\n // Create signature payload\n const payload = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n timestamp: Date.now(),\n });\n\n // Sign using actor's private key\n const signature = await this.identityAdapter.signRecord(\n { header: { version: \"1.0\", type: \"request\", payloadChecksum: \"\", signatures: [] }, payload } as any,\n ctx.actorId,\n \"executor\",\n \"API request signature\"\n );\n\n headers[\"X-GitGov-Signature\"] = JSON.stringify(signature);\n headers[\"X-GitGov-Actor\"] = ctx.actorId;\n break;\n }\n\n case \"oauth\":\n // OAuth would require more complex flow (token refresh, etc.)\n // For now, treat similar to bearer\n if (auth.token) {\n headers[\"Authorization\"] = `Bearer ${auth.token}`;\n }\n break;\n\n default:\n // No authentication\n break;\n }\n }\n\n /**\n * Normalize API response to AgentOutput format.\n * Handles various response structures.\n */\n private normalizeOutput(responseBody: unknown): AgentOutput {\n if (responseBody === null || responseBody === undefined) {\n return {};\n }\n\n if (typeof responseBody !== \"object\") {\n return { data: responseBody };\n }\n\n const body = responseBody as Record<string, unknown>;\n\n // If response already has AgentOutput structure, use it\n const output: AgentOutput = {};\n\n if (body[\"data\"] !== undefined) {\n output.data = body[\"data\"];\n } else {\n // If no data field, use entire body as data\n output.data = body;\n }\n\n if (typeof body[\"message\"] === \"string\") {\n output.message = body[\"message\"];\n }\n\n if (Array.isArray(body[\"artifacts\"])) {\n output.artifacts = body[\"artifacts\"];\n }\n\n if (typeof body[\"metadata\"] === \"object\" && body[\"metadata\"] !== null) {\n output.metadata = body[\"metadata\"] as Record<string, unknown>;\n }\n\n return output;\n }\n}\n","/**\n * Backend for executing agents via Model Context Protocol (engine.type: \"mcp\").\n *\n * EARS Coverage:\n * - [EARS-E1] Connect to MCP server at engine.url\n * - [EARS-E2] Invoke tool and capture result as AgentOutput\n * - [EARS-E3] Map tool result to AgentOutput.data\n * - [EARS-E4] Throw McpBackendError on connection/tool failure\n *\n * Reference: agent_protocol.md §5.1.3\n *\n * Note: This implementation uses HTTP transport for MCP. In production,\n * this would integrate with the actual MCP SDK for full protocol support.\n */\n\nimport type {\n McpEngine,\n AgentExecutionContext,\n AgentOutput,\n AuthConfig,\n} from \"../agent_runner.types\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\n\n/**\n * Error thrown when MCP backend operation fails.\n * [EARS-E4]\n */\nexport class McpBackendError extends Error {\n public readonly code: string | undefined;\n\n constructor(message: string, code?: string) {\n super(`McpBackendError: ${message}`);\n this.name = \"McpBackendError\";\n this.code = code;\n }\n}\n\n/**\n * MCP JSON-RPC request structure.\n */\ninterface McpRequest {\n jsonrpc: \"2.0\";\n id: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\n/**\n * MCP JSON-RPC response structure.\n */\ninterface McpResponse {\n jsonrpc: \"2.0\";\n id: string | number;\n result?: unknown;\n error?: {\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\n/**\n * Backend for executing agents via Model Context Protocol.\n *\n * Connects to MCP servers and invokes tools.\n * CAPTURES the tool result and returns it as AgentOutput.\n *\n * Tool resolution priority (per agent_protocol.md §5.1.3):\n * 1. toolOverride (RunOptions.tool) - runtime selection\n * 2. engine.tool - AgentRecord configuration\n * 3. agentId without \"agent:\" prefix - fallback\n *\n * Reference: agent_protocol.md §5.1.3\n */\nexport class McpBackend {\n constructor(private identityAdapter?: IIdentityAdapter) {}\n\n /**\n * Executes an agent via MCP and captures the result.\n *\n * @param engine - MCP engine configuration\n * @param ctx - Execution context\n * @param toolOverride - Optional tool override from RunOptions.tool\n * @returns AgentOutput with tool result\n *\n * @throws McpBackendError - When connection or tool invocation fails [EARS-E4]\n */\n async execute(\n engine: McpEngine,\n ctx: AgentExecutionContext,\n toolOverride?: string\n ): Promise<AgentOutput> {\n // [EARS-E2] Determine tool to invoke (priority order)\n const tool = this.resolveToolName(engine, ctx, toolOverride);\n\n // [EARS-E1] Prepare MCP connection/request\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // Apply authentication if configured\n if (engine.auth) {\n await this.applyAuth(headers, engine.auth, ctx);\n }\n\n // Build MCP JSON-RPC request for tool invocation\n const mcpRequest: McpRequest = {\n jsonrpc: \"2.0\",\n id: ctx.runId,\n method: \"tools/call\",\n params: {\n name: tool,\n arguments: {\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n input: ctx.input,\n },\n },\n };\n\n try {\n // [EARS-E1] Connect to MCP server via HTTP\n const response = await fetch(engine.url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(mcpRequest),\n });\n\n if (!response.ok) {\n // [EARS-E4] Connection failure\n throw new McpBackendError(\n `HTTP ${response.status}: ${response.statusText}`,\n \"CONNECTION_FAILED\"\n );\n }\n\n const mcpResponse: McpResponse = await response.json();\n\n // [EARS-E4] Check for MCP error response\n if (mcpResponse.error) {\n throw new McpBackendError(\n mcpResponse.error.message,\n `MCP_ERROR_${mcpResponse.error.code}`\n );\n }\n\n // [EARS-E3] Map tool result to AgentOutput.data\n return this.mapResultToOutput(mcpResponse.result);\n } catch (error) {\n // Re-throw McpBackendError as-is\n if (error instanceof McpBackendError) {\n throw error;\n }\n\n // [EARS-E4] Wrap other errors\n throw new McpBackendError(\n error instanceof Error ? error.message : \"Unknown error\",\n \"EXECUTION_FAILED\"\n );\n }\n }\n\n /**\n * [EARS-E2] Resolve tool name following priority order:\n * 1. toolOverride (from RunOptions.tool)\n * 2. engine.tool (from AgentRecord)\n * 3. agentId without \"agent:\" prefix\n */\n private resolveToolName(\n engine: McpEngine,\n ctx: AgentExecutionContext,\n toolOverride?: string\n ): string {\n if (toolOverride) {\n return toolOverride;\n }\n\n if (engine.tool) {\n return engine.tool;\n }\n\n // Fallback: use agentId without \"agent:\" prefix\n return ctx.agentId.replace(/^agent:/, \"\");\n }\n\n /**\n * Apply authentication headers based on auth config.\n */\n private async applyAuth(\n headers: Record<string, string>,\n auth: AuthConfig,\n ctx: AgentExecutionContext\n ): Promise<void> {\n switch (auth.type) {\n case \"bearer\": {\n const token = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n break;\n }\n\n case \"api-key\": {\n const apiKey = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (apiKey) {\n headers[\"X-API-Key\"] = apiKey;\n }\n break;\n }\n\n case \"actor-signature\": {\n if (!this.identityAdapter) {\n throw new McpBackendError(\n \"IdentityAdapter required for actor-signature auth\",\n \"AUTH_MISSING_ADAPTER\"\n );\n }\n\n const payload = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n timestamp: Date.now(),\n });\n\n const signature = await this.identityAdapter.signRecord(\n { header: { version: \"1.0\", type: \"request\", payloadChecksum: \"\", signatures: [] }, payload } as any,\n ctx.actorId,\n \"executor\",\n \"MCP request signature\"\n );\n\n headers[\"X-GitGov-Signature\"] = JSON.stringify(signature);\n headers[\"X-GitGov-Actor\"] = ctx.actorId;\n break;\n }\n\n default:\n break;\n }\n }\n\n /**\n * [EARS-E3] Map MCP tool result to AgentOutput.\n */\n private mapResultToOutput(result: unknown): AgentOutput {\n if (result === null || result === undefined) {\n return {};\n }\n\n // If result is already AgentOutput-like, extract fields\n if (typeof result === \"object\") {\n const obj = result as Record<string, unknown>;\n const output: AgentOutput = {\n data: obj[\"data\"] ?? result, // Use data field or entire result\n };\n\n if (typeof obj[\"message\"] === \"string\") {\n output.message = obj[\"message\"];\n }\n\n if (Array.isArray(obj[\"artifacts\"])) {\n output.artifacts = obj[\"artifacts\"];\n }\n\n if (typeof obj[\"metadata\"] === \"object\" && obj[\"metadata\"] !== null) {\n output.metadata = obj[\"metadata\"] as Record<string, unknown>;\n }\n\n // Handle MCP-specific content array format\n if (Array.isArray(obj[\"content\"])) {\n const textContent = obj[\"content\"].find(\n (c: any) => c.type === \"text\"\n );\n if (textContent && typeof textContent.text === \"string\") {\n output.message = textContent.text;\n }\n }\n\n return output;\n }\n\n // Primitive result\n return { data: result };\n }\n}\n","/**\n * Backend for executing agents via custom protocol handlers (engine.type: \"custom\").\n *\n * EARS Coverage:\n * - [EARS-F1] Lookup handler in ProtocolHandlerRegistry\n * - [EARS-F2] Throw CustomEngineConfigError when protocol missing\n * - [EARS-F3] Throw ProtocolHandlerNotFound when handler not registered\n * - [EARS-F4] Invoke handler with engine and context\n *\n * Reference: agent_protocol.md §5.1.4\n */\n\nimport type { ProtocolHandlerRegistry, ProtocolHandler } from \"../agent_runner\";\nimport type {\n CustomEngine,\n AgentExecutionContext,\n AgentOutput,\n} from \"../agent_runner.types\";\n\n/**\n * Error thrown when custom engine configuration is invalid.\n * [EARS-F2]\n */\nexport class CustomEngineConfigError extends Error {\n constructor(message: string) {\n super(`CustomEngineConfigError: ${message}`);\n this.name = \"CustomEngineConfigError\";\n }\n}\n\n/**\n * Error thrown when protocol handler is not found in registry.\n * [EARS-F3]\n */\nexport class ProtocolHandlerNotFoundError extends Error {\n public readonly protocol: string;\n\n constructor(protocol: string) {\n super(`ProtocolHandlerNotFound: ${protocol}`);\n this.name = \"ProtocolHandlerNotFoundError\";\n this.protocol = protocol;\n }\n}\n\n/**\n * Backend for executing agents via custom protocol handlers.\n *\n * Allows extensibility without modifying the runner core.\n * Protocol handlers MUST return AgentOutput.\n *\n * Reference: agent_protocol.md §5.1.4\n */\nexport class CustomBackend {\n constructor(private registry?: ProtocolHandlerRegistry) {}\n\n /**\n * Executes an agent via protocol handler.\n *\n * @param engine - Custom engine configuration\n * @param ctx - Execution context\n * @returns AgentOutput from handler\n *\n * @throws CustomEngineConfigError - When protocol is not defined [EARS-F2]\n * @throws ProtocolHandlerNotFoundError - When handler not registered [EARS-F3]\n */\n async execute(\n engine: CustomEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-F2] Validate protocol is defined\n if (!engine.protocol) {\n throw new CustomEngineConfigError(\"protocol required for execution\");\n }\n\n // [EARS-F1] Lookup handler in registry\n if (!this.registry) {\n throw new ProtocolHandlerNotFoundError(engine.protocol);\n }\n\n const handler = this.registry.get(engine.protocol);\n\n // [EARS-F3] Error if handler not registered\n if (!handler) {\n throw new ProtocolHandlerNotFoundError(engine.protocol);\n }\n\n // [EARS-F4] Invoke handler with engine and context, capture output\n const output = await handler(engine, ctx);\n\n return output;\n }\n}\n\n/**\n * Default implementation of ProtocolHandlerRegistry.\n * In-memory registry for protocol handlers.\n */\nexport class DefaultProtocolHandlerRegistry implements ProtocolHandlerRegistry {\n private handlers = new Map<string, ProtocolHandler>();\n\n register(protocol: string, handler: ProtocolHandler): void {\n this.handlers.set(protocol, handler);\n }\n\n get(protocol: string): ProtocolHandler | undefined {\n return this.handlers.get(protocol);\n }\n}\n","import path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport {\n LocalBackend,\n ApiBackend,\n McpBackend,\n CustomBackend,\n} from \"../backends\";\nimport {\n AgentNotFoundError,\n UnsupportedEngineTypeError,\n EngineConfigError,\n MissingDependencyError,\n} from \"../agent_runner.errors\";\nimport type { AgentRecord } from \"../../record_types\";\nimport type { IEventStream } from \"../../event_bus\";\nimport type { IExecutionAdapter } from \"../../adapters/execution_adapter\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\nimport type {\n IAgentRunner,\n ProtocolHandlerRegistry,\n RuntimeHandlerRegistry,\n} from \"../agent_runner\";\nimport type {\n LocalEngine,\n ApiEngine,\n McpEngine,\n CustomEngine,\n AgentRunnerDependencies,\n AgentExecutionContext,\n AgentOutput,\n AgentResponse,\n AgentRunnerEvent,\n RunOptions,\n} from \"../agent_runner.types\";\n\nconst VALID_ENGINE_TYPES = [\"local\", \"api\", \"mcp\", \"custom\"] as const;\n\n/**\n * Filesystem-based Agent Runner - Executes agents based on their engine.type.\n *\n * Responsibilities:\n * - Load AgentRecords from .gitgov/agents/\n * - Execute via appropriate backend (local, api, mcp, custom)\n * - Capture responses and write ExecutionRecords\n * - Emit events via EventBus\n */\nexport class FsAgentRunner implements IAgentRunner {\n private gitgovPath: string;\n private projectRoot: string;\n private identityAdapter: IIdentityAdapter | undefined;\n private executionAdapter: IExecutionAdapter;\n private eventBus: IEventStream | undefined;\n /** Protocol handlers for CustomBackend */\n public readonly protocolHandlers: ProtocolHandlerRegistry | undefined;\n private runtimeHandlers: RuntimeHandlerRegistry | undefined;\n\n // Engine backends\n private localBackend: LocalBackend;\n private apiBackend: ApiBackend;\n private mcpBackend: McpBackend;\n private customBackend: CustomBackend;\n\n constructor(deps: AgentRunnerDependencies) {\n // [EARS-H4] Validate ExecutionAdapter is provided\n if (!deps.executionAdapter) {\n throw new MissingDependencyError(\"ExecutionAdapter\", \"required\");\n }\n\n this.projectRoot = deps.projectRoot;\n this.gitgovPath = deps.gitgovPath ?? path.join(this.projectRoot, \".gitgov\");\n this.identityAdapter = deps.identityAdapter ?? undefined;\n this.executionAdapter = deps.executionAdapter;\n this.eventBus = deps.eventBus ?? undefined;\n this.protocolHandlers = deps.protocolHandlers ?? undefined;\n this.runtimeHandlers = deps.runtimeHandlers ?? undefined;\n\n // Initialize all engine backends\n this.localBackend = new LocalBackend(this.projectRoot, this.runtimeHandlers);\n this.apiBackend = new ApiBackend(this.identityAdapter);\n this.mcpBackend = new McpBackend(this.identityAdapter);\n this.customBackend = new CustomBackend(this.protocolHandlers);\n }\n\n /**\n * Executes an agent once and returns the response.\n * TaskRecord must exist before calling this method.\n */\n async runOnce(opts: RunOptions): Promise<AgentResponse> {\n const startedAt = new Date().toISOString();\n const runId = randomUUID(); // [EARS-C3]\n let output: AgentOutput | undefined;\n let error: string | undefined;\n let status: \"success\" | \"error\" = \"success\";\n\n // [EARS-A1, A2, A3] Load AgentRecord\n const agent = await this.loadAgent(opts.agentId);\n\n // [EARS-A3] Extract engine from payload\n const engine = agent.engine;\n const engineType = engine.type as string;\n\n // [EARS-G1] Validate engine.type\n if (!VALID_ENGINE_TYPES.includes(engineType as typeof VALID_ENGINE_TYPES[number])) {\n throw new UnsupportedEngineTypeError(engineType);\n }\n\n // [EARS-G2] Validate url for api/mcp\n if ((engineType === \"api\" || engineType === \"mcp\") && !(\"url\" in engine)) {\n throw new EngineConfigError(engineType, \"url\");\n }\n\n // [EARS-G3] Validate IdentityAdapter for actor-signature auth\n if (engineType === \"api\" || engineType === \"mcp\") {\n const engineWithAuth = engine as { auth?: { type?: string } };\n if (\n engineWithAuth.auth?.type === \"actor-signature\" &&\n !this.identityAdapter\n ) {\n throw new MissingDependencyError(\n \"IdentityAdapter\",\n \"required for actor-signature auth\"\n );\n }\n }\n\n // [EARS-C1, C2] Build context\n const ctx: AgentExecutionContext = {\n agentId: opts.agentId,\n actorId: opts.actorId ?? opts.agentId, // [EARS-C2]\n taskId: opts.taskId,\n runId,\n input: opts.input,\n };\n\n // [EARS-I1] Emit agent:started event\n this.emitEvent({\n type: \"agent:started\",\n payload: { runId, agentId: opts.agentId, taskId: opts.taskId, startedAt },\n });\n\n try {\n // Execute via appropriate backend and CAPTURE output\n switch (engineType) {\n case \"local\":\n output = await this.localBackend.execute(engine as LocalEngine, ctx);\n break;\n case \"api\":\n output = await this.apiBackend.execute(engine as ApiEngine, ctx);\n break;\n case \"mcp\":\n output = await this.mcpBackend.execute(\n engine as McpEngine,\n ctx,\n opts.tool // Pass tool override from RunOptions\n );\n break;\n case \"custom\":\n output = await this.customBackend.execute(engine as CustomEngine, ctx);\n break;\n }\n } catch (err) {\n status = \"error\";\n error = (err as Error).message;\n }\n\n const completedAt = new Date().toISOString();\n const durationMs =\n new Date(completedAt).getTime() - new Date(startedAt).getTime();\n\n // [EARS-H1, H2] Write ExecutionRecord\n // Build result message (min 10 chars required by schema)\n const resultMessage = status === \"success\"\n ? output?.message || `Agent ${opts.agentId} completed successfully`\n : `Agent ${opts.agentId} failed: ${error || 'Unknown error'}`;\n\n const executionRecord = await this.executionAdapter.create(\n {\n taskId: opts.taskId,\n type: status === \"success\" ? \"completion\" : \"blocker\",\n title: `Agent execution: ${opts.agentId}`,\n result: resultMessage.length >= 10 ? resultMessage : resultMessage.padEnd(10, '.'),\n metadata: {\n agentId: opts.agentId,\n runId,\n status,\n output: status === \"success\" ? output : undefined,\n error: status === \"error\" ? error : undefined,\n startedAt,\n completedAt,\n durationMs,\n },\n },\n ctx.actorId\n );\n\n // [EARS-H3] executionRecordId in response\n const executionRecordId = executionRecord.id;\n\n // [EARS-I2, I3] Emit completion event\n if (status === \"success\") {\n this.emitEvent({\n type: \"agent:completed\",\n payload: {\n runId,\n agentId: opts.agentId,\n taskId: opts.taskId,\n status,\n durationMs,\n executionRecordId,\n },\n });\n } else {\n this.emitEvent({\n type: \"agent:error\",\n payload: {\n runId,\n agentId: opts.agentId,\n taskId: opts.taskId,\n status,\n error: error!,\n durationMs,\n executionRecordId,\n },\n });\n }\n\n // [EARS-J1, J2, J3] Return AgentResponse\n const response: AgentResponse = {\n runId,\n agentId: opts.agentId,\n status,\n executionRecordId,\n startedAt,\n completedAt,\n durationMs,\n };\n\n // [EARS-J2] Include output only on success\n if (status === \"success\" && output) {\n response.output = output;\n }\n\n // [EARS-J3] Include error only on failure\n if (status === \"error\" && error) {\n response.error = error;\n }\n\n return response;\n }\n\n /**\n * [EARS-A1, A2] Loads AgentRecord from .gitgov/agents/agent-{id}.json\n */\n private async loadAgent(agentId: string): Promise<AgentRecord> {\n // Remove \"agent:\" prefix if present\n const id = agentId.startsWith(\"agent:\") ? agentId.slice(6) : agentId;\n const agentPath = path.join(this.gitgovPath, \"agents\", `agent-${id}.json`);\n\n try {\n const content = await fs.readFile(agentPath, \"utf-8\");\n const record = JSON.parse(content);\n // Return payload if wrapped in GitGovRecord structure\n return record.payload ?? record;\n } catch {\n throw new AgentNotFoundError(agentId);\n }\n }\n\n /**\n * [EARS-I4] Emits event via EventBus if available.\n * Works silently without EventBus.\n */\n private emitEvent(event: AgentRunnerEvent): void {\n if (this.eventBus) {\n this.eventBus.publish({\n type: event.type,\n timestamp: Date.now(),\n source: \"agent_runner_module\",\n payload: event.payload,\n });\n }\n }\n}\n\n/**\n * [EARS-K1] Factory function for FsAgentRunner.\n *\n * Creates a filesystem-based agent runner with injected dependencies.\n * Recommended for dependency injection scenarios.\n */\nexport function createFsAgentRunner(deps: AgentRunnerDependencies): IAgentRunner {\n return new FsAgentRunner(deps);\n}\n","/**\n * Filesystem AgentRunner implementation\n *\n * This module provides the filesystem-based implementation of IAgentRunner:\n * - FsAgentRunner: Loads AgentRecords from .gitgov/agents/\n * - createAgentRunner(): Factory function for DI\n *\n * Note: LocalBackend is re-exported from backends/ for convenience.\n * Use @gitgov/core for direct backend imports.\n */\nexport { FsAgentRunner } from './fs_agent_runner';\nexport { LocalBackend } from '../backends';\nexport type { AgentRunnerDependencies as FsAgentRunnerDependencies } from '../agent_runner.types';\n\nimport type { IAgentRunner } from '../agent_runner';\nimport type { AgentRunnerDependencies } from '../agent_runner.types';\nimport { FsAgentRunner } from './fs_agent_runner';\n\n/**\n * Factory function to create a filesystem-based AgentRunner.\n */\nexport function createAgentRunner(deps: AgentRunnerDependencies): IAgentRunner {\n return new FsAgentRunner(deps);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/record_store/record_store.ts","../../src/record_store/fs/fs_record_store.ts","../../src/config_manager/config_manager.ts","../../src/config_store/fs/fs_config_store.ts","../../src/session_manager/session_manager.ts","../../src/session_store/fs/fs_session_store.ts","../../src/key_provider/key_provider.ts","../../src/key_provider/fs/fs_key_provider.ts","../../src/file_lister/file_lister.errors.ts","../../src/file_lister/fs/fs_file_lister.ts","../../src/record_types/type_guards.ts","../../src/utils/id_parser.ts","../../src/utils/array_utils.ts","../../src/logger/logger.ts","../../src/crypto/checksum.ts","../../src/record_types/common.types.ts","../../src/record_schemas/errors.ts","../../src/record_schemas/generated/actor_record_schema.json","../../src/record_schemas/generated/agent_record_schema.json","../../src/record_schemas/generated/changelog_record_schema.json","../../src/record_schemas/generated/cycle_record_schema.json","../../src/record_schemas/generated/embedded_metadata_schema.json","../../src/record_schemas/generated/execution_record_schema.json","../../src/record_schemas/generated/feedback_record_schema.json","../../src/record_schemas/generated/task_record_schema.json","../../src/record_schemas/generated/workflow_record_schema.json","../../src/record_schemas/generated/index.ts","../../src/record_schemas/schema_cache.ts","../../src/crypto/signatures.ts","../../src/record_validations/embedded_metadata_validator.ts","../../src/record_validations/actor_validator.ts","../../src/record_factories/actor_factory.ts","../../src/record_validations/agent_validator.ts","../../src/record_factories/agent_factory.ts","../../src/record_validations/task_validator.ts","../../src/record_factories/task_factory.ts","../../src/record_validations/cycle_validator.ts","../../src/record_factories/cycle_factory.ts","../../src/record_validations/execution_validator.ts","../../src/record_factories/execution_factory.ts","../../src/record_validations/changelog_validator.ts","../../src/record_factories/changelog_factory.ts","../../src/record_validations/feedback_validator.ts","../../src/record_factories/feedback_factory.ts","../../src/lint/fs/fs_lint.ts","../../src/utils/esm_helper.ts","../../src/project_initializer/fs/fs_project_initializer.ts","../../src/git/errors.ts","../../src/git/local/local_git_module.ts","../../src/utils/project_discovery.ts","../../src/sync_state/sync_state.errors.ts","../../src/sync_state/sync_state.types.ts","../../src/sync_state/fs/fs_sync_state.ts","../../src/watcher_state/watcher_state.errors.ts","../../src/watcher_state/fs/fs_watcher_state.ts","../../src/agent_runner/agent_runner.errors.ts","../../src/agent_runner/backends/local_backend.ts","../../src/agent_runner/backends/api_backend.ts","../../src/agent_runner/backends/mcp_backend.ts","../../src/agent_runner/backends/custom_backend.ts","../../src/agent_runner/fs/fs_agent_runner.ts","../../src/agent_runner/fs/index.ts"],"names":["path","path2","fs","path3","fs4","path4","path5","fs5","logger","readdir","join","dirname","path6","require","path7","path8","existsSync","promisify","stat","readFileSync","verifySignatures","repoRoot","gitgovPath","gitgovExists","ChecksumMismatchError","readFile","basename"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBO,IAAM,kBAAA,GAAgC;AAAA,EAC3C,QAAQ,CAAC,EAAA,KAAe,EAAA,CAAG,OAAA,CAAQ,MAAM,GAAG,CAAA;AAAA,EAC5C,QAAQ,CAAC,OAAA,KAAoB,OAAA,CAAQ,OAAA,CAAQ,MAAM,GAAG;AACxD;;;ACmBA,IAAM,kBAAA,GAAiC;AAAA,EACrC,WAAW,CAAC,KAAA,KAAU,KAAK,SAAA,CAAU,KAAA,EAAO,MAAM,CAAC,CAAA;AAAA,EACnD,KAAA,EAAO,CAAC,IAAA,KAAS,IAAA,CAAK,MAAM,IAAI;AAClC,CAAA;AAOA,SAAS,WAAW,EAAA,EAAkB;AACpC,EAAA,IAAI,CAAC,EAAA,IAAM,OAAO,EAAA,KAAO,QAAA,EAAU;AACjC,IAAA,MAAM,IAAI,MAAM,+BAA+B,CAAA;AAAA,EACjD;AACA,EAAA,IAAI,GAAG,QAAA,CAAS,IAAI,KAAK,QAAA,CAAS,IAAA,CAAK,EAAE,CAAA,EAAG;AAC1C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgB,EAAE,CAAA,kCAAA,CAAoC,CAAA;AAAA,EACxE;AACF;AAeO,IAAM,gBAAN,MAAiD;AAAA,EACrC,QAAA;AAAA,EACA,SAAA;AAAA,EACA,UAAA;AAAA,EACA,eAAA;AAAA,EACA,SAAA;AAAA,EAEjB,YAAY,OAAA,EAA+B;AACzC,IAAA,IAAA,CAA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O,SAAS,kBAAkB,IAAA,EAA6C;AAC7E,EAAA,OAAO,IAAI,cAAc,IAAI,CAAA;AAC/B","file":"fs.js","sourcesContent":["/**\n * IdEncoder for transforming IDs to storage-safe filenames.\n * Useful for characters not allowed in filesystem (e.g., `:` on Windows)\n * or URL-unsafe characters in remote backends.\n */\nexport interface IdEncoder {\n /** Transform ID to storage-safe string */\n encode: (id: string) => string;\n /** Recover original ID from encoded string */\n decode: (encoded: string) => string;\n}\n\n/**\n * Default encoder: `:` → `_` (for IDs like \"human:camilo\")\n * Reversible because IDs cannot contain `_` (see id_generator.ts)\n */\nexport const DEFAULT_ID_ENCODER: IdEncoder = {\n encode: (id: string) => id.replace(/:/g, '_'),\n decode: (encoded: string) => encoded.replace(/_/g, ':'),\n};\n\n/**\n * RecordStore<V, R, O> - Generic interface for record persistence\n *\n * Abstracts CRUD operations without assuming storage backend.\n * Each implementation decides how to persist (fs, memory, db, remote).\n *\n * @typeParam V - Value type (the record being stored)\n * @typeParam R - Return type for write operations (default: void for local, GitHubWriteResult for GitHub)\n * @typeParam O - Options type for write operations (default: void for local, GitHubWriteOpts for GitHub)\n */\nexport interface RecordStore<V, R = void, O = void> {\n /**\n * Gets a record by ID\n * @returns The record or null if it doesn't exist\n */\n get(id: string): Promise<V | null>;\n\n /**\n * Persists a record\n * @param id - Unique identifier\n * @param value - The record to persist\n */\n put(id: string, value: V, ...opts: O extends void ? [] : [opts?: O]): Promise<R>;\n\n /**\n * Persists multiple records in a single operation.\n * Local backends iterate sequentially; GitHub backend uses atomic commits.\n */\n putMany(entries: Array<{ id: string; value: V }>, ...opts: O extends void ? [] : [opts?: O]): Promise<R>;\n\n /**\n * Deletes a record\n * @param id - Identifier of the record to delete\n */\n delete(id: string, ...opts: O extends void ? [] : [opts?: O]): Promise<R>;\n\n /**\n * Lists all record IDs\n * @returns Array of IDs\n */\n list(): Promise<string[]>;\n\n /**\n * Checks if a record exists\n * @param id - Identifier to check\n */\n exists(id: string): Promise<boolean>;\n}\n","import * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { RecordStore } from '../record_store';\nimport { DEFAULT_ID_ENCODER } from '../record_store';\nimport type { IdEncoder } from '../record_store';\n\n// Re-export for backward compatibility\nexport { DEFAULT_ID_ENCODER };\nexport type { IdEncoder };\n\n/**\n * Serializer for FsRecordStore - allows custom serialization\n */\nexport interface Serializer {\n stringify: (value: unknown) => string;\n parse: <T>(text: string) => T;\n}\n\n/**\n * Options for FsRecordStore\n */\nexport interface FsRecordStoreOptions {\n /** Base directory for files */\n basePath: string;\n\n /** File extension (default: \".json\") */\n extension?: string;\n\n /** Custom serializer (default: JSON with indent 2) */\n serializer?: Serializer;\n\n /** Create directory if it doesn't exist (default: true) */\n createIfMissing?: boolean;\n\n /** ID encoder for filesystem-safe filenames (default: undefined = no encoding) */\n idEncoder?: IdEncoder;\n}\n\nconst DEFAULT_SERIALIZER: Serializer = {\n stringify: (value) => JSON.stringify(value, null, 2),\n parse: (text) => JSON.parse(text),\n};\n\n/**\n * Validates that an ID does not contain path traversal.\n * Blocks: `..`, `/`, `\\`\n * Allows: single `.` (e.g., \"human.camilo\")\n */\nfunction validateId(id: string): void {\n if (!id || typeof id !== 'string') {\n throw new Error('ID must be a non-empty string');\n }\n if (id.includes('..') || /[\\/\\\\]/.test(id)) {\n throw new Error(`Invalid ID: \"${id}\". IDs cannot contain /, \\\\, or ..`);\n }\n}\n\n/**\n * FsRecordStore<T> - Filesystem implementation of Store<T>\n *\n * Persists records as JSON files on disk.\n *\n * @example\n * const store = new FsRecordStore<TaskRecord>({\n * basePath: '.gitgov/tasks',\n * });\n *\n * await store.put('123-task-foo', task);\n * const task = await store.get('123-task-foo');\n */\nexport class FsRecordStore<T> implements RecordStore<T> {\n private readonly basePath: string;\n private readonly extension: string;\n private readonly serializer: Serializer;\n private readonly createIfMissing: boolean;\n private readonly idEncoder: IdEncoder | undefined;\n\n constructor(options: FsRecordStoreOptions) {\n this.basePath = options.basePath;\n this.extension = options.extension ?? '.json';\n this.serializer = options.serializer ?? DEFAULT_SERIALIZER;\n this.createIfMissing = options.createIfMissing ?? true;\n this.idEncoder = options.idEncoder;\n }\n\n private getFilePath(id: string): string {\n validateId(id);\n const fileId = this.idEncoder ? this.idEncoder.encode(id) : id;\n return path.join(this.basePath, `${fileId}${this.extension}`);\n }\n\n async get(id: string): Promise<T | null> {\n const filePath = this.getFilePath(id);\n try {\n const content = await fs.readFile(filePath, 'utf-8');\n return this.serializer.parse<T>(content);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null;\n }\n throw error;\n }\n }\n\n async put(id: string, value: T): Promise<void> {\n const filePath = this.getFilePath(id);\n if (this.createIfMissing) {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n }\n const content = this.serializer.stringify(value);\n await fs.writeFile(filePath, content, 'utf-8');\n }\n\n async putMany(entries: Array<{ id: string; value: T }>): Promise<void> {\n for (const { id, value } of entries) {\n await this.put(id, value);\n }\n }\n\n async delete(id: string): Promise<void> {\n const filePath = this.getFilePath(id);\n try {\n await fs.unlink(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n async list(): Promise<string[]> {\n try {\n const files = await fs.readdir(this.basePath);\n const ids = files\n .filter((f) => f.endsWith(this.extension))\n .map((f) => f.slice(0, -this.extension.length));\n return this.idEncoder ? ids.map((id) => this.idEncoder!.decode(id)) : ids;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n }\n\n async exists(id: string): Promise<boolean> {\n const filePath = this.getFilePath(id);\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n }\n}\n","/**\n * ConfigManager - Project Configuration Manager\n *\n * Provides typed access to GitGovernance project configuration (config.json).\n * Configuration is versioned in Git and shared between collaborators.\n *\n * Uses ConfigStore abstraction for backend-agnostic persistence.\n *\n * NOTE: Session state (.session.json) is handled by SessionManager, not ConfigManager.\n */\n\nimport type { ConfigStore } from '../config_store/config_store';\nimport type {\n IConfigManager,\n GitGovConfig,\n AuditState,\n SyncConfig,\n SyncDefaults,\n AuditStateUpdate\n} from './config_manager.types';\n\n/**\n * Configuration Manager Class\n *\n * Provides typed access to GitGovernance project configuration.\n * Uses ConfigStore abstraction for backend-agnostic persistence.\n *\n * @example\n * ```typescript\n * // Production usage\n * import { FsConfigStore } from '@gitgov/core/fs';\n * const configStore = new FsConfigStore('/path/to/project');\n * const configManager = new ConfigManager(configStore);\n *\n * // Test usage\n * import { MemoryConfigStore } from '@gitgov/core/memory';\n * const configStore = new MemoryConfigStore();\n * configStore.setConfig({ ... });\n * const configManager = new ConfigManager(configStore);\n * ```\n */\nexport class ConfigManager implements IConfigManager {\n private readonly configStore: ConfigStore;\n\n constructor(configStore: ConfigStore) {\n this.configStore = configStore;\n }\n\n /**\n * Load GitGovernance configuration\n */\n async loadConfig(): Promise<GitGovConfig | null> {\n return this.configStore.loadConfig();\n }\n\n /**\n * Get root cycle from configuration\n */\n async getRootCycle(): Promise<string | null> {\n const config = await this.loadConfig();\n return config?.rootCycle || null;\n }\n\n /**\n * Get project information from configuration\n */\n async getProjectInfo(): Promise<{ id: string; name: string } | null> {\n const config = await this.loadConfig();\n if (!config) return null;\n\n return {\n id: config.projectId,\n name: config.projectName\n };\n }\n\n /**\n * Get sync configuration from config.json\n * Returns sync strategy and related settings with defaults\n */\n async getSyncConfig(): Promise<SyncConfig | null> {\n const config = await this.loadConfig();\n if (!config?.state?.sync) return null;\n\n return {\n strategy: config.state.sync.strategy || \"manual\",\n maxRetries: config.state.sync.maxRetries || 3,\n pushIntervalSeconds: config.state.sync.pushIntervalSeconds || 30,\n batchIntervalSeconds: config.state.sync.batchIntervalSeconds || 60\n };\n }\n\n /**\n * Get sync defaults from config.json\n * Returns recommended defaults for pullScheduler and fileWatcher\n */\n async getSyncDefaults(): Promise<SyncDefaults> {\n const config = await this.loadConfig();\n\n return {\n pullScheduler: {\n defaultIntervalSeconds: config?.state?.defaults?.pullScheduler?.defaultIntervalSeconds || 30,\n defaultEnabled: config?.state?.defaults?.pullScheduler?.defaultEnabled || false,\n defaultContinueOnNetworkError: config?.state?.defaults?.pullScheduler?.defaultContinueOnNetworkError ?? true,\n defaultStopOnConflict: config?.state?.defaults?.pullScheduler?.defaultStopOnConflict || false\n },\n fileWatcher: {\n defaultDebounceMs: config?.state?.defaults?.fileWatcher?.defaultDebounceMs || 300,\n defaultIgnoredPatterns: config?.state?.defaults?.fileWatcher?.defaultIgnoredPatterns || [\"*.tmp\", \".DS_Store\", \"*.swp\"]\n }\n };\n }\n\n /**\n * Get audit state from config.json\n * Returns last full audit commit and timestamp for incremental mode\n */\n async getAuditState(): Promise<AuditState> {\n const config = await this.loadConfig();\n return {\n lastFullAuditCommit: config?.state?.audit?.lastFullAuditCommit || null,\n lastFullAuditTimestamp: config?.state?.audit?.lastFullAuditTimestamp || null,\n lastFullAuditFindingsCount: config?.state?.audit?.lastFullAuditFindingsCount ?? null\n };\n }\n\n /**\n * Update audit state in config.json after a full audit\n * This is used to enable incremental audits\n */\n async updateAuditState(auditState: AuditStateUpdate): Promise<void> {\n const config = await this.loadConfig();\n if (!config) {\n throw new Error('Cannot update audit state: config.json not found');\n }\n\n if (!config.state) {\n config.state = {};\n }\n\n config.state.audit = {\n lastFullAuditCommit: auditState.lastFullAuditCommit,\n lastFullAuditTimestamp: auditState.lastFullAuditTimestamp,\n lastFullAuditFindingsCount: auditState.lastFullAuditFindingsCount\n };\n\n await this.configStore.saveConfig(config);\n }\n\n /**\n * Get state branch name from configuration\n */\n async getStateBranch(): Promise<string> {\n const config = await this.loadConfig();\n return config?.state?.branch || 'gitgov-state';\n }\n}\n","/**\n * FsConfigStore - Filesystem implementation of ConfigStore\n *\n * Handles persistence of config.json to the local filesystem.\n *\n * NOTE: Session state (.session.json) is handled by FsSessionStore.\n * NOTE: Project discovery utilities are in src/utils/project_discovery.ts\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { ConfigStore } from '../config_store';\nimport type { GitGovConfig } from '../../config_manager/config_manager.types';\nimport { ConfigManager } from '../../config_manager/config_manager';\n\n/**\n * Filesystem-based ConfigStore implementation.\n *\n * Stores configuration in .gitgov/config.json.\n * Implements fail-safe pattern: returns null instead of throwing for missing files.\n *\n * @example\n * ```typescript\n * const store = new FsConfigStore('/path/to/project');\n * const config = await store.loadConfig();\n * if (config) {\n * console.log(config.projectName);\n * }\n * ```\n */\nexport class FsConfigStore implements ConfigStore {\n private readonly configPath: string;\n\n constructor(projectRootPath: string) {\n this.configPath = path.join(projectRootPath, '.gitgov', 'config.json');\n }\n\n /**\n * Load project configuration from .gitgov/config.json\n *\n * [EARS-A1] Returns complete GitGovConfig for valid files\n * [EARS-A2] Returns null for non-existent files (fail-safe)\n * [EARS-A3] Returns null for invalid JSON (graceful degradation)\n */\n async loadConfig(): Promise<GitGovConfig | null> {\n try {\n const configContent = await fs.readFile(this.configPath, 'utf-8');\n const config = JSON.parse(configContent) as GitGovConfig;\n\n // [EARS-A5] Warn if rootCycle doesn't match expected format\n if (config.rootCycle && !/^\\d+-cycle-[a-z0-9-]+$/.test(config.rootCycle)) {\n console.warn(\n `Warning: rootCycle \"${config.rootCycle}\" doesn't match expected format ` +\n `\"{timestamp}-cycle-{slug}\". This may cause issues with cycle navigation.`\n );\n }\n\n return config;\n } catch (error) {\n // Config file doesn't exist or is invalid - fail-safe behavior\n return null;\n }\n }\n\n /**\n * Save project configuration to .gitgov/config.json\n *\n * [EARS-A4] Writes config with JSON indentation\n */\n async saveConfig(config: GitGovConfig): Promise<void> {\n await fs.writeFile(this.configPath, JSON.stringify(config, null, 2), 'utf-8');\n }\n}\n\n/**\n * Create a ConfigManager instance for a project.\n *\n * [EARS-B1] Factory function that creates a ConfigManager with FsConfigStore backend.\n * Use this when you already have the projectRoot (e.g., from DI container).\n *\n * @param projectRoot - Absolute path to project root (REQUIRED)\n * @returns ConfigManager instance with FsConfigStore backend\n */\nexport function createConfigManager(projectRoot: string): ConfigManager {\n const configStore = new FsConfigStore(projectRoot);\n return new ConfigManager(configStore);\n}\n","/**\n * SessionManager - Local Session State Manager\n *\n * Provides typed access to GitGovernance session state (.session.json).\n * Session state is ephemeral, machine-local, and NOT versioned in Git.\n *\n * Uses SessionStore abstraction for backend-agnostic persistence.\n */\n\nimport type { SessionStore } from '../session_store/session_store';\nimport type {\n ISessionManager,\n GitGovSession,\n ActorState,\n SyncPreferencesUpdate\n} from './session_manager.types';\n\n/**\n * Session Manager Class\n *\n * Provides typed access to GitGovernance session state.\n * Uses SessionStore abstraction for backend-agnostic persistence.\n *\n * @example\n * ```typescript\n * // Production usage\n * import { FsSessionStore } from '@gitgov/core/fs';\n * const sessionStore = new FsSessionStore('/path/to/project');\n * const sessionManager = new SessionManager(sessionStore);\n *\n * // Test usage\n * import { MemorySessionStore } from '@gitgov/core/memory';\n * const sessionStore = new MemorySessionStore();\n * sessionStore.setSession({ ... });\n * const sessionManager = new SessionManager(sessionStore);\n * ```\n */\nexport class SessionManager implements ISessionManager {\n private readonly sessionStore: SessionStore;\n\n constructor(sessionStore: SessionStore) {\n this.sessionStore = sessionStore;\n }\n\n /**\n * Load GitGovernance session state\n * [EARS-E1] Auto-detects actor from .key files if no session or no actorId exists\n */\n async loadSession(): Promise<GitGovSession | null> {\n let session = await this.sessionStore.loadSession();\n\n // [EARS-E1] If session exists but no lastSession.actorId, try to auto-detect\n if (session && !session.lastSession?.actorId) {\n const detectedActorId = await this.detectActorFromKeyFiles();\n if (detectedActorId) {\n session.lastSession = {\n actorId: detectedActorId,\n timestamp: new Date().toISOString()\n };\n await this.sessionStore.saveSession(session);\n }\n }\n\n // [EARS-E1] If no session, try to create from .key files\n if (!session) {\n const detectedActorId = await this.detectActorFromKeyFiles();\n if (detectedActorId) {\n const newSession: GitGovSession = {\n lastSession: {\n actorId: detectedActorId,\n timestamp: new Date().toISOString()\n },\n actorState: {}\n };\n try {\n await this.sessionStore.saveSession(newSession);\n return newSession;\n } catch {\n return newSession;\n }\n }\n }\n\n return session;\n }\n\n /**\n * [EARS-E1] Detect actor from .key files in .gitgov/actors/\n */\n async detectActorFromKeyFiles(): Promise<string | null> {\n if (this.sessionStore.detectActorFromKeyFiles) {\n return this.sessionStore.detectActorFromKeyFiles();\n }\n return null;\n }\n\n /**\n * Get actor state for a specific actor\n */\n async getActorState(actorId: string): Promise<ActorState | null> {\n const session = await this.loadSession();\n return session?.actorState?.[actorId] || null;\n }\n\n /**\n * Update actor state for a specific actor\n */\n async updateActorState(actorId: string, state: Partial<ActorState>): Promise<void> {\n const session = await this.loadSession() || {};\n if (!session.actorState) session.actorState = {};\n\n session.actorState[actorId] = {\n ...session.actorState[actorId],\n ...state,\n lastSync: new Date().toISOString()\n };\n\n // Update lastSession if the actor is a human (not an agent)\n if (actorId.startsWith('human:')) {\n session.lastSession = {\n actorId,\n timestamp: new Date().toISOString()\n };\n }\n\n await this.sessionStore.saveSession(session);\n }\n\n /**\n * Get cloud session token\n */\n async getCloudSessionToken(): Promise<string | null> {\n const session = await this.loadSession();\n return session?.cloud?.sessionToken || null;\n }\n\n /**\n * Get sync preferences from session\n */\n async getSyncPreferences(): Promise<GitGovSession['syncPreferences'] | null> {\n const session = await this.loadSession();\n return session?.syncPreferences || null;\n }\n\n /**\n * Update sync preferences in .session.json\n * These are local machine preferences that override project defaults\n */\n async updateSyncPreferences(preferences: SyncPreferencesUpdate): Promise<void> {\n const session = await this.loadSession() || {};\n\n if (!session.syncPreferences) {\n session.syncPreferences = {};\n }\n\n if (preferences.pullScheduler) {\n session.syncPreferences.pullScheduler = {\n ...session.syncPreferences.pullScheduler,\n ...preferences.pullScheduler\n };\n }\n\n if (preferences.fileWatcher) {\n session.syncPreferences.fileWatcher = {\n ...session.syncPreferences.fileWatcher,\n ...preferences.fileWatcher\n };\n }\n\n await this.sessionStore.saveSession(session);\n }\n\n /**\n * Get last session info (last human who interacted)\n */\n async getLastSession(): Promise<{ actorId: string; timestamp: string } | null> {\n const session = await this.loadSession();\n return session?.lastSession || null;\n }\n}\n","/**\n * FsSessionStore - Filesystem implementation of SessionStore\n *\n * Handles persistence of .session.json to the local filesystem.\n * Session files are machine-local and NOT versioned in Git.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { SessionStore } from '../session_store';\nimport type { GitGovSession } from '../../session_manager/session_manager.types';\nimport { SessionManager } from '../../session_manager/session_manager';\n\n/**\n * Filesystem-based SessionStore implementation.\n *\n * Stores session state in .gitgov/.session.json.\n * Implements fail-safe pattern: returns null instead of throwing for missing files.\n *\n * @example\n * ```typescript\n * const store = new FsSessionStore('/path/to/project');\n * const session = await store.loadSession();\n * if (session) {\n * console.log(session.lastSession?.actorId);\n * }\n * ```\n */\nexport class FsSessionStore implements SessionStore {\n private readonly sessionPath: string;\n private readonly actorsPath: string;\n\n constructor(projectRootPath: string) {\n this.sessionPath = path.join(projectRootPath, '.gitgov', '.session.json');\n this.actorsPath = path.join(projectRootPath, '.gitgov', 'actors');\n }\n\n /**\n * Load local session from .gitgov/.session.json\n *\n * [EARS-A1] Returns complete GitGovSession for valid files\n * [EARS-A2] Returns null for non-existent files (fail-safe)\n * [EARS-A3] Returns null for invalid JSON (graceful degradation)\n * [EARS-A4] Returns cloud token if present\n * [EARS-A5] Returns syncPreferences if present\n */\n async loadSession(): Promise<GitGovSession | null> {\n try {\n const sessionContent = await fs.readFile(this.sessionPath, 'utf-8');\n return JSON.parse(sessionContent) as GitGovSession;\n } catch (error) {\n // Session file doesn't exist or is invalid - fail-safe behavior\n return null;\n }\n }\n\n /**\n * Save local session to .gitgov/.session.json\n *\n * [EARS-B1] Writes session to .gitgov/.session.json with JSON indentation\n * [EARS-B2] Preserves all fields (cloud, actorState, syncPreferences)\n */\n async saveSession(session: GitGovSession): Promise<void> {\n await fs.writeFile(this.sessionPath, JSON.stringify(session, null, 2), 'utf-8');\n }\n\n /**\n * Detect actor from .key files in .gitgov/actors/\n *\n * [EARS-C1] Returns actor ID from first .key file\n * [EARS-C2] Returns first .key file alphabetically if multiple exist\n * [EARS-C3] Returns null if no .key files exist\n * [EARS-C4] Returns null if actors directory doesn't exist\n * [EARS-C5] Ignores non-.key files\n * [EARS-C6] Returns null for empty directory\n *\n * @returns Actor ID (e.g., \"human:camilo-v2\") or null\n */\n async detectActorFromKeyFiles(): Promise<string | null> {\n try {\n const files = await fs.readdir(this.actorsPath);\n\n // Find all .key files\n const keyFiles = files.filter(f => f.endsWith('.key'));\n\n // Get first .key file\n const firstKeyFile = keyFiles[0];\n if (!firstKeyFile) {\n return null;\n }\n\n // Extract actor ID from filename (remove .key extension)\n // e.g., \"human:camilo-v2.key\" -> \"human:camilo-v2\"\n const actorId = firstKeyFile.replace('.key', '');\n return actorId;\n } catch {\n // Directory doesn't exist or can't be read\n return null;\n }\n }\n}\n\n/**\n * Create a SessionManager instance for a project.\n *\n * [EARS-D1] Factory function that creates a SessionManager with FsSessionStore backend.\n * Use this when you already have the projectRoot (e.g., from DI container).\n *\n * @param projectRoot - Absolute path to project root (REQUIRED)\n * @returns SessionManager instance with FsSessionStore backend\n */\nexport function createSessionManager(projectRoot: string): SessionManager {\n const sessionStore = new FsSessionStore(projectRoot);\n return new SessionManager(sessionStore);\n}\n\n","/**\n * KeyProvider Interface\n *\n * Abstracts private key storage for Actor signing operations.\n * Enables different backends: filesystem (development), environment variables (serverless),\n * or cloud KMS (enterprise).\n *\n * @module key_provider\n */\n\n/**\n * Error codes for KeyProvider operations.\n */\nexport type KeyProviderErrorCode =\n | 'KEY_NOT_FOUND'\n | 'KEY_READ_ERROR'\n | 'KEY_WRITE_ERROR'\n | 'KEY_DELETE_ERROR'\n | 'INVALID_KEY_FORMAT'\n | 'INVALID_ACTOR_ID';\n\n/**\n * Error thrown when key operations fail.\n */\nexport class KeyProviderError extends Error {\n constructor(\n message: string,\n public readonly code: KeyProviderErrorCode,\n public readonly actorId?: string\n ) {\n super(message);\n this.name = 'KeyProviderError';\n }\n}\n\n/**\n * Interface for managing private key storage.\n * Implementations handle the actual persistence mechanism.\n *\n * @example\n * ```typescript\n * // Filesystem backend (development)\n * const provider = new FsKeyProvider({ actorsDir: '.gitgov/actors' });\n *\n * // Environment backend (serverless)\n * const provider = new EnvKeyProvider({ prefix: 'GITGOV_KEY_' });\n *\n * // Usage\n * const privateKey = await provider.getPrivateKey('actor:human:alice');\n * if (privateKey) {\n * const signature = signPayload(payload, privateKey, actorId, role);\n * }\n * ```\n */\nexport interface KeyProvider {\n /**\n * Retrieves the private key for an actor.\n * @param actorId - The actor's ID (e.g., 'actor:human:alice')\n * @returns The base64-encoded private key, or null if not found\n */\n getPrivateKey(actorId: string): Promise<string | null>;\n\n /**\n * Stores a private key for an actor.\n * @param actorId - The actor's ID\n * @param privateKey - The base64-encoded private key\n * @throws KeyProviderError if write fails\n */\n setPrivateKey(actorId: string, privateKey: string): Promise<void>;\n\n /**\n * Checks if a private key exists for an actor.\n * @param actorId - The actor's ID\n * @returns true if key exists, false otherwise\n */\n hasPrivateKey(actorId: string): Promise<boolean>;\n\n /**\n * Deletes the private key for an actor.\n * @param actorId - The actor's ID\n * @returns true if key was deleted, false if it didn't exist\n */\n deletePrivateKey(actorId: string): Promise<boolean>;\n}\n","/**\n * FsKeyProvider - Filesystem-based KeyProvider implementation\n *\n * Stores private keys alongside actor records in .gitgov/actors/{actorId}.key\n * Used in development and CLI environments.\n *\n * @module key_provider/fs/fs_key_provider\n */\n\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { KeyProvider } from '../key_provider';\nimport { KeyProviderError } from '../key_provider';\n\n/**\n * Options for FsKeyProvider.\n */\nexport interface FsKeyProviderOptions {\n /** Directory where key files are stored (same as actors: .gitgov/actors) */\n actorsDir: string;\n /** File extension for key files (default: '.key') */\n extension?: string;\n /** File permissions for key files (default: 0o600 - owner read/write only) */\n fileMode?: number;\n}\n\n/**\n * Filesystem-based KeyProvider implementation.\n * Keys are stored alongside actor records with .key extension.\n *\n * @example\n * ```typescript\n * const provider = new FsKeyProvider({ actorsDir: '.gitgov/actors' });\n * await provider.setPrivateKey('actor:human:alice', 'base64PrivateKey...');\n * const key = await provider.getPrivateKey('actor:human:alice');\n * ```\n */\nexport class FsKeyProvider implements KeyProvider {\n private readonly actorsDir: string;\n private readonly extension: string;\n private readonly fileMode: number;\n\n constructor(options: FsKeyProviderOptions) {\n this.actorsDir = options.actorsDir;\n this.extension = options.extension ?? '.key';\n this.fileMode = options.fileMode ?? 0o600;\n }\n\n /**\n * [EARS-KP01] Retrieves the private key for an actor.\n * [EARS-FKP07] Trims whitespace from content.\n * [EARS-FKP08] Returns null for empty key file.\n */\n async getPrivateKey(actorId: string): Promise<string | null> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n const content = await fs.readFile(keyPath, 'utf-8');\n const key = content.trim();\n\n if (!key) {\n return null;\n }\n\n return key;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // [EARS-KP02] File not found - return null\n return null;\n }\n\n throw new KeyProviderError(\n `Failed to read private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_READ_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-KP03] Stores a private key for an actor.\n * [EARS-FKP01] Creates actorsDir if not exists.\n * [EARS-FKP02] Writes key to {actorsDir}/{actorId}.key.\n * [EARS-FKP03] Sets secure file permissions (0600).\n */\n async setPrivateKey(actorId: string, privateKey: string): Promise<void> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n // [EARS-FKP01] Ensure directory exists\n await fs.mkdir(this.actorsDir, { recursive: true });\n\n // [EARS-FKP02] Write key to {actorsDir}/{actorId}.key\n await fs.writeFile(keyPath, privateKey, 'utf-8');\n\n // [EARS-FKP03] Set secure file permissions (owner read/write only)\n await fs.chmod(keyPath, this.fileMode);\n } catch (error) {\n throw new KeyProviderError(\n `Failed to write private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_WRITE_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-FKP06] Checks if a private key exists for an actor.\n */\n async hasPrivateKey(actorId: string): Promise<boolean> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n await fs.access(keyPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * [EARS-KP04] Deletes the private key for an actor.\n */\n async deletePrivateKey(actorId: string): Promise<boolean> {\n const keyPath = this.getKeyPath(actorId);\n\n try {\n await fs.unlink(keyPath);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // File didn't exist\n return false;\n }\n\n throw new KeyProviderError(\n `Failed to delete private key for ${this.sanitizeForLog(actorId)}: ${(error as Error).message}`,\n 'KEY_DELETE_ERROR',\n actorId\n );\n }\n }\n\n /**\n * [EARS-FKP04] Builds the key file path, sanitizing actorId to prevent path traversal.\n * [EARS-FKP05] Replaces slashes with underscores.\n */\n private getKeyPath(actorId: string): string {\n // Sanitize actorId to prevent path traversal attacks\n const sanitized = this.sanitizeActorId(actorId);\n return path.join(this.actorsDir, `${sanitized}${this.extension}`);\n }\n\n /**\n * [EARS-FKP04] Sanitizes actorId to prevent directory traversal.\n * [EARS-FKP05] Replaces path separators with underscores.\n * [EARS-FKP09] Throws INVALID_ACTOR_ID for empty actorId.\n */\n private sanitizeActorId(actorId: string): string {\n // Remove path traversal attempts\n let sanitized = actorId\n .replace(/\\.\\./g, '') // Remove ..\n .replace(/[/\\\\]/g, '_'); // Replace path separators with underscore\n\n // Validate result is not empty\n if (!sanitized || sanitized === '') {\n throw new KeyProviderError(\n 'Invalid actorId: empty after sanitization',\n 'INVALID_ACTOR_ID',\n actorId\n );\n }\n\n return sanitized;\n }\n\n /**\n * Sanitizes actorId for logging (removes potential secrets).\n */\n private sanitizeForLog(actorId: string): string {\n // Just show first part for privacy\n if (actorId.length > 20) {\n return actorId.substring(0, 20) + '...';\n }\n return actorId;\n }\n}\n","/**\n * Error codes for FileLister operations.\n */\nexport type FileListerErrorCode =\n | 'FILE_NOT_FOUND'\n | 'READ_ERROR'\n | 'PERMISSION_DENIED'\n | 'INVALID_PATH'\n | 'NETWORK_ERROR';\n\n/**\n * Error thrown when file operations fail.\n */\nexport class FileListerError extends Error {\n constructor(\n message: string,\n public readonly code: FileListerErrorCode,\n public readonly filePath?: string\n ) {\n super(message);\n this.name = 'FileListerError';\n }\n}\n","/**\n * FsFileLister - Filesystem-based FileLister implementation\n *\n * Uses fast-glob for pattern matching and fs/promises for file operations.\n * Used in CLI and development environments.\n *\n * @module file_lister/fs/fs_file_lister\n */\n\nimport fg from 'fast-glob';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport type { FileLister, FileListOptions, FileStats, FsFileListerOptions } from '../file_lister';\nimport { FileListerError } from '../file_lister';\n\n/**\n * Filesystem-based FileLister implementation.\n * Uses fast-glob for pattern matching and fs/promises for file operations.\n *\n * @example\n * ```typescript\n * const lister = new FsFileLister({ cwd: '/path/to/project' });\n * const files = await lister.list(['**\\/*.ts'], { ignore: ['node_modules/**'] });\n * const content = await lister.read('src/index.ts');\n * ```\n */\nexport class FsFileLister implements FileLister {\n private readonly cwd: string;\n\n constructor(options: FsFileListerOptions) {\n this.cwd = options.cwd;\n }\n\n /**\n * [EARS-FL01] Lists files matching glob patterns.\n * [EARS-FFL01] Excludes files matching ignore patterns.\n */\n async list(patterns: string[], options?: FileListOptions): Promise<string[]> {\n // [EARS-FFL04] Validate patterns don't contain path traversal\n // [EARS-FFL05] Validate patterns are not absolute paths\n for (const pattern of patterns) {\n if (pattern.includes('..')) {\n throw new FileListerError(\n `Invalid pattern: path traversal not allowed: ${pattern}`,\n 'INVALID_PATH',\n pattern\n );\n }\n if (path.isAbsolute(pattern)) {\n throw new FileListerError(\n `Invalid pattern: absolute paths not allowed: ${pattern}`,\n 'INVALID_PATH',\n pattern\n );\n }\n }\n\n const fgOptions: Parameters<typeof fg>[1] = {\n cwd: this.cwd,\n ignore: options?.ignore ?? [],\n onlyFiles: options?.onlyFiles ?? true,\n absolute: options?.absolute ?? false,\n dot: true,\n };\n\n // Only add deep if maxDepth is specified\n if (options?.maxDepth !== undefined) {\n fgOptions.deep = options.maxDepth;\n }\n\n return fg(patterns, fgOptions);\n }\n\n /**\n * [EARS-FL02] Checks if a file exists.\n */\n async exists(filePath: string): Promise<boolean> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n try {\n const fullPath = path.join(this.cwd, filePath);\n await fs.access(fullPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * [EARS-FL03] Reads file content as string.\n * [EARS-FFL03] Throws FILE_NOT_FOUND for missing files.\n */\n async read(filePath: string): Promise<string> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n const fullPath = path.join(this.cwd, filePath);\n try {\n return await fs.readFile(fullPath, 'utf-8');\n } catch (err: unknown) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n throw new FileListerError(\n `File not found: ${filePath}`,\n 'FILE_NOT_FOUND',\n filePath\n );\n }\n if (error.code === 'EACCES') {\n throw new FileListerError(\n `Permission denied: ${filePath}`,\n 'PERMISSION_DENIED',\n filePath\n );\n }\n throw new FileListerError(\n `Read error: ${error.message}`,\n 'READ_ERROR',\n filePath\n );\n }\n }\n\n /**\n * [EARS-FL04] Gets file statistics.\n * [EARS-FFL03] Throws FILE_NOT_FOUND for missing files.\n */\n async stat(filePath: string): Promise<FileStats> {\n // [EARS-FFL04] Validate path doesn't contain traversal\n this.validatePath(filePath);\n\n const fullPath = path.join(this.cwd, filePath);\n try {\n const stats = await fs.stat(fullPath);\n return {\n size: stats.size,\n mtime: stats.mtimeMs,\n isFile: stats.isFile(),\n };\n } catch (err: unknown) {\n const error = err as NodeJS.ErrnoException;\n if (error.code === 'ENOENT') {\n throw new FileListerError(\n `File not found: ${filePath}`,\n 'FILE_NOT_FOUND',\n filePath\n );\n }\n throw new FileListerError(\n `Stat error: ${error.message}`,\n 'READ_ERROR',\n filePath\n );\n }\n }\n\n /**\n * [EARS-FFL04] Validates that the path doesn't contain traversal characters.\n * [EARS-FFL05] Validates that the path is not absolute.\n */\n private validatePath(filePath: string): void {\n if (filePath.includes('..')) {\n throw new FileListerError(\n `Invalid path: path traversal not allowed: ${filePath}`,\n 'INVALID_PATH',\n filePath\n );\n }\n // [EARS-FFL05] Prevent absolute paths to avoid escaping cwd\n if (path.isAbsolute(filePath)) {\n throw new FileListerError(\n `Invalid path: absolute paths not allowed: ${filePath}`,\n 'INVALID_PATH',\n filePath\n );\n }\n }\n}\n","/**\n * Lightweight Type Guards for GitGov Record Payloads\n *\n * These type guards are for narrowing already-validated GitGovRecordPayload unions.\n * They check structural properties, NOT schema validation.\n *\n * For schema validation (with AJV), use validators in validation/*.ts:\n * - isTaskRecord(unknown) in task_validator.ts\n * - isCycleRecord(unknown) in cycle_validator.ts\n * etc.\n *\n * @module types/type_guards\n */\n\nimport type {\n GitGovRecordPayload,\n TaskRecord,\n CycleRecord,\n ExecutionRecord,\n ActorRecord,\n AgentRecord,\n ChangelogRecord,\n FeedbackRecord\n} from './index';\n\n/**\n * Type guard: checks if payload is a TaskRecord.\n * Verifies presence of task-specific fields: title, status, priority, description.\n */\nexport function isTaskPayload(payload: GitGovRecordPayload): payload is TaskRecord {\n return 'title' in payload && 'status' in payload && 'priority' in payload && 'description' in payload;\n}\n\n/**\n * Type guard: checks if payload is a CycleRecord.\n * Verifies presence of cycle-specific fields: title, status (but NOT priority).\n */\nexport function isCyclePayload(payload: GitGovRecordPayload): payload is CycleRecord {\n return 'title' in payload && 'status' in payload && !('priority' in payload);\n}\n\n/**\n * Type guard: checks if payload is an ExecutionRecord.\n * Verifies presence of execution-specific fields: taskId, title, type, result.\n */\nexport function isExecutionPayload(payload: GitGovRecordPayload): payload is ExecutionRecord {\n return 'taskId' in payload && 'title' in payload && 'type' in payload && 'result' in payload;\n}\n\n/**\n * Type guard: checks if payload is an ActorRecord.\n * Verifies presence of actor-specific fields: displayName, publicKey, roles, type.\n */\nexport function isActorPayload(payload: GitGovRecordPayload): payload is ActorRecord {\n return 'displayName' in payload && 'publicKey' in payload && 'roles' in payload && 'type' in payload;\n}\n\n/**\n * Type guard: checks if payload is an AgentRecord (agent manifest).\n * Verifies presence of agent-specific field: engine.\n * Note: AgentRecord is a manifest, different from ActorRecord with type='agent'.\n */\nexport function isAgentPayload(payload: GitGovRecordPayload): payload is AgentRecord {\n return 'engine' in payload;\n}\n\n/**\n * Type guard: checks if payload is a ChangelogRecord.\n * Verifies presence of changelog-specific fields: title, description, relatedTasks, completedAt.\n */\nexport function isChangelogPayload(payload: GitGovRecordPayload): payload is ChangelogRecord {\n return 'title' in payload && 'description' in payload && 'relatedTasks' in payload && 'completedAt' in payload;\n}\n\n/**\n * Type guard: checks if payload is a FeedbackRecord.\n * Verifies presence of feedback-specific fields: entityType, entityId, type, status, content.\n */\nexport function isFeedbackPayload(payload: GitGovRecordPayload): payload is FeedbackRecord {\n return 'entityType' in payload && 'entityId' in payload && 'type' in payload && 'status' in payload && 'content' in payload;\n}\n","/**\n * ID Parsing Utilities for GitGov Records\n *\n * Functions for extracting information from record IDs and file paths.\n * Complements id_generator.ts (which creates IDs).\n *\n * @module utils/id_parser\n */\n\nimport type { GitGovRecordType } from '../record_types';\n\n/**\n * Mapping from directory names to entity types.\n */\nconst DIR_TO_TYPE: Record<string, Exclude<GitGovRecordType, 'custom'>> = {\n 'tasks': 'task',\n 'cycles': 'cycle',\n 'executions': 'execution',\n 'changelogs': 'changelog',\n 'feedbacks': 'feedback',\n 'actors': 'actor',\n 'agents': 'agent'\n};\n\n/**\n * Valid directory names for GitGov records.\n */\nconst VALID_DIRS = Object.keys(DIR_TO_TYPE);\n\n/**\n * Extracts the record ID from a file path.\n *\n * @param filePath - Path to a record file (e.g., '.gitgov/tasks/123-task-foo.json')\n * @returns The record ID without extension (e.g., '123-task-foo')\n *\n * @example\n * extractRecordIdFromPath('.gitgov/tasks/123-task-foo.json') // '123-task-foo'\n * extractRecordIdFromPath('/abs/path/.gitgov/actors/human_dev.json') // 'human_dev'\n */\nexport function extractRecordIdFromPath(filePath: string): string {\n const parts = filePath.split('/');\n const filename = parts[parts.length - 1] || '';\n return filename.replace('.json', '');\n}\n\n/**\n * Extracts the entity type from a file path based on directory name.\n *\n * @param filePath - Path to a record file (e.g., '.gitgov/tasks/123.json')\n * @returns The entity type or null if not found\n *\n * @example\n * getEntityTypeFromPath('.gitgov/tasks/123.json') // 'task'\n * getEntityTypeFromPath('.gitgov/actors/human_dev.json') // 'actor'\n * getEntityTypeFromPath('/some/other/path.json') // null\n */\nexport function getEntityTypeFromPath(filePath: string): Exclude<GitGovRecordType, 'custom'> | null {\n const pathParts = filePath.split('/');\n const typeDirIndex = pathParts.findIndex(part => VALID_DIRS.includes(part));\n\n if (typeDirIndex >= 0) {\n const dirName = pathParts[typeDirIndex];\n return dirName ? DIR_TO_TYPE[dirName] || null : null;\n }\n\n return null;\n}\n\n/**\n * Infers the entity type from a record ID pattern.\n *\n * Uses ID naming conventions:\n * - `{timestamp}-exec-*` or `*-execution-*` → execution\n * - `{timestamp}-changelog-*` → changelog\n * - `{timestamp}-feedback-*` → feedback\n * - `{timestamp}-cycle-*` or `cycle:*` → cycle\n * - `{timestamp}-task-*` or `task:*` → task\n * - `human:*` or `human_*` → actor\n * - `agent:*` or `agent_*` → agent\n *\n * @param recordId - The record ID to analyze\n * @returns The inferred entity type (defaults to 'task' if unknown)\n *\n * @example\n * inferEntityTypeFromId('1234567890-exec-commit') // 'execution'\n * inferEntityTypeFromId('human:developer') // 'actor'\n * inferEntityTypeFromId('agent:code-reviewer') // 'agent'\n * inferEntityTypeFromId('1234567890-task-implement-auth') // 'task'\n */\nexport function inferEntityTypeFromId(recordId: string): Exclude<GitGovRecordType, 'custom'> {\n // Execution patterns\n if (recordId.match(/^\\d+-exec-/) || recordId.includes('-execution-')) {\n return 'execution';\n }\n\n // Changelog pattern\n if (recordId.match(/^\\d+-changelog-/)) {\n return 'changelog';\n }\n\n // Feedback pattern\n if (recordId.match(/^\\d+-feedback-/)) {\n return 'feedback';\n }\n\n // Cycle patterns\n if (recordId.match(/^\\d+-cycle-/) || recordId.startsWith('cycle:')) {\n return 'cycle';\n }\n\n // Task patterns\n if (recordId.match(/^\\d+-task-/) || recordId.startsWith('task:')) {\n return 'task';\n }\n\n // Actor patterns (human)\n if (recordId.startsWith('human:') || recordId.startsWith('human_')) {\n return 'actor';\n }\n\n // Agent patterns\n if (recordId.startsWith('agent:') || recordId.startsWith('agent_')) {\n return 'agent';\n }\n\n // Default to task\n return 'task';\n}\n\n/**\n * Valid prefixes for timestamp-based record IDs.\n */\nconst VALID_PREFIXES = ['task', 'cycle', 'exec', 'changelog', 'feedback'] as const;\n\n/**\n * Parses a timestamp-based record ID (e.g., '12345-task-slug') into its components.\n *\n * @param id - The record ID to parse\n * @returns Parsed components or null if invalid format\n *\n * @example\n * parseTimestampedId('1234567890-task-implement-auth')\n * // { timestamp: 1234567890, prefix: 'task', slug: 'implement-auth' }\n */\nexport function parseTimestampedId(id: string): { timestamp: number; prefix: string; slug: string } | null {\n if (typeof id !== 'string') return null;\n const match = id.match(/^(\\d+)-(\\w+)-(.+)$/);\n if (!match || !match[1] || !match[2] || !match[3]) {\n return null;\n }\n return {\n timestamp: parseInt(match[1], 10),\n prefix: match[2],\n slug: match[3],\n };\n}\n\n/**\n * Parses an Actor ID (e.g., 'human:camilo') into its components.\n *\n * @param id - The actor ID to parse\n * @returns Parsed components or null if invalid format\n *\n * @example\n * parseActorId('human:camilo-velandia') // { type: 'human', slug: 'camilo-velandia' }\n * parseActorId('agent:code-reviewer') // { type: 'agent', slug: 'code-reviewer' }\n */\nexport function parseActorId(id: string): { type: 'human' | 'agent'; slug: string } | null {\n if (typeof id !== 'string') return null;\n const parts = id.split(':');\n if (parts.length < 2 || (parts[0] !== 'human' && parts[0] !== 'agent')) {\n return null;\n }\n const type = parts[0] as 'human' | 'agent';\n const slug = parts.slice(1).join(':'); // Re-join in case slug contains ':'\n return { type, slug };\n}\n\n/**\n * Validates the format of a timestamp-based record ID.\n *\n * @param id - The record ID to validate\n * @returns True if valid format, false otherwise\n *\n * @example\n * isValidTimestampedId('12345-task-valid-slug') // true\n * isValidTimestampedId('123-badprefix-slug') // false\n */\nexport function isValidTimestampedId(id: string): boolean {\n const parsed = parseTimestampedId(id);\n if (!parsed) return false;\n\n // Check if prefix is valid and slug is not empty\n return VALID_PREFIXES.includes(parsed.prefix as typeof VALID_PREFIXES[number]) && parsed.slug.length > 0;\n}\n","/**\n * Array Utility Functions\n *\n * Generic helpers for array manipulation.\n *\n * @module utils/array_utils\n */\n\n/**\n * Splits an array into chunks of a specified size.\n *\n * @param array - The array to split\n * @param size - Maximum size of each chunk\n * @returns Array of chunks\n *\n * @example\n * chunkArray([1, 2, 3, 4, 5], 2) // [[1, 2], [3, 4], [5]]\n * chunkArray(['a', 'b', 'c'], 3) // [['a', 'b', 'c']]\n * chunkArray([], 5) // []\n */\nexport function chunkArray<T>(array: T[], size: number): T[][] {\n if (size <= 0) {\n throw new Error('Chunk size must be greater than 0');\n }\n\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += size) {\n chunks.push(array.slice(i, i + size));\n }\n return chunks;\n}\n","export type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\nexport interface Logger {\n debug(message: string, ...args: any[]): void;\n info(message: string, ...args: any[]): void;\n warn(message: string, ...args: any[]): void;\n error(message: string, ...args: any[]): void;\n}\n\nclass ConsoleLogger implements Logger {\n private level: LogLevel;\n private prefix: string;\n\n constructor(prefix: string = \"\", level: LogLevel = \"info\") {\n this.prefix = prefix;\n this.level = level;\n }\n\n private shouldLog(level: LogLevel): boolean {\n const levels: LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\", \"silent\"];\n const currentLevelIndex = levels.indexOf(this.level);\n const messageLevelIndex = levels.indexOf(level);\n\n return currentLevelIndex <= messageLevelIndex && this.level !== \"silent\";\n }\n\n debug(message: string, ...args: any[]): void {\n if (this.shouldLog(\"debug\")) {\n console.log(`${this.prefix}${message}`, ...args);\n }\n }\n\n info(message: string, ...args: any[]): void {\n if (this.shouldLog(\"info\")) {\n console.log(`${this.prefix}${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: any[]): void {\n if (this.shouldLog(\"warn\")) {\n console.warn(`${this.prefix}${message}`, ...args);\n }\n }\n\n error(message: string, ...args: any[]): void {\n if (this.shouldLog(\"error\")) {\n console.error(`${this.prefix}${message}`, ...args);\n }\n }\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n}\n\n// Factory function para crear loggers\nexport function createLogger(prefix: string = \"\", level?: LogLevel): Logger {\n const logLevel = level ||\n (process.env['NODE_ENV'] === \"test\" ? \"silent\" : \"info\") ||\n (process.env['LOG_LEVEL'] as LogLevel) ||\n \"info\";\n\n return new ConsoleLogger(prefix, logLevel);\n}\n\n// Logger global para uso directo\nexport const logger = createLogger(\"[App] \"); ","import { createHash } from \"crypto\";\nimport type { GitGovRecordPayload } from \"../record_types\";\n\n/**\n * Recursively sorts the keys of an object, including nested objects.\n * This is the core of canonical serialization.\n * @param obj The object to sort.\n * @returns A new object with all keys sorted alphabetically.\n */\nfunction sortKeys(obj: any): any {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n const sortedKeys = Object.keys(obj).sort();\n const newObj: Record<string, any> = {};\n for (const key of sortedKeys) {\n newObj[key] = sortKeys(obj[key]);\n }\n return newObj;\n}\n\n/**\n * Canonically serializes a payload object.\n * @param payload The object to serialize.\n * @returns A deterministic JSON string.\n */\nfunction canonicalize(payload: object): string {\n const sortedPayload = sortKeys(payload);\n return JSON.stringify(sortedPayload);\n}\n\n/**\n * Calculates the SHA-256 checksum of a record's payload.\n */\nexport function calculatePayloadChecksum(payload: GitGovRecordPayload): string {\n const jsonString = canonicalize(payload);\n return createHash(\"sha256\").update(jsonString, \"utf8\").digest(\"hex\");\n} ","import type { ActorRecord } from \"./\";\nimport type { AgentRecord } from \"./\";\nimport type { CycleRecord } from \"./\";\nimport type { TaskRecord } from \"./\";\nimport type { ExecutionRecord } from \"./\";\nimport type { ChangelogRecord } from \"./\";\nimport type { FeedbackRecord } from \"./\";\nimport type { EmbeddedMetadataRecord } from \"./embedded.types\";\n\n/**\n * A custom record type for testing purposes.\n */\nexport type CustomRecord = {\n type: 'custom';\n data: unknown;\n}\n\n/**\n * Defines the possible 'type' values for any record in the system.\n */\nexport type GitGovRecordType =\n | \"actor\"\n | \"agent\"\n | \"cycle\"\n | \"task\"\n | \"execution\"\n | \"changelog\"\n | \"feedback\"\n | \"custom\";\n\n/**\n * The canonical payload for any GitGovernance record.\n */\nexport type GitGovRecordPayload =\n | ActorRecord\n | AgentRecord\n | CycleRecord\n | TaskRecord\n | ExecutionRecord\n | ChangelogRecord\n | FeedbackRecord\n | CustomRecord;\n\n/**\n * The canonical type for any record in GitGovernance, wrapping a payload with metadata.\n */\nexport type GitGovRecord = EmbeddedMetadataRecord<GitGovRecordPayload>;\n\n/**\n * Specific GitGov record types with full metadata (header + payload).\n * These types provide clean, type-safe access to records with their signatures and checksums.\n * \n * @example\n * const taskRecord: GitGovTaskRecord = await taskStore.read(taskId);\n * const authorId = taskRecord.header.signatures[0].keyId;\n */\nexport type GitGovTaskRecord = EmbeddedMetadataRecord<TaskRecord>;\nexport type GitGovCycleRecord = EmbeddedMetadataRecord<CycleRecord>;\nexport type GitGovFeedbackRecord = EmbeddedMetadataRecord<FeedbackRecord>;\nexport type GitGovExecutionRecord = EmbeddedMetadataRecord<ExecutionRecord>;\nexport type GitGovChangelogRecord = EmbeddedMetadataRecord<ChangelogRecord>;\nexport type GitGovActorRecord = EmbeddedMetadataRecord<ActorRecord>;\nexport type GitGovAgentRecord = EmbeddedMetadataRecord<AgentRecord>;\n\n// Payloads for creating new records\nexport type ActorPayload = Partial<ActorRecord>;\nexport type AgentPayload = Partial<AgentRecord>;\nexport type CyclePayload = Partial<CycleRecord>;\nexport type TaskPayload = Partial<TaskRecord>;\nexport type ExecutionPayload = Partial<ExecutionRecord>;\nexport type ChangelogPayload = Partial<ChangelogRecord>;\nexport type FeedbackPayload = Partial<FeedbackRecord>;\n\n/**\n * Base class for all GitGovernance-specific errors.\n * Centralized here as it's used across multiple modules (schemas, validation, etc.)\n */\nexport class GitGovError extends Error {\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n\n","/**\n * Schema-specific error types for GitGovernance core.\n * These errors are thrown during JSON Schema validation and compilation.\n */\n\n// Import GitGovError from models (common types) - no circular dependencies\nimport { GitGovError } from '../record_types/common.types';\n\n// Re-export for backward compatibility\nexport { GitGovError };\n\n/**\n * Custom Error type for failures related to JSON Schema validation.\n */\nexport class SchemaValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SchemaValidationError\";\n }\n}\n\n/**\n * Error for detailed AJV validation failures with multiple field errors.\n */\nexport class DetailedValidationError extends GitGovError {\n constructor(\n recordType: string,\n public readonly errors: Array<{\n field: string;\n message: string;\n value: unknown;\n }>\n ) {\n const errorSummary = errors\n .map(err => `${err.field}: ${err.message}`)\n .join(', ');\n\n super(\n `${recordType} validation failed: ${errorSummary}`,\n 'DETAILED_VALIDATION_ERROR'\n );\n }\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"actor_record_schema.json\",\n \"title\": \"ActorRecord\",\n \"description\": \"Canonical schema for actor records as defined in actor_protocol.md\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"type\",\n \"displayName\",\n \"publicKey\",\n \"roles\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"Unique, human-readable identifier for the actor.\",\n \"examples\": [\n \"human:camilo\",\n \"agent:aion\",\n \"agent:camilo:cursor\"\n ]\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"human\",\n \"agent\"\n ],\n \"description\": \"The type of actor.\"\n },\n \"displayName\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100,\n \"description\": \"The name of the actor to be used in user interfaces.\"\n },\n \"publicKey\": {\n \"type\": \"string\",\n \"minLength\": 44,\n \"maxLength\": 44,\n \"description\": \"The Ed25519 public key (base64 encoded, 44 characters) for verifying the actor's signatures.\"\n },\n \"roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"minItems\": 1,\n \"uniqueItems\": true,\n \"description\": \"List of capacity roles defining the actor's skills and permissions. Uses hierarchical format with colons.\",\n \"examples\": [\n [\n \"developer:backend:go\",\n \"auditor\"\n ],\n [\n \"planner:ai\"\n ]\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"active\",\n \"revoked\"\n ],\n \"default\": \"active\",\n \"description\": \"Optional. The lifecycle status of the actor. Defaults to 'active' if not specified.\"\n },\n \"supersededBy\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"Optional. The ID of the actor that replaces this one.\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"description\": \"An optional field for additional, non-canonical metadata.\",\n \"examples\": [\n {\n \"version\": \"1.2.0\",\n \"source\": \"https://github.com/...\"\n },\n {\n \"team\": \"frontend\"\n }\n ]\n }\n }\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"agent_record_schema.json\",\n \"title\": \"AgentRecord\",\n \"description\": \"Canonical schema for agent operational manifests.\",\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"engine\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^agent:[a-z0-9:-]+$\",\n \"description\": \"Unique identifier for the agent, linking to an ActorRecord.\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"active\",\n \"archived\"\n ],\n \"default\": \"active\"\n },\n \"triggers\": {\n \"type\": \"array\",\n \"default\": [],\n \"description\": \"Optional list of triggers that activate the agent.\\nAdditional fields are allowed and depend on trigger type:\\n- webhook triggers: 'event' (event identifier), 'filter' (condition)\\n- scheduled triggers: 'cron' (cron expression)\\n- manual triggers: 'command' (example CLI command)\\n\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"manual\",\n \"webhook\",\n \"scheduled\"\n ],\n \"description\": \"Type of trigger that activates the agent\"\n }\n },\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": true\n }\n },\n \"knowledge_dependencies\": {\n \"type\": \"array\",\n \"default\": [],\n \"items\": {\n \"type\": \"string\",\n \"description\": \"Glob patterns for blueprint files this agent needs access to\"\n }\n },\n \"prompt_engine_requirements\": {\n \"type\": \"object\",\n \"properties\": {\n \"roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"skills\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"metadata\": {\n \"type\": \"object\",\n \"description\": \"Optional framework-specific or deployment-specific metadata for agent extensions.\\nCommon use cases: framework identification (langchain, google-adk), deployment info (provider, image, region),\\ncost tracking (cost_per_invocation, currency), tool capabilities, maintainer info.\\nThis field does NOT affect agent execution - it is purely informational.\\n\",\n \"additionalProperties\": true\n },\n \"engine\": {\n \"type\": \"object\",\n \"oneOf\": [\n {\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"local\"\n },\n \"runtime\": {\n \"type\": \"string\",\n \"description\": \"Runtime environment (typescript, python, etc.)\"\n },\n \"entrypoint\": {\n \"type\": \"string\",\n \"description\": \"Path to the agent entry file\"\n },\n \"function\": {\n \"type\": \"string\",\n \"description\": \"Function name to invoke\"\n }\n }\n },\n {\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"api\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"HTTP endpoint for the agent\"\n },\n \"method\": {\n \"type\": \"string\",\n \"enum\": [\n \"POST\",\n \"GET\",\n \"PUT\"\n ],\n \"default\": \"POST\"\n },\n \"auth\": {\n \"type\": \"object\",\n \"description\": \"Authentication configuration for API requests\",\n \"additionalProperties\": true,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"bearer\",\n \"oauth\",\n \"api-key\",\n \"actor-signature\"\n ],\n \"description\": \"Authentication type. 'actor-signature' uses the agent's ActorRecord keypair to sign requests.\"\n },\n \"secret_key\": {\n \"type\": \"string\",\n \"description\": \"Reference to secret in Secret Manager (for bearer/api-key/oauth auth types)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Direct token value (not recommended for production, use secret_key instead)\"\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"type\",\n \"url\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"mcp\"\n },\n \"url\": {\n \"type\": \"string\",\n \"format\": \"uri\",\n \"description\": \"MCP server endpoint\"\n },\n \"tool\": {\n \"type\": \"string\",\n \"description\": \"Name of the MCP tool to invoke. If not specified, defaults to agentId without 'agent:' prefix.\"\n },\n \"auth\": {\n \"type\": \"object\",\n \"description\": \"Authentication configuration for MCP server\",\n \"additionalProperties\": true,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"bearer\",\n \"oauth\",\n \"api-key\",\n \"actor-signature\"\n ],\n \"description\": \"Authentication type. 'actor-signature' uses the agent's ActorRecord keypair to sign requests.\"\n },\n \"secret_key\": {\n \"type\": \"string\",\n \"description\": \"Reference to secret in Secret Manager (for bearer/api-key/oauth auth types)\"\n },\n \"token\": {\n \"type\": \"string\",\n \"description\": \"Direct token value (not recommended for production, use secret_key instead)\"\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"type\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"const\": \"custom\"\n },\n \"protocol\": {\n \"type\": \"string\",\n \"description\": \"Custom protocol identifier (e.g., 'a2a', 'grpc')\"\n },\n \"config\": {\n \"type\": \"object\",\n \"description\": \"Protocol-specific configuration\"\n }\n }\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"agent:scribe\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"local\",\n \"runtime\": \"typescript\",\n \"entrypoint\": \"packages/agents/scribe/index.ts\",\n \"function\": \"runScribe\"\n },\n \"metadata\": {\n \"purpose\": \"documentation-generation\",\n \"maintainer\": \"team:platform\"\n },\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ],\n \"knowledge_dependencies\": [\n \"packages/blueprints/**/*.md\"\n ]\n },\n {\n \"id\": \"agent:langchain-analyzer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"https://langchain-service-xyz.a.run.app/analyze\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"framework\": \"langchain\",\n \"version\": \"0.2.0\",\n \"model\": \"gpt-4-turbo\",\n \"deployment\": {\n \"provider\": \"gcp\",\n \"service\": \"cloud-run\",\n \"region\": \"us-central1\"\n },\n \"cost_per_invocation\": 0.03,\n \"currency\": \"USD\"\n },\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"task.ready\"\n }\n ],\n \"knowledge_dependencies\": [\n \"docs/architecture/**/*.md\"\n ]\n },\n {\n \"id\": \"agent:sentiment-analyzer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"http://sentiment-analyzer:8082/analyze\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"framework\": \"google-adk\",\n \"version\": \"1.0.0\",\n \"model\": \"gemini-pro\",\n \"deployment\": {\n \"runtime\": \"docker\",\n \"image\": \"gitgov/sentiment-analyzer:v1.2.0\",\n \"port\": 8082\n },\n \"max_tokens\": 1024\n },\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"feedback.created\"\n }\n ]\n },\n {\n \"id\": \"agent:cursor-reviewer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"mcp\",\n \"url\": \"http://localhost:8083/mcp\",\n \"auth\": {\n \"type\": \"actor-signature\"\n }\n },\n \"metadata\": {\n \"ide\": \"cursor\",\n \"tool\": \"code-review\",\n \"accepts_tools\": [\n \"review\",\n \"refactor\",\n \"test\"\n ]\n },\n \"knowledge_dependencies\": [\n \"packages/**/*.ts\",\n \"packages/**/*.tsx\"\n ],\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"task.status.ready\"\n }\n ]\n },\n {\n \"id\": \"agent:deepl-translator\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"api\",\n \"url\": \"https://api.deepl.com/v2/translate\",\n \"method\": \"POST\",\n \"auth\": {\n \"type\": \"bearer\",\n \"secret_key\": \"DEEPL_API_KEY\"\n }\n },\n \"metadata\": {\n \"provider\": \"deepl\",\n \"supported_languages\": [\n \"EN\",\n \"ES\",\n \"FR\",\n \"DE\",\n \"PT\"\n ],\n \"max_chars_per_request\": 5000\n },\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ]\n },\n {\n \"id\": \"agent:coordinator\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"custom\",\n \"protocol\": \"a2a\",\n \"config\": {\n \"endpoint\": \"https://agent-hub.gitgov.io/a2a\",\n \"version\": \"draft-2025-01\",\n \"capabilities\": [\n \"task-delegation\",\n \"status-sync\",\n \"feedback-loop\"\n ]\n }\n },\n \"metadata\": {\n \"purpose\": \"multi-agent-orchestration\",\n \"experimental\": true\n },\n \"triggers\": [\n {\n \"type\": \"scheduled\",\n \"cron\": \"0 */4 * * *\"\n }\n ]\n },\n {\n \"id\": \"agent:minimal-watcher\",\n \"engine\": {\n \"type\": \"local\"\n }\n },\n {\n \"id\": \"agent:local-mcp-server\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"mcp\",\n \"url\": \"http://localhost:9000/mcp\"\n },\n \"knowledge_dependencies\": [\n \"packages/blueprints/**/*.md\"\n ],\n \"triggers\": [\n {\n \"type\": \"manual\"\n }\n ]\n },\n {\n \"id\": \"agent:code-reviewer\",\n \"status\": \"active\",\n \"engine\": {\n \"type\": \"local\",\n \"runtime\": \"typescript\",\n \"entrypoint\": \"packages/agents/code-reviewer/index.ts\",\n \"function\": \"reviewCode\"\n },\n \"prompt_engine_requirements\": {\n \"roles\": [\n \"code-reviewer\",\n \"security-auditor\"\n ],\n \"skills\": [\n \"typescript\",\n \"security-best-practices\",\n \"code-quality-analysis\"\n ]\n },\n \"knowledge_dependencies\": [\n \"packages/**/*.ts\",\n \"packages/**/*.tsx\"\n ],\n \"triggers\": [\n {\n \"type\": \"webhook\",\n \"event\": \"pull-request.opened\",\n \"filter\": \"branch:main\"\n }\n ]\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"changelog_record_schema.json\",\n \"title\": \"ChangelogRecord\",\n \"description\": \"Canonical schema for changelog records - aggregates N tasks into 1 release note\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"description\",\n \"relatedTasks\",\n \"completedAt\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-changelog-[a-z0-9-]{1,50}$\",\n \"maxLength\": 71,\n \"description\": \"Unique identifier for the changelog entry\",\n \"examples\": [\n \"1752707800-changelog-sistema-autenticacion-v1\",\n \"1752707800-changelog-sprint-24-api-performance\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 150,\n \"description\": \"Executive title of the deliverable\",\n \"examples\": [\n \"Sistema de Autenticación Completo v1.0\",\n \"Sprint 24 - Performance Optimizations\"\n ]\n },\n \"description\": {\n \"type\": \"string\",\n \"minLength\": 20,\n \"maxLength\": 5000,\n \"description\": \"Detailed description of the value delivered, including key decisions and impact\"\n },\n \"relatedTasks\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\"\n },\n \"minItems\": 1,\n \"description\": \"IDs of tasks that compose this deliverable (minimum 1 required)\"\n },\n \"completedAt\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"description\": \"Unix timestamp in seconds when the deliverable was completed\"\n },\n \"relatedCycles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\"\n },\n \"default\": [],\n \"description\": \"Optional IDs of cycles related to this deliverable\"\n },\n \"relatedExecutions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-exec-[a-z0-9-]{1,50}$\"\n },\n \"default\": [],\n \"description\": \"Optional IDs of key execution records related to this work\"\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 50,\n \"description\": \"Optional version or release identifier (e.g., 'v1.0.0', 'sprint-24')\",\n \"examples\": [\n \"v1.0.0\",\n \"v2.1.3\",\n \"sprint-24\"\n ]\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"default\": [],\n \"description\": \"Optional tags for categorization (e.g., 'feature:auth', 'bugfix', 'security')\"\n },\n \"commits\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 100\n },\n \"default\": [],\n \"description\": \"Optional list of git commit hashes related to this deliverable\"\n },\n \"files\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Optional list of main files that were created or modified\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"maxLength\": 3000,\n \"description\": \"Optional additional context, decisions, or learnings\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1752707800-changelog-sistema-autenticacion-v1\",\n \"title\": \"Sistema de Autenticación Completo v1.0\",\n \"description\": \"Implementación completa del sistema de autenticación con OAuth2, 2FA via TOTP, recuperación de contraseña, y UI responsive. Incluye tests E2E completos (95% coverage) y documentación técnica actualizada.\",\n \"relatedTasks\": [\n \"1752274500-task-crear-ui-login\",\n \"1752274600-task-integrar-oauth2-backend\",\n \"1752274700-task-implementar-2fa-totp\",\n \"1752274800-task-tests-e2e-auth\",\n \"1752274900-task-documentar-flujo-auth\"\n ],\n \"completedAt\": 1752707800,\n \"relatedCycles\": [\n \"1752200000-cycle-q1-auth-milestone\"\n ],\n \"relatedExecutions\": [\n \"1752274550-exec-analisis-auth-providers\",\n \"1752707750-exec-final-integration-test\"\n ],\n \"version\": \"v1.0.0\",\n \"tags\": [\n \"feature:auth\",\n \"security\",\n \"frontend\",\n \"backend\"\n ],\n \"commits\": [\n \"abc123def\",\n \"456ghi789\",\n \"jkl012mno\"\n ],\n \"files\": [\n \"src/pages/Login.tsx\",\n \"src/services/auth.ts\",\n \"src/components/TwoFactorSetup.tsx\",\n \"e2e/auth.spec.ts\"\n ],\n \"notes\": \"Decisión técnica: Usamos NextAuth.js después de evaluar Passport.js. El 2FA se implementó con TOTP (Google Authenticator compatible) en lugar de SMS por seguridad y costo.\"\n },\n {\n \"id\": \"1752707900-changelog-hotfix-payment-timeout\",\n \"title\": \"Hotfix: Critical Payment Timeout Fix\",\n \"description\": \"Fixed critical payment timeout issue affecting 15% of transactions. Increased timeout from 5s to 30s and added circuit breaker pattern for third-party API calls.\",\n \"relatedTasks\": [\n \"1752707850-task-fix-payment-timeout\",\n \"1752707870-task-add-circuit-breaker\"\n ],\n \"completedAt\": 1752707900,\n \"version\": \"v1.2.1\",\n \"tags\": [\n \"hotfix\",\n \"critical\",\n \"payment\"\n ],\n \"commits\": [\n \"xyz789abc\"\n ],\n \"notes\": \"Emergency response to production incident. Deployed to production within 2 hours.\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"cycle_record_schema.json\",\n \"title\": \"CycleRecord\",\n \"description\": \"Canonical schema for cycle records - strategic grouping of work\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"status\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67,\n \"description\": \"Unique identifier for the cycle (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\",\n \"examples\": [\n \"1754400000-cycle-sprint-24-api-performance\",\n \"1754500000-cycle-auth-system-v2\",\n \"1754600000-cycle-q4-2025-growth\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"Human-readable title for the cycle (e.g., 'Sprint 24', 'Auth v2.0', 'Q4 2025')\",\n \"examples\": [\n \"Sprint 24 - API Performance\",\n \"Authentication System v2.0\",\n \"Q4 2025 - Growth & Scale\"\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"planning\",\n \"active\",\n \"completed\",\n \"archived\"\n ],\n \"description\": \"The lifecycle status of the cycle\"\n },\n \"taskIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66\n },\n \"default\": [],\n \"description\": \"Optional array of Task IDs that belong to this cycle. Can be empty for cycles that only contain child cycles. (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n [\n \"1752274500-task-optimizar-endpoint-search\",\n \"1752360900-task-anadir-cache-a-redis\"\n ]\n ]\n },\n \"childCycleIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67\n },\n \"default\": [],\n \"description\": \"Optional array of Cycle IDs that are children of this cycle, allowing for hierarchies (e.g., Q1 containing Sprint 1, Sprint 2, Sprint 3). (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\",\n \"examples\": [\n [\n \"1754400000-cycle-sprint-24\",\n \"1754500000-cycle-sprint-25\"\n ]\n ]\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\",\n \"maxLength\": 100\n },\n \"default\": [],\n \"description\": \"Optional list of key:value tags for categorization (e.g., 'roadmap:q4', 'team:alpha', 'okr:growth').\",\n \"examples\": [\n [\n \"roadmap:q4\",\n \"team:backend\"\n ],\n [\n \"sprint:24\",\n \"focus:performance\"\n ],\n [\n \"milestone:v2\",\n \"security\"\n ]\n ]\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 0,\n \"maxLength\": 10000,\n \"description\": \"Optional description of the cycle's goals, objectives, and context\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1754400000-cycle-sprint-24-api-performance\",\n \"title\": \"Sprint 24 - API Performance\",\n \"status\": \"active\",\n \"taskIds\": [\n \"1752274500-task-optimizar-endpoint-search\",\n \"1752360900-task-anadir-cache-a-redis\",\n \"1752447300-task-implementar-rate-limiting\"\n ],\n \"tags\": [\n \"sprint:24\",\n \"team:backend\",\n \"focus:performance\"\n ],\n \"notes\": \"Objetivo: Reducir la latencia p95 de la API por debajo de 200ms y preparar infraestructura para Black Friday.\"\n },\n {\n \"id\": \"1754500000-cycle-auth-system-v2\",\n \"title\": \"Authentication System v2.0\",\n \"status\": \"planning\",\n \"taskIds\": [\n \"1752274500-task-oauth2-integration\",\n \"1752360900-task-2fa-implementation\",\n \"1752447300-task-password-recovery\",\n \"1752533700-task-session-management\"\n ],\n \"tags\": [\n \"milestone:v2\",\n \"security\",\n \"feature:auth\"\n ],\n \"notes\": \"Milestone mayor: Sistema completo de autenticación con OAuth2, 2FA, y gestión avanzada de sesiones. Crítico para lanzamiento Q4.\"\n },\n {\n \"id\": \"1754600000-cycle-q4-2025-growth\",\n \"title\": \"Q4 2025 - Growth & Scale\",\n \"status\": \"active\",\n \"childCycleIds\": [\n \"1754400000-cycle-sprint-24-api-performance\",\n \"1754500000-cycle-auth-system-v2\",\n \"1754650000-cycle-mobile-app-launch\"\n ],\n \"tags\": [\n \"roadmap:q4\",\n \"strategy:growth\",\n \"okr:scale-to-1m-users\"\n ],\n \"notes\": \"Objetivo trimestral: Escalar a 1M usuarios activos. Incluye mejoras de performance, nuevo sistema de auth, y lanzamiento de app móvil.\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"embedded_metadata_schema.json\",\n \"title\": \"EmbeddedMetadataRecord\",\n \"description\": \"Canonical schema for the wrapper structure of all GitGovernance records.\",\n \"type\": \"object\",\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"version\": {\n \"type\": \"string\",\n \"enum\": [\n \"1.0\"\n ],\n \"description\": \"Version of the embedded metadata format.\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"actor\",\n \"agent\",\n \"task\",\n \"execution\",\n \"changelog\",\n \"feedback\",\n \"cycle\",\n \"custom\"\n ],\n \"description\": \"The type of the record contained in the payload.\"\n },\n \"schemaUrl\": {\n \"type\": \"string\",\n \"description\": \"Optional URL to a custom schema for the payload.\"\n },\n \"schemaChecksum\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-fA-F0-9]{64}$\",\n \"description\": \"Optional SHA-256 checksum of the custom schema.\"\n },\n \"payloadChecksum\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-fA-F0-9]{64}$\",\n \"description\": \"SHA-256 checksum of the canonically serialized payload.\"\n },\n \"signatures\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"keyId\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"description\": \"The Actor ID of the signer (must match ActorRecord.id pattern).\"\n },\n \"role\": {\n \"type\": \"string\",\n \"pattern\": \"^([a-z-]+|custom:[a-z0-9-]+)$\",\n \"minLength\": 1,\n \"maxLength\": 50,\n \"description\": \"The context role of the signature (e.g., 'author', 'reviewer', 'auditor', or 'custom:*').\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 1000,\n \"description\": \"Human-readable note from the signer. Part of the signature digest.\"\n },\n \"signature\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9+/]{86}==$\",\n \"description\": \"The Ed25519 signature (base64 encoded, 88 chars with padding) of the signature digest.\"\n },\n \"timestamp\": {\n \"type\": \"integer\",\n \"description\": \"Unix timestamp of the signature.\"\n }\n },\n \"required\": [\n \"keyId\",\n \"role\",\n \"notes\",\n \"signature\",\n \"timestamp\"\n ],\n \"additionalProperties\": false\n },\n \"description\": \"An array of one or more signature objects.\"\n }\n },\n \"required\": [\n \"version\",\n \"type\",\n \"payloadChecksum\",\n \"signatures\"\n ],\n \"additionalProperties\": false\n },\n \"payload\": {\n \"type\": \"object\",\n \"description\": \"The specific record data, validated against the schema defined by header.type.\"\n }\n },\n \"required\": [\n \"header\",\n \"payload\"\n ],\n \"additionalProperties\": false,\n \"oneOf\": [\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"actor\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:actor_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"agent\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:agent_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"task\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:task_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"execution\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:execution_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"changelog\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:changelog_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"feedback\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:feedback_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"cycle\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"payload\": {\n \"$ref\": \"ref:cycle_record_schema\"\n }\n }\n },\n \"else\": false\n },\n {\n \"if\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"const\": \"custom\"\n }\n }\n }\n }\n },\n \"then\": {\n \"properties\": {\n \"header\": {\n \"type\": \"object\",\n \"required\": [\n \"schemaUrl\",\n \"schemaChecksum\"\n ]\n }\n }\n },\n \"else\": false\n }\n ],\n \"examples\": [\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"task\",\n \"payloadChecksum\": \"a1b2c3d4e5f6...\",\n \"signatures\": [\n {\n \"keyId\": \"human:lead-dev\",\n \"role\": \"author\",\n \"notes\": \"Initial task creation for OAuth 2.0 implementation\",\n \"signature\": \"...\",\n \"timestamp\": 1752274500\n }\n ]\n },\n \"payload\": {\n \"id\": \"1752274500-task-implementar-auth\",\n \"status\": \"pending\",\n \"priority\": \"high\",\n \"description\": \"Implementar autenticación OAuth 2.0.\",\n \"tags\": [\n \"skill:go\",\n \"area:backend\"\n ]\n }\n },\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"execution\",\n \"payloadChecksum\": \"b2c3d4e5f6a1...\",\n \"signatures\": [\n {\n \"keyId\": \"agent:cursor\",\n \"role\": \"author\",\n \"notes\": \"OAuth 2.0 flow completed with GitHub provider integration\",\n \"signature\": \"...\",\n \"timestamp\": 1752274600\n },\n {\n \"keyId\": \"human:camilo\",\n \"role\": \"reviewer\",\n \"notes\": \"Reviewed and tested locally. LGTM.\",\n \"signature\": \"...\",\n \"timestamp\": 1752274650\n }\n ]\n },\n \"payload\": {\n \"id\": \"1752274600-exec-implement-oauth\",\n \"taskId\": \"1752274500-task-implement-oauth\",\n \"type\": \"progress\",\n \"title\": \"OAuth 2.0 flow implemented\",\n \"result\": \"Completed the OAuth 2.0 authentication flow...\"\n }\n },\n {\n \"header\": {\n \"version\": \"1.0\",\n \"type\": \"actor\",\n \"payloadChecksum\": \"c3d4e5f6a1b2...\",\n \"signatures\": [\n {\n \"keyId\": \"human:admin\",\n \"role\": \"author\",\n \"notes\": \"New developer onboarded to team\",\n \"signature\": \"...\",\n \"timestamp\": 1752274700\n },\n {\n \"keyId\": \"agent:aion\",\n \"role\": \"auditor\",\n \"notes\": \"Actor verification: 10/10. Credentials validated.\",\n \"signature\": \"...\",\n \"timestamp\": 1752274705\n }\n ]\n },\n \"payload\": {\n \"id\": \"human:new-developer\",\n \"type\": \"human\",\n \"displayName\": \"New Developer\",\n \"publicKey\": \"...\",\n \"roles\": [\n \"developer\"\n ]\n }\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"execution_record_schema.json\",\n \"title\": \"ExecutionRecord\",\n \"description\": \"Canonical schema for execution log records - the universal event stream\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"taskId\",\n \"type\",\n \"title\",\n \"result\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-exec-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"Unique identifier for the execution log entry (10 timestamp + 1 dash + 4 'exec' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n \"1752275000-exec-refactor-queries\",\n \"1752361200-exec-api-externa-caida\"\n ]\n },\n \"taskId\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"ID of the parent task this execution belongs to (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"analysis\",\n \"progress\",\n \"blocker\",\n \"completion\",\n \"info\",\n \"correction\"\n ],\n \"description\": \"Semantic classification of the execution event\",\n \"examples\": [\n \"progress\",\n \"analysis\",\n \"blocker\",\n \"completion\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"Human-readable title for the execution (used to generate ID)\",\n \"examples\": [\n \"Refactor de queries N+1\",\n \"API Externa Caída\",\n \"Plan de implementación OAuth2\"\n ]\n },\n \"result\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 22000,\n \"description\": \"The tangible, verifiable output or result of the execution. \\nThis is the \\\"WHAT\\\" - evidence of work or event summary.\\n\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"maxLength\": 6500,\n \"description\": \"Optional narrative, context and decisions behind the execution.\\nThis is the \\\"HOW\\\" and \\\"WHY\\\" - the story behind the result.\\n\"\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Optional list of typed references to relevant commits, files, PRs, or external documents.\\nShould use typed prefixes for clarity and trazabilidad (see execution_protocol_appendix.md):\\n- commit: Git commit SHA\\n- pr: Pull Request number\\n- file: File path (relative to repo root)\\n- url: External URL\\n- issue: GitHub Issue number\\n- task: TaskRecord ID\\n- exec: ExecutionRecord ID (for corrections or dependencies)\\n- changelog: ChangelogRecord ID\\n\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Optional structured data for machine consumption.\\nUse this field for data that needs to be programmatically processed (e.g., audit findings,\\nperformance metrics, scan results). This complements result (human-readable WHAT) and\\nnotes (narrative HOW/WHY) by providing structured, queryable data.\\nCommon use cases: audit findings arrays, performance metrics, tool outputs, scan summaries.\\n\",\n \"examples\": [\n {\n \"findings\": [\n {\n \"type\": \"PII\",\n \"file\": \"src/user.ts\",\n \"line\": 42\n }\n ],\n \"scannedFiles\": 245\n },\n {\n \"metrics\": {\n \"duration_ms\": 1250,\n \"memory_mb\": 512\n }\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"1752275500-exec-refactor-queries\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"progress\",\n \"title\": \"Refactor de queries N+1\",\n \"result\": \"Refactorizados 3 queries N+1 a un solo JOIN optimizado. Performance mejoró de 2.5s a 200ms.\",\n \"notes\": \"Identificados 3 N+1 queries en el endpoint /api/search. Aplicado eager loading y caching de relaciones.\",\n \"references\": [\n \"commit:b2c3d4e\",\n \"file:src/api/search.ts\"\n ]\n },\n {\n \"id\": \"1752361200-exec-api-externa-caida\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"blocker\",\n \"title\": \"API Externa Caída\",\n \"result\": \"No se puede continuar con testing de integración. API de pagos devuelve 503.\",\n \"notes\": \"La API de pagos de terceros (api.payments.com) está devolviendo errores 503. Contactado soporte del proveedor. ETA de resolución: 2-3 horas.\",\n \"references\": [\n \"url:https://status.payments.com\"\n ]\n },\n {\n \"id\": \"1752188000-exec-plan-oauth-implementation\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"analysis\",\n \"title\": \"Plan de implementación OAuth2\",\n \"result\": \"Documento de diseño técnico completado. 5 sub-tareas identificadas con estimaciones de complejidad.\",\n \"notes\": \"Evaluadas 3 opciones: NextAuth.js (elegida), Passport.js, custom implementation. NextAuth.js por madurez y soporte de múltiples providers.\",\n \"references\": [\n \"file:docs/oauth-design.md\"\n ]\n },\n {\n \"id\": \"1752707800-exec-oauth-completed\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"completion\",\n \"title\": \"OAuth Implementation Completed\",\n \"result\": \"Sistema OAuth2 completamente implementado, testeado y deployado a staging. 95% test coverage. Todos los acceptance criteria cumplidos.\",\n \"notes\": \"Implementación finalizada. Code review aprobado. Tests E2E passing. Ready para changelog y deploy a producción.\",\n \"references\": [\n \"pr:456\",\n \"commit:def789abc\",\n \"url:https://staging.app.com/login\"\n ]\n },\n {\n \"id\": \"1752275600-exec-cambio-estrategia-redis\",\n \"taskId\": \"1752274500-task-oauth-implementation\",\n \"type\": \"info\",\n \"title\": \"Cambio de estrategia: Usar Redis para sessions\",\n \"result\": \"Decisión: Migrar de JWT stateless a sessions en Redis por requisito de revocación inmediata.\",\n \"notes\": \"Durante code review se identificó requisito crítico: revocar sesiones inmediatamente (ej: compromiso de cuenta). JWT stateless no permite esto sin lista negra compleja. Redis sessions permite revocación instantánea.\",\n \"references\": [\n \"issue:567\",\n \"url:https://redis.io/docs/manual/keyspace-notifications/\"\n ]\n },\n {\n \"id\": \"1752275700-exec-correccion-metricas\",\n \"taskId\": \"1752274500-task-optimizar-api\",\n \"type\": \"correction\",\n \"title\": \"Corrección: Métricas de performance\",\n \"result\": \"Corrección de execution 1752275500-exec-refactor-queries: El performance fue 200ms, no 50ms como se reportó.\",\n \"notes\": \"Error de tipeo en execution original. La mejora real fue de 2.5s a 200ms (no 50ms). Sigue siendo significativa (92% mejora) pero números correctos son importantes para métricas.\",\n \"references\": [\n \"exec:1752275500-exec-refactor-queries\"\n ]\n },\n {\n \"id\": \"1752276000-exec-source-audit-scan\",\n \"taskId\": \"1752274500-task-audit-compliance\",\n \"type\": \"analysis\",\n \"title\": \"Source Audit Scan - 2025-01-15\",\n \"result\": \"Escaneados 245 archivos. Encontrados 10 findings (3 critical, 4 high, 3 medium). Ver metadata para detalles estructurados.\",\n \"notes\": \"Scan ejecutado con RegexDetector + HeuristicDetector. LLM calls: 0 (tier free).\",\n \"references\": [\n \"file:src/config/db.ts\",\n \"file:src/auth/keys.ts\"\n ],\n \"metadata\": {\n \"scannedFiles\": 245,\n \"scannedLines\": 18420,\n \"duration_ms\": 1250,\n \"findings\": [\n {\n \"id\": \"SEC-001\",\n \"severity\": \"critical\",\n \"file\": \"src/config/db.ts\",\n \"line\": 5,\n \"type\": \"api_key\"\n },\n {\n \"id\": \"SEC-003\",\n \"severity\": \"critical\",\n \"file\": \"src/auth/keys.ts\",\n \"line\": 2,\n \"type\": \"private_key\"\n },\n {\n \"id\": \"PII-003\",\n \"severity\": \"critical\",\n \"file\": \"src/payments/stripe.ts\",\n \"line\": 8,\n \"type\": \"credit_card\"\n }\n ],\n \"summary\": {\n \"critical\": 3,\n \"high\": 4,\n \"medium\": 3,\n \"low\": 0\n }\n }\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"feedback_record_schema.json\",\n \"title\": \"FeedbackRecord\",\n \"description\": \"Canonical schema for feedback records - structured conversation about work\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"entityType\",\n \"entityId\",\n \"type\",\n \"status\",\n \"content\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\",\n \"maxLength\": 70,\n \"description\": \"Unique identifier for the feedback entry\",\n \"examples\": [\n \"1752788100-feedback-blocking-rest-api\",\n \"1752788200-feedback-question-test-coverage\"\n ]\n },\n \"entityType\": {\n \"type\": \"string\",\n \"enum\": [\n \"task\",\n \"execution\",\n \"changelog\",\n \"feedback\",\n \"cycle\"\n ],\n \"description\": \"The type of entity this feedback refers to\"\n },\n \"entityId\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 256,\n \"description\": \"The ID of the entity this feedback refers to.\\nMust match the pattern for its entityType:\\n- task: ^\\\\d{10}-task-[a-z0-9-]{1,50}$\\n- execution: ^\\\\d{10}-exec-[a-z0-9-]{1,50}$\\n- changelog: ^\\\\d{10}-changelog-[a-z0-9-]{1,50}$\\n- feedback: ^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\\n- cycle: ^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\\n\",\n \"examples\": [\n \"1752274500-task-implementar-oauth\",\n \"1752642000-exec-subtarea-9-4\",\n \"1752788100-feedback-blocking-rest-api\"\n ]\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"blocking\",\n \"suggestion\",\n \"question\",\n \"approval\",\n \"clarification\",\n \"assignment\"\n ],\n \"description\": \"The semantic intent of the feedback\",\n \"examples\": [\n \"blocking\",\n \"question\",\n \"approval\"\n ]\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"open\",\n \"acknowledged\",\n \"resolved\",\n \"wontfix\"\n ],\n \"description\": \"The lifecycle status of the feedback. \\nNote: FeedbackRecords are immutable. To change status, create a new feedback \\nthat references this one using entityType: \\\"feedback\\\" and resolvesFeedbackId.\\n\"\n },\n \"content\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 5000,\n \"description\": \"The content of the feedback. Reduced from 10000 to 5000 chars for practical use.\"\n },\n \"assignee\": {\n \"type\": \"string\",\n \"pattern\": \"^(human|agent)(:[a-z0-9-]+)+$\",\n \"maxLength\": 256,\n \"description\": \"Optional. The Actor ID responsible for addressing the feedback (e.g., 'human:maria', 'agent:camilo:cursor')\",\n \"examples\": [\n \"human:maria\",\n \"agent:code-reviewer\",\n \"agent:camilo:cursor\"\n ]\n },\n \"resolvesFeedbackId\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-feedback-[a-z0-9-]{1,50}$\",\n \"maxLength\": 70,\n \"description\": \"Optional. The ID of another feedback record that this one resolves or responds to\",\n \"examples\": [\n \"1752788100-feedback-blocking-rest-api\"\n ]\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": true,\n \"description\": \"Optional structured data for machine consumption.\\nUse this field for domain-specific data that needs to be programmatically processed.\\nCommon use cases: waiver details (fingerprint, ruleId, file, line), approval context, assignment metadata.\\n\",\n \"examples\": [\n {\n \"fingerprint\": \"abc123def456\",\n \"ruleId\": \"PII-001\",\n \"file\": \"src/user.ts\",\n \"line\": 42,\n \"expiresAt\": \"2025-12-31T23:59:59Z\"\n }\n ]\n }\n },\n \"examples\": [\n {\n \"id\": \"1752788100-feedback-blocking-rest-api\",\n \"entityType\": \"execution\",\n \"entityId\": \"1752642000-exec-subtarea-9-4\",\n \"type\": \"blocking\",\n \"status\": \"open\",\n \"content\": \"Esta implementación no cumple el estándar de rutas REST. Los endpoints deben seguir el patrón /api/v1/{resource}/{id}. Actualmente usa /get-user?id=X que no es RESTful.\"\n },\n {\n \"id\": \"1752788200-feedback-rest-api-fixed\",\n \"entityType\": \"feedback\",\n \"entityId\": \"1752788100-feedback-blocking-rest-api\",\n \"type\": \"clarification\",\n \"status\": \"resolved\",\n \"content\": \"Implementada la corrección. Ahora todos los endpoints siguen el estándar REST: GET /api/v1/users/:id, POST /api/v1/users, etc. Tests actualizados y passing.\",\n \"resolvesFeedbackId\": \"1752788100-feedback-blocking-rest-api\"\n },\n {\n \"id\": \"1752788300-feedback-assign-auth-task\",\n \"entityType\": \"task\",\n \"entityId\": \"1752274500-task-implementar-oauth\",\n \"type\": \"assignment\",\n \"status\": \"open\",\n \"content\": \"Asignando esta tarea a María por su experiencia con OAuth2. Prioridad alta para el sprint actual.\",\n \"assignee\": \"human:maria\"\n },\n {\n \"id\": \"1752788400-feedback-question-test-coverage\",\n \"entityType\": \"task\",\n \"entityId\": \"1752274500-task-implementar-oauth\",\n \"type\": \"question\",\n \"status\": \"open\",\n \"content\": \"¿Cuál es el nivel de test coverage esperado para esta feature? El spec no lo menciona explícitamente. ¿Debemos apuntar a 80% como el resto del proyecto?\"\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"task_record_schema.json\",\n \"title\": \"TaskRecord\",\n \"description\": \"Canonical schema for task records as defined in task_protocol.md\",\n \"additionalProperties\": false,\n \"type\": \"object\",\n \"required\": [\n \"id\",\n \"title\",\n \"status\",\n \"priority\",\n \"description\"\n ],\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d{10}-task-[a-z0-9-]{1,50}$\",\n \"maxLength\": 66,\n \"description\": \"Unique identifier for the task (10 timestamp + 1 dash + 4 'task' + 1 dash + max 50 slug = 66 max)\",\n \"examples\": [\n \"1752274500-task-implementar-auth\",\n \"1752347700-task-fix-logging\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"minLength\": 3,\n \"maxLength\": 150,\n \"description\": \"A brief, human-readable title for the task. Used to generate the ID slug.\"\n },\n \"cycleIds\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"^\\\\d{10}-cycle-[a-z0-9-]{1,50}$\",\n \"maxLength\": 67\n },\n \"default\": [],\n \"description\": \"Optional. The IDs of the strategic cycles this task belongs to. (10 timestamp + 1 dash + 5 'cycle' + 1 dash + max 50 slug = 67 max)\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\n \"draft\",\n \"review\",\n \"ready\",\n \"active\",\n \"done\",\n \"archived\",\n \"paused\",\n \"discarded\"\n ],\n \"maxLength\": 40,\n \"description\": \"Current state of the task in the institutional flow\"\n },\n \"priority\": {\n \"type\": \"string\",\n \"enum\": [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\"\n ],\n \"maxLength\": 40,\n \"description\": \"Strategic or tactical priority level\"\n },\n \"description\": {\n \"type\": \"string\",\n \"minLength\": 10,\n \"maxLength\": 22000,\n \"description\": \"Functional, technical or strategic summary of the objective\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-:]+)*$\"\n },\n \"default\": [],\n \"description\": \"Optional. List of key:value tags for categorization and role suggestion (e.g., 'skill:react', 'role:agent:developer').\"\n },\n \"references\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 500\n },\n \"default\": [],\n \"description\": \"Valid links or files, when mentioned\"\n },\n \"notes\": {\n \"type\": \"string\",\n \"minLength\": 0,\n \"maxLength\": 3000,\n \"description\": \"Additional comments, decisions made or added context\"\n }\n },\n \"examples\": [\n {\n \"id\": \"1752274500-task-implement-oauth-flow\",\n \"title\": \"Implement OAuth 2.0 authentication flow\",\n \"status\": \"draft\",\n \"priority\": \"high\",\n \"description\": \"Implement complete OAuth 2.0 flow with GitHub provider. Include token refresh, session management, and secure storage. Must support both web and CLI flows.\",\n \"cycleIds\": [\n \"1752270000-cycle-auth-mvp\"\n ],\n \"tags\": [\n \"skill:security\",\n \"category:feature\",\n \"package:core\"\n ],\n \"references\": [\n \"url:https://docs.github.com/en/apps/oauth-apps/building-oauth-apps\"\n ],\n \"notes\": \"Consider using proven library like passport.js or implement from scratch for learning.\"\n },\n {\n \"id\": \"1752347700-task-fix-memory-leak-indexer\",\n \"title\": \"Fix memory leak in indexer process\",\n \"status\": \"active\",\n \"priority\": \"critical\",\n \"description\": \"Indexer process consuming >2GB RAM after 24h uptime. Profiling shows EventEmitter listeners not being cleaned up properly. Fix leak and add monitoring.\",\n \"cycleIds\": [],\n \"tags\": [\n \"category:bug\",\n \"skill:performance\",\n \"package:core\"\n ],\n \"references\": [\n \"file:packages/core/src/adapters/indexer_adapter/index.ts\",\n \"commit:a1b2c3d4\",\n \"issue:789\"\n ],\n \"notes\": \"Discovered during production monitoring. Affects long-running processes only.\"\n },\n {\n \"id\": \"1752448900-task-add-typescript-linting\",\n \"title\": \"Add TypeScript strict mode and ESLint rules\",\n \"status\": \"done\",\n \"priority\": \"medium\",\n \"description\": \"Enable TypeScript strict mode across all packages. Configure ESLint with recommended rules. Fix all existing violations. Add pre-commit hook.\",\n \"cycleIds\": [\n \"1752440000-cycle-code-quality-q1\"\n ],\n \"tags\": [\n \"category:tooling\",\n \"skill:typescript\",\n \"epic:code-quality\"\n ],\n \"references\": [\n \"pr:123\",\n \"file:.eslintrc.js\",\n \"file:tsconfig.json\"\n ],\n \"notes\": \"Approved by tech lead. All 47 violations fixed in PR #123.\"\n },\n {\n \"id\": \"1752550000-task-research-graphql-migration\",\n \"title\": \"Research GraphQL migration feasibility\",\n \"status\": \"draft\",\n \"priority\": \"low\",\n \"description\": \"Evaluate feasibility of migrating REST API to GraphQL. Document pros/cons, effort estimation, and recommended approach. Focus on developer experience and performance.\",\n \"cycleIds\": [],\n \"tags\": [\n \"category:research\",\n \"skill:graphql\",\n \"skill:backend\"\n ],\n \"references\": []\n }\n ]\n}","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"$id\": \"workflow_schema.json\",\n \"title\": \"WorkflowRecord\",\n \"description\": \"Complete schema for workflow methodology configuration files that define state transitions, signatures, and custom rules\",\n \"type\": \"object\",\n \"required\": [\n \"version\",\n \"name\",\n \"state_transitions\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"$schema\": {\n \"type\": \"string\",\n \"description\": \"JSON Schema reference\"\n },\n \"version\": {\n \"type\": \"string\",\n \"pattern\": \"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+$\",\n \"description\": \"Semantic version of the methodology configuration\"\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100,\n \"description\": \"Human-readable name of the methodology\"\n },\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 500,\n \"description\": \"Brief description of the methodology's purpose and scope\"\n },\n \"state_transitions\": {\n \"type\": \"object\",\n \"description\": \"Defines valid state transitions and their requirements\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"from\",\n \"requires\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"from\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z][a-z0-9_]{0,49}$\"\n },\n \"minItems\": 1,\n \"description\": \"Valid source states for this transition\"\n },\n \"requires\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": \"CLI command that triggers this transition\"\n },\n \"event\": {\n \"type\": \"string\",\n \"description\": \"System event that triggers this transition\"\n },\n \"signatures\": {\n \"type\": \"object\",\n \"description\": \"Signature requirements keyed by role (e.g., 'approver:quality', 'developer:backend')\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"role\",\n \"capability_roles\",\n \"min_approvals\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"role\": {\n \"type\": \"string\",\n \"description\": \"Required signature role\"\n },\n \"capability_roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"minItems\": 1,\n \"description\": \"Required capability roles in actor record\"\n },\n \"min_approvals\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Minimum number of required approvals\"\n },\n \"actor_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"human\",\n \"agent\"\n ],\n \"description\": \"Optional: restrict to specific actor type\"\n },\n \"specific_actors\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"Optional: specific actors that can sign\"\n }\n }\n }\n },\n \"custom_rules\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n },\n \"description\": \"List of custom rule identifiers to validate\"\n }\n }\n }\n }\n }\n },\n \"custom_rules\": {\n \"type\": \"object\",\n \"description\": \"Definitions for custom validation rules\",\n \"additionalProperties\": {\n \"type\": \"object\",\n \"required\": [\n \"description\",\n \"validation\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 200,\n \"description\": \"Human-readable description of the rule\"\n },\n \"validation\": {\n \"type\": \"string\",\n \"enum\": [\n \"assignment_required\",\n \"sprint_capacity\",\n \"epic_complexity\",\n \"custom\"\n ],\n \"description\": \"Validation type identifier\"\n },\n \"parameters\": {\n \"type\": \"object\",\n \"description\": \"Optional parameters for the validation rule\"\n },\n \"expression\": {\n \"type\": \"string\",\n \"description\": \"Inline validation expression for 'custom' validation type. Implementation determines the runtime and language. Must return boolean or Promise<boolean>.\"\n },\n \"module_path\": {\n \"type\": \"string\",\n \"description\": \"Path to external module for custom validation (alternative to expression)\"\n }\n }\n }\n },\n \"agent_integration\": {\n \"type\": \"object\",\n \"description\": \"Optional agent automation configuration for methodology\",\n \"additionalProperties\": false,\n \"properties\": {\n \"description\": {\n \"type\": \"string\",\n \"maxLength\": 200,\n \"description\": \"Brief description of the agent integration\"\n },\n \"required_agents\": {\n \"type\": \"array\",\n \"description\": \"References to agents required for this methodology. Agent details (engine, knowledge, etc.) live in their AgentRecord.\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"triggers\"\n ],\n \"anyOf\": [\n {\n \"required\": [\n \"id\"\n ]\n },\n {\n \"required\": [\n \"required_roles\"\n ]\n }\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"pattern\": \"^agent:[a-z0-9:-]+$\",\n \"description\": \"Specific agent ID. References an existing AgentRecord.\"\n },\n \"required_roles\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9-]+(:[a-z0-9-]+)*$\"\n },\n \"minItems\": 1,\n \"description\": \"Required capability roles. Matches any agent with these roles (from ActorRecord).\"\n },\n \"triggers\": {\n \"type\": \"array\",\n \"description\": \"When this agent activates within this methodology\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"event\",\n \"action\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"event\": {\n \"type\": \"string\",\n \"description\": \"Event that triggers the agent\"\n },\n \"action\": {\n \"type\": \"string\",\n \"description\": \"Action the agent should perform\"\n },\n \"cron\": {\n \"type\": \"string\",\n \"description\": \"Cron expression for scheduled triggers\"\n }\n }\n }\n }\n }\n }\n }\n }\n }\n },\n \"examples\": [\n {\n \"version\": \"1.0.0\",\n \"name\": \"Simple Kanban\",\n \"description\": \"Basic workflow for small teams\",\n \"state_transitions\": {\n \"review\": {\n \"from\": [\n \"draft\"\n ],\n \"requires\": {\n \"command\": \"gitgov task submit\"\n }\n },\n \"ready\": {\n \"from\": [\n \"review\"\n ],\n \"requires\": {\n \"command\": \"gitgov task approve\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:product\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"active\": {\n \"from\": [\n \"ready\"\n ],\n \"requires\": {\n \"event\": \"first_execution_record_created\"\n }\n },\n \"done\": {\n \"from\": [\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task complete\"\n }\n }\n }\n },\n {\n \"version\": \"1.0.0\",\n \"name\": \"GitGovernance Default Methodology\",\n \"description\": \"Standard GitGovernance workflow with quality gates and agent collaboration\",\n \"state_transitions\": {\n \"review\": {\n \"from\": [\n \"draft\"\n ],\n \"requires\": {\n \"command\": \"gitgov task submit\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"submitter\",\n \"capability_roles\": [\n \"author\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"ready\": {\n \"from\": [\n \"review\"\n ],\n \"requires\": {\n \"command\": \"gitgov task approve\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:product\"\n ],\n \"min_approvals\": 1\n },\n \"design\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:design\"\n ],\n \"min_approvals\": 1\n },\n \"quality\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"active\": {\n \"from\": [\n \"ready\",\n \"paused\"\n ],\n \"requires\": {\n \"event\": \"first_execution_record_created\",\n \"custom_rules\": [\n \"task_must_have_valid_assignment_for_executor\"\n ]\n }\n },\n \"done\": {\n \"from\": [\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task complete\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"approver\",\n \"capability_roles\": [\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n },\n \"archived\": {\n \"from\": [\n \"done\"\n ],\n \"requires\": {\n \"event\": \"changelog_record_created\"\n }\n },\n \"paused\": {\n \"from\": [\n \"active\",\n \"review\"\n ],\n \"requires\": {\n \"event\": \"feedback_blocking_created\"\n }\n },\n \"discarded\": {\n \"from\": [\n \"ready\",\n \"active\"\n ],\n \"requires\": {\n \"command\": \"gitgov task cancel\",\n \"signatures\": {\n \"__default__\": {\n \"role\": \"canceller\",\n \"capability_roles\": [\n \"approver:product\",\n \"approver:quality\"\n ],\n \"min_approvals\": 1\n }\n }\n }\n }\n },\n \"custom_rules\": {\n \"task_must_have_valid_assignment_for_executor\": {\n \"description\": \"Task must have a valid assignment before execution can begin\",\n \"validation\": \"assignment_required\"\n }\n }\n }\n ]\n}","/**\n * GitGovernance Protocol Schemas\n * \n * Auto-generated from blueprints. Do not edit manually.\n * Run 'pnpm sync:schemas' to update.\n */\n\nimport actorRecordSchema from \"./actor_record_schema.json\";\nimport agentRecordSchema from \"./agent_record_schema.json\";\nimport changelogRecordSchema from \"./changelog_record_schema.json\";\nimport cycleRecordSchema from \"./cycle_record_schema.json\";\nimport embeddedMetadataSchema from \"./embedded_metadata_schema.json\";\nimport executionRecordSchema from \"./execution_record_schema.json\";\nimport feedbackRecordSchema from \"./feedback_record_schema.json\";\nimport taskRecordSchema from \"./task_record_schema.json\";\nimport workflowRecordSchema from \"./workflow_record_schema.json\";\n\n/**\n * All GitGovernance protocol schemas\n */\nexport const Schemas = {\n ActorRecord: actorRecordSchema,\n AgentRecord: agentRecordSchema,\n ChangelogRecord: changelogRecordSchema,\n CycleRecord: cycleRecordSchema,\n EmbeddedMetadata: embeddedMetadataSchema,\n ExecutionRecord: executionRecordSchema,\n FeedbackRecord: feedbackRecordSchema,\n TaskRecord: taskRecordSchema,\n WorkflowRecord: workflowRecordSchema,\n} as const;\n\n/**\n * Schema names for type safety\n */\nexport type SchemaName = \n | \"ActorRecord\"\n | \"AgentRecord\"\n | \"ChangelogRecord\"\n | \"CycleRecord\"\n | \"EmbeddedMetadata\"\n | \"ExecutionRecord\"\n | \"FeedbackRecord\"\n | \"TaskRecord\"\n | \"WorkflowRecord\";\n\n/**\n * Get a schema by name\n */\nexport function getSchema(name: SchemaName) {\n return Schemas[name];\n}\n\n/**\n * Get all schema names\n */\nexport function getSchemaNames(): SchemaName[] {\n return Object.keys(Schemas) as SchemaName[];\n}\n\n/**\n * Check if a schema exists\n */\nexport function hasSchema(name: string): name is SchemaName {\n return name in Schemas;\n}\n","import Ajv from \"ajv\";\nimport type { ValidateFunction } from \"ajv\";\nimport addFormats from \"ajv-formats\";\n\n// Direct import from generated schemas\nimport { Schemas } from \"./generated\";\n\n/**\n * Singleton cache for schema validators to avoid repeated I/O and AJV compilation.\n * Improves performance by caching compiled validators for schema files.\n */\nexport class SchemaValidationCache {\n private static schemaValidators = new Map<string, ValidateFunction>();\n private static ajv: Ajv | null = null;\n\n /**\n * Gets or creates a cached validator for a schema object.\n * @param schema The schema object (already parsed YAML/JSON)\n * @returns Compiled AJV validator function\n */\n static getValidatorFromSchema<T = unknown>(schema: object): ValidateFunction<T> {\n // Create a stable key from the schema object\n const schemaKey = JSON.stringify(schema);\n\n if (!this.schemaValidators.has(schemaKey)) {\n // Initialize AJV instance if not already done\n if (!this.ajv) {\n this.ajv = new Ajv({ allErrors: true });\n addFormats(this.ajv);\n\n // Pre-load all schemas for reference resolution\n this.preloadSchemas();\n }\n\n // Remove $id temporarily to avoid conflicts with preloaded schemas\n // (This doesn't modify the original schema object)\n const { $id, ...schemaWithoutId } = schema as any;\n\n // Compile schema directly - AJV will resolve $ref using preloaded aliases\n const validator = this.ajv.compile(schemaWithoutId);\n this.schemaValidators.set(schemaKey, validator);\n }\n\n return this.schemaValidators.get(schemaKey)! as ValidateFunction<T>;\n }\n\n /**\n * Pre-loads referenced schema files for $ref resolution.\n * Uses direct imports and dynamic iteration.\n */\n private static preloadSchemas(): void {\n if (!this.ajv) return;\n\n try {\n // Map schema names to their expected ref aliases\n const schemaRefMap: Record<string, string> = {\n 'ActorRecord': 'ref:actor_record_schema',\n 'AgentRecord': 'ref:agent_record_schema',\n 'ChangelogRecord': 'ref:changelog_record_schema',\n 'CycleRecord': 'ref:cycle_record_schema',\n 'ExecutionRecord': 'ref:execution_record_schema',\n 'FeedbackRecord': 'ref:feedback_record_schema',\n 'TaskRecord': 'ref:task_record_schema',\n 'WorkflowRecord': 'ref:workflow_record_schema'\n };\n\n // Register schemas with correct aliases\n Object.entries(Schemas).forEach(([name, schema]) => {\n if (name !== 'EmbeddedMetadata' && schemaRefMap[name]) {\n const refName = schemaRefMap[name];\n this.ajv!.addSchema(schema, refName);\n }\n });\n } catch {\n // If preloading fails, continue without it\n }\n }\n\n /**\n * Clears the cache (useful for testing or schema updates).\n */\n static clearCache(): void {\n this.schemaValidators.clear();\n this.ajv = null;\n }\n\n /**\n * Gets cache statistics for monitoring.\n */\n static getCacheStats(): { cachedSchemas: number } {\n return {\n cachedSchemas: this.schemaValidators.size\n };\n }\n}\n","import { generateKeyPair, sign, verify, createHash, randomBytes } from \"crypto\";\nimport { promisify } from \"util\";\nimport { calculatePayloadChecksum } from \"./checksum\";\nimport type { GitGovRecordPayload, Signature } from \"../record_types\";\nimport { createLogger } from \"../logger\";\nconst logger = createLogger(\"[CryptoModule] \");\nconst generateKeyPairAsync = promisify(generateKeyPair);\n\n/**\n * Generates a new Ed25519 key pair.\n * @returns A promise that resolves to an object with publicKey and privateKey in base64 format.\n * \n * The publicKey is the raw Ed25519 key (32 bytes -> 44 chars in base64).\n * The privateKey is stored in PKCS8 PEM format for compatibility.\n * \n * Note: Node.js crypto does not support 'raw' format directly for Ed25519,\n * so we extract the raw 32-byte key from the SPKI DER encoding (RFC 8410).\n * SPKI DER structure: [algorithm identifier (12 bytes)] + [raw public key (32 bytes)]\n */\nexport async function generateKeys(): Promise<{ publicKey: string; privateKey: string; }> {\n const { publicKey, privateKey } = await generateKeyPairAsync('ed25519', {\n publicKeyEncoding: { type: 'spki', format: 'der' },\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n });\n\n // Extract raw Ed25519 public key (last 32 bytes of SPKI DER format)\n const rawPublicKey = publicKey.subarray(-32);\n\n return {\n publicKey: rawPublicKey.toString('base64'), // 32 bytes -> 44 chars\n privateKey: Buffer.from(privateKey).toString('base64'),\n };\n}\n\n/**\n * Creates a signature for a given payload.\n */\nexport function signPayload(\n payload: GitGovRecordPayload,\n privateKey: string,\n keyId: string,\n role: string,\n notes: string,\n): Signature {\n const payloadChecksum = calculatePayloadChecksum(payload);\n const timestamp = Math.floor(Date.now() / 1000);\n const digest = `${payloadChecksum}:${keyId}:${role}:${notes}:${timestamp}`;\n\n // Per the blueprint, sign the SHA-256 hash of the digest\n const digestHash = createHash('sha256').update(digest).digest();\n\n const signature = sign(null, digestHash, {\n key: Buffer.from(privateKey, 'base64'),\n type: 'pkcs8',\n format: 'pem'\n });\n\n return {\n keyId,\n role,\n notes,\n signature: signature.toString('base64'),\n timestamp,\n };\n}\n\n/**\n * Verifies all signatures on a record.\n * \n * Reconstructs SPKI DER format from raw Ed25519 key for verification.\n */\nexport async function verifySignatures(\n record: { header: { payloadChecksum: string, signatures: Signature[] }, payload: GitGovRecordPayload },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<boolean> {\n for (const signature of record.header.signatures) {\n const publicKeyBase64 = await getActorPublicKey(signature.keyId);\n if (!publicKeyBase64) {\n // Use debug level instead of warn to reduce noise during indexer validation\n // The indexer already captures these errors in its integrity report\n logger.debug(`Public key not found for actor: ${signature.keyId}`);\n return false;\n }\n\n const digest = `${record.header.payloadChecksum}:${signature.keyId}:${signature.role}:${signature.notes}:${signature.timestamp}`;\n const digestHash = createHash('sha256').update(digest).digest();\n\n // Reconstruct SPKI DER from raw Ed25519 public key (RFC 8410)\n // SPKI DER structure: [algorithm identifier (12 bytes)] + [raw key (32 bytes)]\n const algorithmIdentifier = Buffer.from([\n 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65,\n 0x70, 0x03, 0x21, 0x00\n ]);\n const rawPublicKey = Buffer.from(publicKeyBase64, 'base64');\n const spkiPublicKey = Buffer.concat([algorithmIdentifier, rawPublicKey]);\n\n const isValid = verify(\n null,\n digestHash,\n {\n key: spkiPublicKey,\n type: 'spki',\n format: 'der'\n },\n Buffer.from(signature.signature, 'base64')\n );\n\n if (!isValid) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Generates a mock signature with valid Ed25519 format.\n * Used as fallback when private key is not available.\n *\n * [EARS-7] Returns a base64-encoded string of 64 random bytes (86 chars + ==)\n */\nexport function generateMockSignature(): string {\n return randomBytes(64).toString('base64');\n}\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { EmbeddedMetadataRecord } from '../record_types/embedded.types';\nimport type { GitGovRecordPayload } from '../record_types/common.types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { calculatePayloadChecksum } from '../crypto/checksum';\nimport { verifySignatures } from '../crypto/signatures';\nimport { DetailedValidationError, ChecksumMismatchError, SignatureVerificationError } from './common';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for EmbeddedMetadata wrapper\n */\nexport function validateEmbeddedMetadataSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.EmbeddedMetadata);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid EmbeddedMetadataRecord\n */\nexport function isEmbeddedMetadataRecord<T extends GitGovRecordPayload>(data: unknown): data is EmbeddedMetadataRecord<T> {\n const [isValid] = validateEmbeddedMetadataSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation for EmbeddedMetadataRecord with formatted errors\n */\nexport function validateEmbeddedMetadataDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateEmbeddedMetadataSchema(data);\n\n const formattedErrors = ajvErrors?.map((error: ErrorObject) => ({\n field: error.instancePath || error.schemaPath,\n message: error.message || 'Validation failed',\n value: error.data\n })) || [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n/**\n * Full validation for EmbeddedMetadataRecord including schema, checksum, and signatures\n */\nexport async function validateFullEmbeddedMetadataRecord<T extends GitGovRecordPayload>(\n record: EmbeddedMetadataRecord<T>,\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation - validate the entire record structure\n const [isValidSchema, errors] = validateEmbeddedMetadataSchema(record);\n if (!isValidSchema) {\n const formattedErrors = errors?.map(error => ({\n field: error.instancePath || error.schemaPath,\n message: error.message || 'Validation failed',\n value: error.data\n })) || [];\n\n throw new DetailedValidationError('EmbeddedMetadata', formattedErrors);\n }\n\n // 2. Checksum Validation\n const expectedChecksum = calculatePayloadChecksum(record.payload);\n if (expectedChecksum !== record.header.payloadChecksum) {\n throw new ChecksumMismatchError();\n }\n\n // 3. Signature Verification\n const areSignaturesValid = await verifySignatures(\n record,\n getActorPublicKey\n );\n if (!areSignaturesValid) {\n throw new SignatureVerificationError();\n }\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ActorRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { DetailedValidationError } from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from \"../record_schemas\";\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\n\n// --- Schema Validation ---\nconst actorSchema = Schemas.ActorRecord;\n\nexport function validateActorRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(actorSchema);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\nexport function isActorRecord(data: unknown): data is ActorRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(actorSchema);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates an ActorRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateActorRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateActorRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of an ActorRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the actor payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullActorRecord(\n record: GitGovRecord & { payload: ActorRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateActorRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ActorRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { ActorRecord, GitGovActorRecord } from \"../record_types\";\nimport { validateActorRecordDetailed } from \"../record_validations/actor_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { generateActorId } from \"../utils/id_generator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\n\n/**\n * Creates a new, fully-formed ActorRecord with validation.\n */\nexport function createActorRecord(\n payload: Partial<ActorRecord>\n): ActorRecord {\n // Build actor with defaults for optional fields\n const actor: ActorRecord = {\n id: payload.id || generateActorId(payload.type || 'human', payload.displayName || ''),\n type: payload.type || 'human' as const,\n displayName: payload.displayName || '',\n publicKey: payload.publicKey || '',\n roles: payload.roles || ['author'] as [string, ...string[]],\n status: payload.status || 'active',\n ...payload,\n } as ActorRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateActorRecordDetailed(actor);\n if (!validation.isValid) {\n throw new DetailedValidationError('ActorRecord', validation.errors);\n }\n\n return actor;\n}\n\n/**\n * Loads and validates an existing ActorRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ActorRecord).\n * \n * @param data - Unknown data to validate as GitGovActorRecord\n * @returns GitGovActorRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadActorRecord(data: unknown): GitGovActorRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ActorRecord)', embeddedValidation.errors);\n }\n \n // Then validate specific ActorRecord payload\n const record = data as GitGovActorRecord;\n const payloadValidation = validateActorRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ActorRecord payload', payloadValidation.errors);\n }\n \n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { AgentRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { DetailedValidationError, SchemaValidationError } from \"./common\";\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from '../record_schemas';\nimport type { ActorRecord } from \"../record_types\";\n\n// --- Schema Validation ---\nexport function validateAgentRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.AgentRecord);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\nexport function isAgentRecord(data: unknown): data is AgentRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.AgentRecord);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates an AgentRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateAgentRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateAgentRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of an AgentRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the agent payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullAgentRecord(\n record: GitGovRecord & { payload: AgentRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateAgentRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('AgentRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n\n/**\n * Validates that an AgentRecord has a valid relationship with its corresponding ActorRecord,\n * including succession chain resolution for key rotation scenarios.\n * \n * @param agentRecord The AgentRecord to validate\n * @param getEffectiveActor Function to get the effective ActorRecord (with succession resolution)\n */\nexport async function validateAgentActorRelationship(\n agentRecord: AgentRecord,\n getEffectiveActor: (agentId: string) => Promise<ActorRecord | null>\n): Promise<void> {\n const effectiveActor = await getEffectiveActor(agentRecord.id);\n\n if (!effectiveActor) {\n throw new SchemaValidationError(\n `No active ActorRecord found for AgentRecord ${agentRecord.id}. AgentRecord requires corresponding ActorRecord.`\n );\n }\n\n if (effectiveActor.type !== 'agent') {\n throw new SchemaValidationError(\n `ActorRecord ${effectiveActor.id} must be of type 'agent' to support AgentRecord ${agentRecord.id}.`\n );\n }\n\n if (effectiveActor.status !== 'active') {\n throw new SchemaValidationError(\n `ActorRecord succession chain for ${agentRecord.id} does not resolve to an active actor. Current effective actor: ${effectiveActor.id} (status: ${effectiveActor.status}).`\n );\n }\n}\n","import type { AgentRecord, GitGovAgentRecord } from \"../record_types\";\nimport { validateAgentRecordDetailed } from \"../record_validations/agent_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\n\n/**\n * Creates a new, fully-formed AgentRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial AgentRecord payload with optional typed metadata\n * @returns AgentRecord<TMetadata> - The validated AgentRecord with preserved metadata type\n */\nexport function createAgentRecord<TMetadata extends object = object>(\n payload: Partial<AgentRecord<TMetadata>>\n): AgentRecord<TMetadata> {\n // Build agent with defaults for optional fields\n const agent = {\n id: payload.id || '',\n engine: payload.engine || { type: 'local' as const },\n status: payload.status || 'active',\n triggers: payload.triggers || [],\n knowledge_dependencies: payload.knowledge_dependencies || [],\n prompt_engine_requirements: payload.prompt_engine_requirements || {},\n metadata: payload.metadata,\n ...payload,\n } as AgentRecord<TMetadata>;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateAgentRecordDetailed(agent);\n if (!validation.isValid) {\n throw new DetailedValidationError('AgentRecord', validation.errors);\n }\n\n return agent;\n}\n\n/**\n * Loads and validates an existing AgentRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (AgentRecord).\n * \n * @param data - Unknown data to validate as GitGovAgentRecord\n * @returns GitGovAgentRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadAgentRecord(data: unknown): GitGovAgentRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (AgentRecord)', embeddedValidation.errors);\n }\n \n // Then validate specific AgentRecord payload\n const record = data as GitGovAgentRecord;\n const payloadValidation = validateAgentRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('AgentRecord payload', payloadValidation.errors);\n }\n \n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { TaskRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { Schemas } from '../record_schemas';\nimport {\n DetailedValidationError\n} from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\n\n// --- Schema Validation ---\nexport function validateTaskRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.TaskRecord);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\n/**\n * Type guard to check if data is a valid TaskRecord.\n */\nexport function isTaskRecord(data: unknown): data is TaskRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(Schemas.TaskRecord);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates a TaskRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateTaskRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateTaskRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of a TaskRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the task payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullTaskRecord(\n record: GitGovRecord & { payload: TaskRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateTaskRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('TaskRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { TaskRecord, GitGovTaskRecord } from \"../record_types\";\nimport { validateTaskRecordDetailed } from \"../record_validations/task_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\nimport { generateTaskId } from \"../utils/id_generator\";\n\n/**\n * Creates a new, fully-formed TaskRecord with validation.\n */\nexport function createTaskRecord(\n payload: Partial<TaskRecord>\n): TaskRecord {\n // Generate timestamp for ID if not provided\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build task with defaults for optional fields\n const task: TaskRecord = {\n id: payload.id || generateTaskId(payload.title || '', timestamp),\n title: payload.title || '',\n status: payload.status || 'draft',\n priority: payload.priority || 'medium',\n description: payload.description || '',\n tags: payload.tags || [],\n cycleIds: payload.cycleIds,\n references: payload.references,\n notes: payload.notes,\n ...payload,\n } as TaskRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateTaskRecordDetailed(task);\n if (!validation.isValid) {\n throw new DetailedValidationError('TaskRecord', validation.errors);\n }\n\n return task;\n}\n\n/**\n * Loads and validates an existing TaskRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (TaskRecord).\n * \n * @param data - Unknown data to validate as GitGovTaskRecord\n * @returns GitGovTaskRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadTaskRecord(data: unknown): GitGovTaskRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (TaskRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific TaskRecord payload\n const record = data as GitGovTaskRecord;\n const payloadValidation = validateTaskRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('TaskRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { CycleRecord } from \"../record_types\";\nimport type { GitGovRecord } from \"../record_types\";\nimport { SchemaValidationCache } from \"../record_schemas/schema_cache\";\nimport { DetailedValidationError } from \"./common\";\nimport type { ValidationResult } from './errors';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from \"../record_schemas\";\n\n// --- Schema Validation ---\nconst cycleSchema = Schemas.CycleRecord;\n\nexport function validateCycleRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(cycleSchema);\n const isValid = validateSchema(data) as boolean;\n return [isValid, validateSchema.errors];\n}\n\n/**\n * Type guard to check if data is a valid CycleRecord.\n */\nexport function isCycleRecord(data: unknown): data is CycleRecord {\n const validateSchema = SchemaValidationCache.getValidatorFromSchema(cycleSchema);\n return validateSchema(data) as boolean;\n}\n\n/**\n * Validates a CycleRecord and returns detailed validation result.\n * Use this in factories and adapters for comprehensive error reporting.\n */\nexport function validateCycleRecordDetailed(data: unknown): ValidationResult {\n const [isValid, ajvErrors] = validateCycleRecordSchema(data);\n\n const formattedErrors = ajvErrors ? ajvErrors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n })) : [];\n\n return {\n isValid,\n errors: formattedErrors\n };\n}\n\n// --- Full Validation Orchestrator ---\n/**\n * Performs a complete validation of a CycleRecord, including schema,\n * checksum, and signature checks.\n * @param record The full GitGovRecord containing the cycle payload.\n * @param getActorPublicKey A function to retrieve the public key for a given actor ID.\n */\nexport async function validateFullCycleRecord(\n record: GitGovRecord & { payload: CycleRecord },\n getActorPublicKey: (keyId: string) => Promise<string | null>\n): Promise<void> {\n // 1. Schema Validation\n const [isValidSchema, errors] = validateCycleRecordSchema(record.payload);\n if (!isValidSchema) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('CycleRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getActorPublicKey);\n}\n","import type { CycleRecord, GitGovCycleRecord } from \"../record_types\";\nimport { validateCycleRecordDetailed } from \"../record_validations/cycle_validator\";\nimport { validateEmbeddedMetadataDetailed } from \"../record_validations/embedded_metadata_validator\";\nimport { DetailedValidationError } from \"../record_validations/common\";\nimport { generateCycleId } from \"../utils/id_generator\";\n\n/**\n * Creates a new, fully-formed CycleRecord with validation.\n */\nexport function createCycleRecord(\n payload: Partial<CycleRecord>\n): CycleRecord {\n // Generate timestamp for ID if not provided\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build cycle with defaults for optional fields\n const cycle: CycleRecord = {\n id: payload.id || generateCycleId(payload.title || '', timestamp),\n title: payload.title || '',\n status: payload.status || 'planning',\n taskIds: payload.taskIds || [], // EARS-21: Default empty array\n childCycleIds: payload.childCycleIds,\n tags: payload.tags,\n notes: payload.notes,\n ...payload,\n } as CycleRecord;\n\n // Use validator to check complete schema with detailed errors\n const validation = validateCycleRecordDetailed(cycle);\n if (!validation.isValid) {\n throw new DetailedValidationError('CycleRecord', validation.errors);\n }\n\n return cycle;\n}\n\n/**\n * Loads and validates an existing CycleRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (CycleRecord).\n * \n * @param data - Unknown data to validate as GitGovCycleRecord\n * @returns GitGovCycleRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadCycleRecord(data: unknown): GitGovCycleRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (CycleRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific CycleRecord payload\n const record = data as GitGovCycleRecord;\n const payloadValidation = validateCycleRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('CycleRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ExecutionRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for ExecutionRecord payload\n */\nexport function validateExecutionRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.ExecutionRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid ExecutionRecord\n */\nexport function isExecutionRecord(data: unknown): data is ExecutionRecord {\n const [isValid] = validateExecutionRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateExecutionRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateExecutionRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullExecutionRecord(\n record: GitGovRecord & { payload: ExecutionRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateExecutionRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ExecutionRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { ExecutionRecord, GitGovExecutionRecord } from '../record_types';\nimport { generateExecutionId } from '../utils/id_generator';\nimport { validateExecutionRecordDetailed } from '../record_validations/execution_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete ExecutionRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial ExecutionRecord payload with optional typed metadata\n * @returns ExecutionRecord<TMetadata> - The validated ExecutionRecord with preserved metadata type\n *\n * @example\n * interface AuditMetadata { scannedFiles: number; }\n * const record = createExecutionRecord<AuditMetadata>({\n * taskId: '1752274500-task-audit',\n * result: 'Audit complete',\n * metadata: { scannedFiles: 245 }\n * });\n * // record.metadata?.scannedFiles is typed as number\n */\nexport function createExecutionRecord<TMetadata extends object = object>(\n payload: Partial<ExecutionRecord<TMetadata>>\n): ExecutionRecord<TMetadata> {\n const timestamp = Math.floor(Date.now() / 1000);\n\n const execution = {\n id: payload.id || generateExecutionId(payload.title || 'execution', timestamp),\n taskId: payload.taskId || '',\n result: payload.result || '',\n type: payload.type,\n title: payload.title,\n notes: payload.notes,\n references: payload.references,\n metadata: payload.metadata,\n } as ExecutionRecord<TMetadata>;\n\n // Validate the complete execution record\n const validation = validateExecutionRecordDetailed(execution);\n if (!validation.isValid) {\n throw new DetailedValidationError('ExecutionRecord', validation.errors);\n }\n\n return execution;\n}\n\n/**\n * Loads and validates an existing ExecutionRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ExecutionRecord).\n * \n * @param data - Unknown data to validate as GitGovExecutionRecord\n * @returns GitGovExecutionRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadExecutionRecord(data: unknown): GitGovExecutionRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ExecutionRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific ExecutionRecord payload\n const record = data as GitGovExecutionRecord;\n const payloadValidation = validateExecutionRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ExecutionRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { ChangelogRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for ChangelogRecord payload\n */\nexport function validateChangelogRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.ChangelogRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid ChangelogRecord\n */\nexport function isChangelogRecord(data: unknown): data is ChangelogRecord {\n const [isValid] = validateChangelogRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateChangelogRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateChangelogRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullChangelogRecord(\n record: GitGovRecord & { payload: ChangelogRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateChangelogRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('ChangelogRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { ChangelogRecord, GitGovChangelogRecord } from '../record_types';\nimport { validateChangelogRecordDetailed } from '../record_validations/changelog_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete ChangelogRecord with validation (Protocol v2)\n * \n * @param payload - Partial ChangelogRecord payload\n * @returns ChangelogRecord - The validated ChangelogRecord\n */\nexport function createChangelogRecord(payload: Partial<ChangelogRecord>): ChangelogRecord {\n const timestamp = Math.floor(Date.now() / 1000);\n\n // Build changelog with required fields\n const changelog: ChangelogRecord = {\n // Required fields\n id: payload.id || '',\n title: payload.title || '',\n description: payload.description || '',\n relatedTasks: (payload.relatedTasks || []) as [string, ...string[]],\n completedAt: payload.completedAt || timestamp,\n\n // Optional fields (only include if provided)\n ...(payload.relatedCycles && { relatedCycles: payload.relatedCycles }),\n ...(payload.relatedExecutions && { relatedExecutions: payload.relatedExecutions }),\n ...(payload.version && { version: payload.version }),\n ...(payload.tags && { tags: payload.tags }),\n ...(payload.commits && { commits: payload.commits }),\n ...(payload.files && { files: payload.files }),\n ...(payload.notes && { notes: payload.notes })\n };\n\n // Validate the complete changelog record\n const validation = validateChangelogRecordDetailed(changelog);\n if (!validation.isValid) {\n throw new DetailedValidationError('ChangelogRecord', validation.errors);\n }\n\n return changelog;\n}\n\n/**\n * Loads and validates an existing ChangelogRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (ChangelogRecord).\n * \n * @param data - Unknown data to validate as GitGovChangelogRecord\n * @returns GitGovChangelogRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadChangelogRecord(data: unknown): GitGovChangelogRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (ChangelogRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific ChangelogRecord payload\n const record = data as GitGovChangelogRecord;\n const payloadValidation = validateChangelogRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('ChangelogRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","import type { ValidateFunction, ErrorObject } from \"ajv\";\nimport type { FeedbackRecord } from '../record_types';\nimport type { GitGovRecord } from '../record_types';\nimport type { ValidationResult } from './errors';\nimport { SchemaValidationCache } from '../record_schemas/schema_cache';\nimport { DetailedValidationError } from './common';\nimport { validateFullEmbeddedMetadataRecord } from './embedded_metadata_validator';\nimport { Schemas } from '../record_schemas';\n\n/**\n * Schema-based validation for FeedbackRecord payload\n */\nexport function validateFeedbackRecordSchema(\n data: unknown\n): [boolean, ValidateFunction[\"errors\"]] {\n const validator = SchemaValidationCache.getValidatorFromSchema(Schemas.FeedbackRecord);\n const isValid = validator(data);\n\n return [isValid, validator.errors];\n}\n\n/**\n * Type guard to check if data is a valid FeedbackRecord\n */\nexport function isFeedbackRecord(data: unknown): data is FeedbackRecord {\n const [isValid] = validateFeedbackRecordSchema(data);\n return isValid;\n}\n\n/**\n * Detailed validation with field-level error reporting\n */\nexport function validateFeedbackRecordDetailed(data: unknown): ValidationResult {\n const [isValid, errors] = validateFeedbackRecordSchema(data);\n\n if (!isValid && errors) {\n const formattedErrors = errors.map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n\n return {\n isValid: false,\n errors: formattedErrors\n };\n }\n\n return {\n isValid: true,\n errors: []\n };\n}\n\n/**\n * Full validation including checksum and signature verification\n */\nexport async function validateFullFeedbackRecord(\n record: GitGovRecord & { payload: FeedbackRecord },\n getPublicKey: (keyId: string) => Promise<string>\n): Promise<void> {\n // 1. Validate payload schema\n const [isValid, errors] = validateFeedbackRecordSchema(record.payload);\n if (!isValid) {\n const formattedErrors = (errors || []).map((error: ErrorObject) => ({\n field: error.instancePath?.replace('/', '') || error.params?.['missingProperty'] || 'root',\n message: error.message || 'Unknown validation error',\n value: error.data\n }));\n throw new DetailedValidationError('FeedbackRecord', formattedErrors);\n }\n\n // 2. Embedded Metadata Validation (header + wrapper)\n await validateFullEmbeddedMetadataRecord(record, getPublicKey);\n}\n","import type { FeedbackRecord, GitGovFeedbackRecord } from '../record_types';\nimport { generateFeedbackId } from '../utils/id_generator';\nimport { validateFeedbackRecordDetailed } from '../record_validations/feedback_validator';\nimport { validateEmbeddedMetadataDetailed } from '../record_validations/embedded_metadata_validator';\nimport { DetailedValidationError } from '../record_validations/common';\n\n/**\n * Creates a complete FeedbackRecord with validation.\n *\n * The factory is generic to preserve the metadata type for compile-time safety.\n *\n * @param payload - Partial FeedbackRecord payload with optional typed metadata\n * @returns FeedbackRecord<TMetadata> - The validated FeedbackRecord with preserved metadata type\n */\nexport function createFeedbackRecord<TMetadata extends object = object>(\n payload: Partial<FeedbackRecord<TMetadata>>\n): FeedbackRecord<TMetadata> {\n const timestamp = Math.floor(Date.now() / 1000);\n\n const feedback = {\n id: payload.id || generateFeedbackId(payload.content || 'feedback', timestamp),\n entityType: payload.entityType || 'task',\n entityId: payload.entityId || '',\n type: payload.type || 'question',\n status: payload.status || (payload.type === 'assignment' ? 'resolved' : 'open'),\n content: payload.content || '',\n assignee: payload.assignee,\n resolvesFeedbackId: payload.resolvesFeedbackId,\n metadata: payload.metadata,\n } as FeedbackRecord<TMetadata>;\n\n // Validate the complete feedback record\n const validation = validateFeedbackRecordDetailed(feedback);\n if (!validation.isValid) {\n throw new DetailedValidationError('FeedbackRecord', validation.errors);\n }\n\n return feedback;\n}\n\n/**\n * Loads and validates an existing FeedbackRecord from untrusted data.\n * Used by RecordStore to validate records when reading from disk.\n * Validates both header (embedded metadata) and payload (FeedbackRecord).\n * \n * @param data - Unknown data to validate as GitGovFeedbackRecord\n * @returns GitGovFeedbackRecord - The validated complete record\n * @throws DetailedValidationError if validation fails\n */\nexport function loadFeedbackRecord(data: unknown): GitGovFeedbackRecord {\n // First validate complete record structure (header + payload)\n const embeddedValidation = validateEmbeddedMetadataDetailed(data);\n if (!embeddedValidation.isValid) {\n throw new DetailedValidationError('GitGovRecord (FeedbackRecord)', embeddedValidation.errors);\n }\n\n // Then validate specific FeedbackRecord payload\n const record = data as GitGovFeedbackRecord;\n const payloadValidation = validateFeedbackRecordDetailed(record.payload);\n if (!payloadValidation.isValid) {\n throw new DetailedValidationError('FeedbackRecord payload', payloadValidation.errors);\n }\n\n return record;\n}\n\n","/**\n * FsLintModule - Filesystem-aware Validation\n *\n * This module wraps the pure LintModule and adds filesystem operations:\n * - Directory scanning for record discovery (EARS-A1)\n * - File naming validation (EARS-B1, EARS-B2)\n * - Backup creation and restoration (EARS-C1, EARS-C2)\n * - Delegation to LintModule core (EARS-D1)\n * - Schema version detection (EARS-E1)\n * - Error filtering (EARS-F1)\n *\n * @see fs_lint_module.md for EARS specifications\n * @module lint/fs\n */\n\n/**\n * [EARS-F1] Ajv error message patterns for oneOf/if-then-else schema validation.\n * These are standard messages from Ajv when validating JSON Schema with oneOf + if/then/else.\n *\n * When a record has additionalProperties errors, Ajv also generates redundant errors\n * from all the oneOf branches that don't match. These should be filtered out.\n *\n * @see https://ajv.js.org/api.html#validation-errors\n */\nconst AJV_ONEOF_ERROR_PATTERNS = {\n /** Message from \"else: false\" in if/then/else schema */\n BOOLEAN_SCHEMA_FALSE: 'boolean schema is false',\n /** Message when if condition doesn't match \"else\" */\n MUST_MATCH_ELSE: 'must match \"else\" schema',\n /** Message when if condition doesn't match \"then\" */\n MUST_MATCH_THEN: 'must match \"then\" schema',\n /** Path prefix for oneOf errors */\n ONEOF_PATH: '#/oneOf/',\n} as const;\n\n/**\n * [EARS-F1] Checks if an error message is a redundant oneOf/if-then-else error from Ajv.\n * These errors are noise when the root cause is additionalProperties.\n */\nfunction isRedundantOneOfError(message: string): boolean {\n return (\n message.includes(AJV_ONEOF_ERROR_PATTERNS.BOOLEAN_SCHEMA_FALSE) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.MUST_MATCH_ELSE) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.MUST_MATCH_THEN) ||\n message.includes(AJV_ONEOF_ERROR_PATTERNS.ONEOF_PATH)\n );\n}\n\nimport { promises as fs } from \"fs\";\nimport { join, dirname, basename } from \"path\";\nimport { readdir } from \"fs/promises\";\nimport type {\n IFsLintModule,\n FsLintModuleDependencies,\n FsLintOptions,\n FsFixOptions,\n FileSystem,\n} from \"./fs_lint.types\";\nimport type {\n LintReport,\n LintResult,\n FixReport,\n FixResult,\n ValidatorType,\n ILintModule,\n LintRecordContext,\n FixRecordOptions,\n} from \"../lint.types\";\n// Note: IIndexerAdapter is in FsLintModuleDependencies but passed to LintModule, not used directly\nimport type {\n GitGovRecord,\n TaskRecord,\n CycleRecord,\n GitGovRecordType\n} from \"../../record_types\";\nimport { isTaskPayload, isCyclePayload } from \"../../record_types/type_guards\";\nimport { extractRecordIdFromPath, getEntityTypeFromPath, inferEntityTypeFromId } from \"../../utils/id_parser\";\nimport { chunkArray } from \"../../utils/array_utils\";\nimport { createLogger } from \"../../logger\";\nimport { calculatePayloadChecksum } from \"../../crypto/checksum\";\nimport {\n loadTaskRecord,\n loadActorRecord,\n loadAgentRecord,\n loadCycleRecord,\n loadExecutionRecord,\n loadChangelogRecord,\n loadFeedbackRecord\n} from \"../../record_factories\";\nimport { DetailedValidationError } from \"../../record_validations/common\";\n\nconst logger = createLogger(\"[FsLint] \");\n\n/**\n * Filesystem-aware lint module.\n * Wraps LintModule (pure) and adds I/O operations.\n *\n * @implements {IFsLintModule}\n */\nexport class FsLintModule implements IFsLintModule {\n private readonly projectRoot: string;\n private readonly lintModule: ILintModule;\n private readonly fileSystem: FileSystem;\n private lastBackupPath: string | null = null;\n\n /**\n * Constructor for FsLintModule.\n *\n * @param dependencies - Module dependencies\n */\n constructor(dependencies: FsLintModuleDependencies) {\n if (!dependencies.projectRoot) {\n throw new Error(\"projectRoot is required for FsLintModule\");\n }\n if (!dependencies.lintModule) {\n throw new Error(\"lintModule is required for FsLintModule\");\n }\n this.projectRoot = dependencies.projectRoot;\n this.lintModule = dependencies.lintModule;\n // Note: indexerAdapter is passed to LintModule, not used directly here\n\n // FileSystem with fallback to Node.js fs\n this.fileSystem = dependencies.fileSystem ?? {\n readFile: async (path: string, encoding: string) => {\n return fs.readFile(path, encoding as BufferEncoding);\n },\n writeFile: async (path: string, content: string) => {\n await fs.writeFile(path, content, \"utf-8\");\n },\n exists: async (path: string) => {\n try {\n await fs.access(path);\n return true;\n } catch {\n return false;\n }\n },\n unlink: async (path: string) => {\n await fs.unlink(path);\n },\n readdir: async (path: string) => {\n return readdir(path);\n }\n };\n }\n\n // ==================== ILintModule Delegation ====================\n\n /**\n * Delegates to LintModule.lintRecord() for pure validation.\n */\n lintRecord(record: GitGovRecord, context: LintRecordContext): LintResult[] {\n return this.lintModule.lintRecord(record, context);\n }\n\n /**\n * Delegates to LintModule.fixRecord() for pure fix.\n */\n fixRecord(record: GitGovRecord, results: LintResult[], options: FixRecordOptions): GitGovRecord {\n return this.lintModule.fixRecord(record, results, options);\n }\n\n // ==================== IFsLintModule Methods ====================\n\n /**\n * [EARS-A1] Scans directories and validates all records.\n *\n * @param options - Configuration options\n * @returns Consolidated lint report\n */\n async lint(options?: Partial<FsLintOptions>): Promise<LintReport> {\n const startTime = Date.now();\n\n const opts: FsLintOptions = {\n path: options?.path ?? \".gitgov/\",\n validateReferences: options?.validateReferences ?? false,\n validateActors: options?.validateActors ?? false,\n validateChecksums: options?.validateChecksums ?? true,\n validateSignatures: options?.validateSignatures ?? true,\n validateTimestamps: options?.validateTimestamps ?? true,\n validateFileNaming: options?.validateFileNaming ?? true,\n failFast: options?.failFast ?? false,\n concurrent: options?.concurrent ?? true,\n concurrencyLimit: options?.concurrencyLimit ?? 10\n };\n\n const results: LintResult[] = [];\n\n // Suppress console.warn during lint\n const originalWarn = console.warn;\n console.warn = () => {};\n\n try {\n // 1. Discovery: Find all records\n const recordsWithTypes = await this.discoverAllRecordsWithTypes(opts.path);\n logger.info(`Starting lint validation for ${recordsWithTypes.length} records`);\n\n // 2. Validation Loop\n if (opts.concurrent) {\n const batches = chunkArray(recordsWithTypes, opts.concurrencyLimit!);\n for (const batch of batches) {\n const batchResults = await Promise.all(\n batch.map(({ id, type }) => this.lintSingleRecord(id, opts, type))\n );\n for (const batchResult of batchResults) {\n results.push(...batchResult);\n if (opts.failFast && batchResult.some(r => r.level === \"error\")) {\n break;\n }\n }\n if (opts.failFast && results.some(r => r.level === \"error\")) {\n break;\n }\n }\n } else {\n for (const { id, type } of recordsWithTypes) {\n const recordResults = await this.lintSingleRecord(id, opts, type);\n results.push(...recordResults);\n if (opts.failFast && recordResults.some(r => r.level === \"error\")) {\n break;\n }\n }\n }\n\n const executionTime = Date.now() - startTime;\n const errors = results.filter(r => r.level === \"error\").length;\n const warnings = results.filter(r => r.level === \"warning\").length;\n const fixable = results.filter(r => r.fixable).length;\n\n logger.info(`Lint completed in ${executionTime}ms: ${recordsWithTypes.length} files, ${errors} errors, ${warnings} warnings`);\n\n return {\n summary: { filesChecked: recordsWithTypes.length, errors, warnings, fixable, executionTime },\n results,\n metadata: { timestamp: new Date().toISOString(), options: opts, version: \"1.0.0\" }\n };\n } finally {\n console.warn = originalWarn;\n }\n }\n\n /**\n * Validates a specific file.\n *\n * @param filePath - Path to the file to validate\n * @param options - Configuration options\n * @returns Lint report for this single file\n */\n async lintFile(filePath: string, options?: Partial<FsLintOptions>): Promise<LintReport> {\n const startTime = Date.now();\n const recordId = extractRecordIdFromPath(filePath);\n const entityType = getEntityTypeFromPath(filePath) || inferEntityTypeFromId(recordId);\n\n const opts: FsLintOptions = {\n path: filePath,\n validateReferences: options?.validateReferences ?? false,\n validateActors: options?.validateActors ?? false,\n validateChecksums: options?.validateChecksums ?? true,\n validateSignatures: options?.validateSignatures ?? true,\n validateTimestamps: options?.validateTimestamps ?? true,\n validateFileNaming: options?.validateFileNaming ?? true,\n failFast: options?.failFast ?? false,\n concurrent: false,\n concurrencyLimit: 1\n };\n\n const originalWarn = console.warn;\n console.warn = () => {};\n\n try {\n const results = await this.lintSingleRecord(recordId, opts, entityType);\n\n const executionTime = Date.now() - startTime;\n const errors = results.filter(r => r.level === \"error\").length;\n const warnings = results.filter(r => r.level === \"warning\").length;\n const fixable = results.filter(r => r.fixable).length;\n\n return {\n summary: { filesChecked: 1, errors, warnings, fixable, executionTime },\n results,\n metadata: { timestamp: new Date().toISOString(), options: opts, version: \"1.0.0\" }\n };\n } finally {\n console.warn = originalWarn;\n }\n }\n\n /**\n * Applies automatic repairs to files, creating backups.\n *\n * @param lintReport - Lint report with detected problems\n * @param fixOptions - Options for the fix operation\n * @returns Report of applied repairs\n */\n async fix(lintReport: LintReport, fixOptions?: Partial<FsFixOptions>): Promise<FixReport> {\n const opts: FsFixOptions = {\n ...(fixOptions?.fixTypes && { fixTypes: fixOptions.fixTypes }),\n createBackups: fixOptions?.createBackups ?? true,\n keyId: fixOptions?.keyId ?? \"system:migrator\",\n dryRun: fixOptions?.dryRun ?? false,\n ...(fixOptions?.privateKey && { privateKey: fixOptions.privateKey })\n };\n\n const fixes: FixResult[] = [];\n\n let fixableResults = lintReport.results.filter(r => r.fixable);\n if (opts.fixTypes && opts.fixTypes.length > 0) {\n fixableResults = fixableResults.filter(r => opts.fixTypes!.includes(r.validator));\n }\n\n logger.info(`Starting fix operation for ${fixableResults.length} fixable problems`);\n\n // Group by file and validator\n const resultsByFile = new Map<string, Map<ValidatorType, LintResult[]>>();\n for (const result of fixableResults) {\n if (!resultsByFile.has(result.filePath)) {\n resultsByFile.set(result.filePath, new Map());\n }\n const fileResults = resultsByFile.get(result.filePath)!;\n if (!fileResults.has(result.validator)) {\n fileResults.set(result.validator, []);\n }\n fileResults.get(result.validator)!.push(result);\n }\n\n for (const [, validatorMap] of resultsByFile) {\n for (const [, results] of validatorMap) {\n const primaryResult = results[0]!;\n let backupPath: string | undefined;\n\n try {\n if (opts.dryRun) {\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Would fix ${primaryResult.validator} (${results.length} error${results.length === 1 ? '' : 's'})`,\n success: true\n });\n continue;\n }\n\n // Create backup\n if (opts.createBackups && !backupPath) {\n backupPath = await this.createBackup(primaryResult.filePath);\n }\n\n // Apply fix\n await this.applyFix(primaryResult, opts, results);\n\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Fixed ${primaryResult.validator} (${results.length} error${results.length === 1 ? '' : 's'})`,\n success: true,\n ...(backupPath && { backupPath })\n });\n\n logger.debug(`Successfully fixed ${primaryResult.filePath}`);\n\n } catch (error) {\n if (opts.createBackups && backupPath) {\n try {\n await this.restoreBackup(primaryResult.filePath);\n logger.warn(`Restored backup for ${primaryResult.filePath}`);\n } catch {\n logger.error(`Failed to restore backup for ${primaryResult.filePath}`);\n }\n }\n\n fixes.push({\n filePath: primaryResult.filePath,\n validator: primaryResult.validator,\n action: `Failed to fix ${primaryResult.validator}`,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n ...(backupPath && { backupPath })\n });\n }\n }\n }\n\n const summary = {\n fixed: fixes.filter(f => f.success).length,\n failed: fixes.filter(f => !f.success).length,\n backupsCreated: opts.createBackups ? fixes.filter(f => f.backupPath).length : 0\n };\n\n logger.info(`Fix completed: ${summary.fixed} fixed, ${summary.failed} failed`);\n\n return { summary, fixes };\n }\n\n // ==================== Private Methods ====================\n\n /**\n * Validates a single record by reading from filesystem.\n * @private\n */\n private async lintSingleRecord(\n recordId: string,\n options: FsLintOptions,\n entityType: Exclude<GitGovRecordType, 'custom'>\n ): Promise<LintResult[]> {\n const results: LintResult[] = [];\n let filePath: string;\n\n if (options.path && options.path.endsWith('.json')) {\n // Resolve path: absolute paths used directly, relative paths joined with projectRoot\n filePath = options.path.startsWith('/')\n ? options.path\n : join(this.projectRoot, options.path);\n } else {\n filePath = this.getFilePath(recordId, entityType);\n }\n\n try {\n // Read and parse file\n const content = await this.fileSystem.readFile(filePath, 'utf-8');\n const raw = JSON.parse(content);\n\n // Load with appropriate loader\n let record: GitGovRecord;\n switch (entityType) {\n case 'task': record = loadTaskRecord(raw); break;\n case 'actor': record = loadActorRecord(raw); break;\n case 'agent': record = loadAgentRecord(raw); break;\n case 'cycle': record = loadCycleRecord(raw); break;\n case 'execution': record = loadExecutionRecord(raw); break;\n case 'changelog': record = loadChangelogRecord(raw); break;\n case 'feedback': record = loadFeedbackRecord(raw); break;\n default: record = raw as GitGovRecord;\n }\n\n // [EARS-D1] Use pure LintModule for validation\n const lintResults = this.lintModule.lintRecord(record, {\n recordId,\n entityType,\n filePath\n });\n results.push(...lintResults);\n\n // File naming validation (filesystem-specific)\n if (options.validateFileNaming) {\n const namingResults = this.validateFileNaming(record, recordId, filePath, entityType);\n results.push(...namingResults);\n }\n\n } catch (error) {\n if (error instanceof DetailedValidationError) {\n const hasAdditionalProperties = error.errors.some(e =>\n e.message.includes(\"must NOT have additional properties\")\n );\n // [EARS-F1] Filter redundant oneOf/if-then-else errors when the root cause is additionalProperties\n const filteredErrors = hasAdditionalProperties\n ? error.errors.filter(e => !isRedundantOneOfError(e.message))\n : error.errors;\n\n for (const err of filteredErrors) {\n results.push({\n level: \"error\",\n filePath,\n validator: this.detectValidatorType(err.message, err.field),\n message: `${err.field}: ${err.message}`,\n entity: { type: entityType, id: recordId },\n fixable: this.isFixable(err.message),\n context: {\n ...(err.field && { field: err.field }),\n ...(err.value !== undefined && { actual: err.value })\n }\n });\n }\n } else {\n const fsError = error as NodeJS.ErrnoException;\n let message: string;\n if (fsError.code === 'ENOENT') {\n message = `Record file not found: ${recordId}`;\n } else if (error instanceof SyntaxError) {\n message = `Invalid JSON in record file: ${recordId}`;\n } else {\n message = error instanceof Error ? error.message : String(error);\n }\n\n results.push({\n level: \"error\",\n filePath,\n validator: \"SCHEMA_VALIDATION\",\n message,\n entity: { type: entityType, id: recordId },\n fixable: false\n });\n }\n }\n\n return results;\n }\n\n /**\n * [EARS-B1, EARS-B2] Validates file naming conventions.\n * @private\n */\n private validateFileNaming(\n _record: GitGovRecord,\n recordId: string,\n filePath: string,\n entityType: Exclude<GitGovRecordType, 'custom'>\n ): LintResult[] {\n const results: LintResult[] = [];\n\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n\n // [EARS-B1] Validate correct directory\n const expectedDir = `.gitgov/${dirNameMap[entityType]}`;\n if (!filePath.includes(expectedDir)) {\n results.push({\n level: \"error\",\n filePath,\n validator: \"FILE_NAMING_CONVENTION\",\n message: `File should be in ${expectedDir}/ directory`,\n entity: { type: entityType, id: recordId },\n fixable: false,\n context: { field: \"directory\", actual: dirname(filePath), expected: expectedDir }\n });\n }\n\n // [EARS-B2] Validate filename matches ID\n const expectedFilename = `${recordId}.json`;\n const actualFilename = basename(filePath);\n if (actualFilename !== expectedFilename) {\n results.push({\n level: \"error\",\n filePath,\n validator: \"FILE_NAMING_CONVENTION\",\n message: `Filename '${actualFilename}' does not match entity ID`,\n entity: { type: entityType, id: recordId },\n fixable: false,\n context: { field: \"filename\", actual: actualFilename, expected: expectedFilename }\n });\n }\n\n return results;\n }\n\n /**\n * [EARS-A1] Discovers all records with their types by scanning filesystem.\n * @private\n */\n private async discoverAllRecordsWithTypes(_path?: string): Promise<Array<{ id: string; type: Exclude<GitGovRecordType, 'custom'> }>> {\n // Note: _path parameter is deprecated, projectRoot is now injected via constructor\n const recordTypes: Array<Exclude<GitGovRecordType, 'custom'>> = [\n 'actor', 'agent', 'cycle', 'task', 'execution', 'changelog', 'feedback'\n ];\n const allRecords: Array<{ id: string; type: Exclude<GitGovRecordType, 'custom'> }> = [];\n\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n\n for (const recordType of recordTypes) {\n const dirPath = join(this.projectRoot, '.gitgov', dirNameMap[recordType]);\n try {\n const files = await readdir(dirPath);\n const jsonFiles = files.filter(f => f.endsWith('.json'));\n const records = jsonFiles.map(f => ({ id: f.replace('.json', ''), type: recordType }));\n allRecords.push(...records);\n } catch {\n // Directory doesn't exist, skip\n }\n }\n\n return allRecords;\n }\n\n /**\n * Gets file path for a record.\n * @private\n */\n private getFilePath(recordId: string, entityType: Exclude<GitGovRecordType, 'custom'>): string {\n const dirNameMap: Record<Exclude<GitGovRecordType, 'custom'>, string> = {\n 'task': 'tasks', 'cycle': 'cycles', 'execution': 'executions',\n 'changelog': 'changelogs', 'feedback': 'feedbacks',\n 'actor': 'actors', 'agent': 'agents'\n };\n const dirName = dirNameMap[entityType];\n const safeId = recordId.replace(/:/g, '_');\n\n return join(this.projectRoot, \".gitgov\", dirName, `${safeId}.json`);\n }\n\n /**\n * [EARS-C1] Creates a backup of a file before modification.\n * @private\n */\n private async createBackup(filePath: string): Promise<string> {\n const timestamp = Date.now();\n const backupPath = `${filePath}.backup-${timestamp}`;\n const content = await this.fileSystem.readFile(filePath, \"utf-8\");\n await this.fileSystem.writeFile(backupPath, content);\n this.lastBackupPath = backupPath;\n return backupPath;\n }\n\n /**\n * [EARS-C2] Restores file from backup if fix fails.\n * @private\n */\n private async restoreBackup(filePath: string): Promise<void> {\n if (this.lastBackupPath) {\n const exists = await this.fileSystem.exists(this.lastBackupPath);\n if (exists) {\n const content = await this.fileSystem.readFile(this.lastBackupPath, \"utf-8\");\n await this.fileSystem.writeFile(filePath, content);\n this.lastBackupPath = null;\n return;\n }\n }\n throw new Error(`No backup found for ${filePath}`);\n }\n\n /**\n * Applies a fix to a file.\n * @private\n */\n private async applyFix(result: LintResult, options: FsFixOptions, allErrors: LintResult[]): Promise<void> {\n switch (result.validator) {\n case \"EMBEDDED_METADATA_STRUCTURE\":\n await this.fixLegacyRecord(result, options, allErrors);\n break;\n case \"BIDIRECTIONAL_CONSISTENCY\":\n await this.fixBidirectionalReference(result);\n break;\n case \"CHECKSUM_VERIFICATION\":\n await this.recalculateChecksum(result);\n break;\n case \"SIGNATURE_STRUCTURE\":\n await this.fixSignatureStructure(result, options, allErrors);\n break;\n default:\n throw new Error(`Fix not implemented for validator: ${result.validator}`);\n }\n }\n\n /**\n * Fixes legacy record with embedded metadata issues.\n * @private\n */\n private async fixLegacyRecord(result: LintResult, options: FsFixOptions, allErrors?: LintResult[]): Promise<void> {\n if (!options.privateKey) {\n throw new Error(\"privateKey is required to fix legacy records\");\n }\n\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n // Use pure LintModule to fix\n const fixedRecord = this.lintModule.fixRecord(record, allErrors || [result], {\n fixTypes: ['EMBEDDED_METADATA_STRUCTURE'],\n ...(options.keyId !== undefined && { keyId: options.keyId }),\n privateKey: options.privateKey\n });\n\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(fixedRecord, null, 2));\n logger.info(`Fixed legacy record: ${result.filePath}`);\n }\n\n /**\n * Fixes bidirectional reference inconsistencies.\n * @private\n */\n private async fixBidirectionalReference(result: LintResult): Promise<void> {\n const entityType = result.entity.type;\n const recordId = result.entity.id;\n const filePath = this.getFilePath(recordId, entityType);\n\n const content = await this.fileSystem.readFile(filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n if (entityType === \"task\" && isTaskPayload(record.payload)) {\n const taskPayload = record.payload;\n if (taskPayload.cycleIds) {\n for (const cycleId of taskPayload.cycleIds) {\n const cycleFilePath = this.getFilePath(cycleId, \"cycle\");\n try {\n const cycleContent = await this.fileSystem.readFile(cycleFilePath, \"utf-8\");\n const cycleRecord = JSON.parse(cycleContent) as GitGovRecord;\n const cyclePayload = cycleRecord.payload as CycleRecord;\n\n if (!cyclePayload.taskIds) {\n cyclePayload.taskIds = [];\n }\n if (!cyclePayload.taskIds.includes(recordId)) {\n cyclePayload.taskIds.push(recordId);\n await this.fileSystem.writeFile(cycleFilePath, JSON.stringify(cycleRecord, null, 2));\n logger.info(`Added task ${recordId} to cycle ${cycleId}`);\n }\n } catch {\n // Cycle file doesn't exist, skip\n }\n }\n }\n } else if (entityType === \"cycle\" && isCyclePayload(record.payload)) {\n const cyclePayload = record.payload;\n if (cyclePayload.taskIds) {\n for (const taskId of cyclePayload.taskIds) {\n const taskFilePath = this.getFilePath(taskId, \"task\");\n try {\n const taskContent = await this.fileSystem.readFile(taskFilePath, \"utf-8\");\n const taskRecord = JSON.parse(taskContent) as GitGovRecord;\n const taskPayload = taskRecord.payload as TaskRecord;\n\n if (!taskPayload.cycleIds) {\n taskPayload.cycleIds = [];\n }\n if (!taskPayload.cycleIds.includes(recordId)) {\n taskPayload.cycleIds.push(recordId);\n await this.fileSystem.writeFile(taskFilePath, JSON.stringify(taskRecord, null, 2));\n logger.info(`Added cycle ${recordId} to task ${taskId}`);\n }\n } catch {\n // Task file doesn't exist, skip\n }\n }\n }\n }\n }\n\n /**\n * Recalculates checksum for a record.\n * @private\n */\n private async recalculateChecksum(result: LintResult): Promise<void> {\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n if (!record.header || !record.payload) {\n throw new Error(\"Cannot recalculate checksum: invalid record structure\");\n }\n\n record.header.payloadChecksum = calculatePayloadChecksum(record.payload);\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(record, null, 2));\n logger.info(`Recalculated checksum for: ${result.filePath}`);\n }\n\n /**\n * Fixes signature structure issues.\n * @private\n */\n private async fixSignatureStructure(result: LintResult, options: FsFixOptions, allErrors: LintResult[]): Promise<void> {\n if (!options.privateKey) {\n throw new Error(\"privateKey is required to fix signature\");\n }\n\n const content = await this.fileSystem.readFile(result.filePath, \"utf-8\");\n const record = JSON.parse(content) as GitGovRecord;\n\n const fixedRecord = this.lintModule.fixRecord(record, allErrors, {\n fixTypes: ['SIGNATURE_STRUCTURE'],\n ...(options.keyId !== undefined && { keyId: options.keyId }),\n privateKey: options.privateKey\n });\n\n await this.fileSystem.writeFile(result.filePath, JSON.stringify(fixedRecord, null, 2));\n logger.info(`Fixed signature structure: ${result.filePath}`);\n }\n\n /**\n * [EARS-E1] Detects validator type from error message.\n * Includes detection of SCHEMA_VERSION_MISMATCH for outdated schemas.\n * @private\n */\n private detectValidatorType(message: string, field?: string): ValidatorType {\n const text = `${message} ${field || ''}`.toLowerCase();\n\n if (text.includes(\"checksum\")) return \"CHECKSUM_VERIFICATION\";\n if (text.includes(\"signature\") || text.includes(\"/signatures/\")) return \"SIGNATURE_STRUCTURE\";\n if (text.includes(\"header\") || text.includes(\"payload\") || text.includes(\"/header/\")) return \"EMBEDDED_METADATA_STRUCTURE\";\n\n // [EARS-E1] Detect schema version mismatch indicators\n const versionMismatchIndicators = [\n 'required in v', 'deprecated', 'obsolete', 'schema version', 'migration'\n ];\n if (versionMismatchIndicators.some(i => text.includes(i)) || /v\\d+|version\\s+\\d+/i.test(text)) {\n return \"SCHEMA_VERSION_MISMATCH\";\n }\n\n return \"SCHEMA_VALIDATION\";\n }\n\n /**\n * Determines if an error is fixable.\n * @private\n */\n private isFixable(message: string): boolean {\n const text = message.toLowerCase();\n if (text.includes(\"header\") || text.includes(\"metadata\")) return true;\n if (text.includes(\"additional properties\")) return true;\n if (text.includes(\"checksum\")) return true;\n if (text.includes(\"signature\") && text.includes(\"format\")) return true;\n return false;\n }\n}\n","/**\n * ESM Helper - Provides access to import.meta for use in ESM contexts\n * \n * This file is separated because import.meta cannot be used in Jest/CommonJS tests.\n * Jest will mock this module when running tests.\n */\n\n/**\n * Get the current module URL (import.meta.url)\n * Returns null in non-ESM contexts (like Jest tests)\n */\nexport function getImportMetaUrl(): string | null {\n try {\n return import.meta.url;\n } catch {\n return null;\n }\n}\n\n","import { promises as fs, existsSync } from 'fs';\nimport * as path from 'path';\nimport { execSync } from 'child_process';\nimport type { GitGovConfig } from '../../config_manager';\nimport type { IProjectInitializer, EnvironmentValidation } from '../project_initializer';\nimport { createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { getImportMetaUrl } from '../../utils/esm_helper';\nimport { createLogger } from '../../logger';\n\nconst logger = createLogger('[FsProjectInitializer] ');\n\n/**\n * Canonical directory structure for .gitgov/\n */\nconst GITGOV_DIRECTORIES = [\n 'actors',\n 'cycles',\n 'tasks',\n 'executions',\n 'feedbacks',\n 'changelogs',\n] as const;\n\n/**\n * FsProjectInitializer - Filesystem implementation of IProjectInitializer.\n *\n * Initializes GitGovernance projects on the local filesystem,\n * creating the .gitgov/ directory structure and configuration files.\n *\n * The projectRoot is injected at construction time (DI from CLI/bootstrap).\n *\n * @example\n * ```typescript\n * const initializer = new FsProjectInitializer('/path/to/project');\n *\n * const validation = await initializer.validateEnvironment();\n * if (!validation.isValid) {\n * console.log(validation.warnings);\n * return;\n * }\n *\n * await initializer.createProjectStructure();\n * await initializer.writeConfig(config);\n * await initializer.initializeSession(actorId);\n * await initializer.copyAgentPrompt();\n * await initializer.setupGitIntegration();\n * ```\n */\nexport class FsProjectInitializer implements IProjectInitializer {\n private readonly projectRoot: string;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n }\n\n // ==================== IProjectInitializer Interface Methods ====================\n\n /**\n * Creates the .gitgov/ directory structure.\n */\n async createProjectStructure(): Promise<void> {\n const gitgovPath = path.join(this.projectRoot, '.gitgov');\n\n await fs.mkdir(gitgovPath, { recursive: true });\n\n for (const dir of GITGOV_DIRECTORIES) {\n await fs.mkdir(path.join(gitgovPath, dir), { recursive: true });\n }\n }\n\n /**\n * Checks if .gitgov/config.json exists.\n */\n async isInitialized(): Promise<boolean> {\n const configPath = path.join(this.projectRoot, '.gitgov', 'config.json');\n try {\n await fs.access(configPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Writes config.json to .gitgov/\n */\n async writeConfig(config: GitGovConfig): Promise<void> {\n const configPath = path.join(this.projectRoot, '.gitgov', 'config.json');\n await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Creates .session.json with initial actor state.\n */\n async initializeSession(actorId: string): Promise<void> {\n const sessionPath = path.join(this.projectRoot, '.gitgov', '.session.json');\n const session = {\n lastSession: {\n actorId,\n timestamp: new Date().toISOString(),\n },\n actorState: {\n [actorId]: {\n lastSync: new Date().toISOString(),\n syncStatus: {\n status: 'synced' as const,\n },\n },\n },\n };\n\n await fs.writeFile(sessionPath, JSON.stringify(session, null, 2), 'utf-8');\n }\n\n /**\n * Reads a file from the filesystem.\n */\n async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, 'utf-8');\n }\n\n /**\n * Gets the path for an actor record.\n */\n getActorPath(actorId: string): string {\n return path.join(this.projectRoot, '.gitgov', 'actors', `${actorId}.json`);\n }\n\n /**\n * Validates environment for GitGovernance initialization.\n * Checks: Git repo exists, write permissions, not already initialized.\n */\n async validateEnvironment(): Promise<EnvironmentValidation> {\n const warnings: string[] = [];\n const suggestions: string[] = [];\n\n try {\n // Check if it's a Git repository\n const gitPath = path.join(this.projectRoot, '.git');\n const isGitRepo = existsSync(gitPath);\n\n if (!isGitRepo) {\n warnings.push(`Not a Git repository in directory: ${this.projectRoot}`);\n suggestions.push(\"Run 'git init' to initialize a Git repository first\");\n }\n\n // Check write permissions\n let hasWritePermissions = false;\n try {\n const testFile = path.join(this.projectRoot, '.gitgov-test');\n await fs.writeFile(testFile, 'test');\n await fs.unlink(testFile);\n hasWritePermissions = true;\n } catch {\n warnings.push('No write permissions in target directory');\n suggestions.push('Ensure you have write permissions in the target directory');\n }\n\n // Check if already initialized\n const isAlreadyInitialized = await this.isInitialized();\n if (isAlreadyInitialized) {\n warnings.push(`GitGovernance already initialized in directory: ${this.projectRoot}`);\n suggestions.push(\"Use 'gitgov status' to check current state or choose a different directory\");\n }\n\n // VCS status checks (only if it's a git repo)\n let hasRemote = false;\n let hasCommits = false;\n let currentBranch = '';\n\n if (isGitRepo) {\n try {\n execSync('git remote get-url origin', {\n cwd: this.projectRoot,\n stdio: 'pipe',\n });\n hasRemote = true;\n } catch {\n hasRemote = false;\n }\n\n try {\n currentBranch = execSync('git branch --show-current', {\n cwd: this.projectRoot,\n encoding: 'utf-8',\n stdio: 'pipe',\n }).trim();\n } catch {\n currentBranch = '';\n }\n\n try {\n execSync('git log --oneline -1', {\n cwd: this.projectRoot,\n stdio: 'pipe',\n });\n hasCommits = true;\n } catch {\n hasCommits = false;\n }\n }\n\n const isValid = isGitRepo && hasWritePermissions && !isAlreadyInitialized;\n\n const result: EnvironmentValidation = {\n isValid,\n isGitRepo,\n hasWritePermissions,\n isAlreadyInitialized,\n warnings,\n suggestions,\n hasRemote,\n hasCommits,\n currentBranch,\n };\n\n if (isAlreadyInitialized) {\n result.gitgovPath = path.join(this.projectRoot, '.gitgov');\n }\n\n return result;\n } catch (error) {\n warnings.push(`Environment validation error: ${error instanceof Error ? error.message : 'Unknown error'}`);\n suggestions.push('Check file system permissions and try again');\n\n return {\n isValid: false,\n isGitRepo: false,\n hasWritePermissions: false,\n isAlreadyInitialized: false,\n warnings,\n suggestions,\n };\n }\n }\n\n /**\n * Copies the @gitgov agent prompt to project root for IDE access.\n */\n async copyAgentPrompt(): Promise<void> {\n const targetPrompt = path.join(this.projectRoot, 'gitgov');\n const potentialSources: string[] = [];\n\n // 1. Development scenario: search in src/docs/generated/\n potentialSources.push(\n path.join(process.cwd(), 'src/docs/generated/gitgov_agent.md')\n );\n\n // 2. NPM installation: use require.resolve\n try {\n const metaUrl = getImportMetaUrl();\n if (metaUrl) {\n const require = createRequire(metaUrl);\n const pkgJsonPath = require.resolve('@gitgov/core/package.json');\n const pkgRoot = path.dirname(pkgJsonPath);\n potentialSources.push(path.join(pkgRoot, 'dist/src/docs/generated/gitgov_agent.md'));\n }\n } catch {\n // require.resolve failed - continue\n }\n\n // 3. Build fallback: relative to compiled __dirname\n try {\n const metaUrl = getImportMetaUrl();\n if (metaUrl) {\n const __filename = fileURLToPath(metaUrl);\n const __dirname = path.dirname(__filename);\n potentialSources.push(path.resolve(__dirname, '../../docs/generated/gitgov_agent.md'));\n }\n } catch {\n // import.meta not available - continue\n }\n\n // Find and copy the first accessible file\n for (const source of potentialSources) {\n try {\n await fs.access(source);\n await fs.copyFile(source, targetPrompt);\n logger.debug(`@gitgov agent prompt copied to project root (./gitgov)\\n`);\n return;\n } catch {\n continue;\n }\n }\n\n // Graceful degradation\n console.warn(\n 'Warning: Could not copy @gitgov agent prompt. Project will work but AI assistant may not have local instructions.'\n );\n }\n\n /**\n * Sets up .gitignore for GitGovernance files.\n */\n async setupGitIntegration(): Promise<void> {\n const gitignorePath = path.join(this.projectRoot, '.gitignore');\n const gitignoreContent = `\n# GitGovernance\n# Ignore entire .gitgov/ directory (state lives in gitgov-state branch)\n.gitgov/\n\n# Ignore agent prompt file (project-specific, created by gitgov init)\ngitgov\n`;\n\n try {\n let existingContent = '';\n try {\n existingContent = await fs.readFile(gitignorePath, 'utf-8');\n } catch {\n // File doesn't exist, will create new\n }\n\n if (existingContent && !existingContent.includes('# GitGovernance')) {\n await fs.appendFile(gitignorePath, gitignoreContent);\n } else if (!existingContent) {\n await fs.writeFile(gitignorePath, gitignoreContent);\n }\n } catch (error) {\n console.warn('Failed to setup Git integration:', error);\n }\n }\n\n /**\n * Removes .gitgov/ directory (for rollback on failed init).\n */\n async rollback(): Promise<void> {\n const gitgovPath = path.join(this.projectRoot, '.gitgov');\n try {\n await fs.access(gitgovPath);\n await fs.rm(gitgovPath, { recursive: true, force: true });\n } catch {\n // Directory doesn't exist, nothing to clean up\n }\n }\n}\n","/**\n * Custom Error Classes for GitModule\n * \n * These errors provide typed exceptions for better error handling\n * and diagnostics in the Git module operations.\n */\n\n/**\n * Base error class for all Git-related errors\n */\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n Object.setPrototypeOf(this, GitError.prototype);\n }\n}\n\n/**\n * Error thrown when a Git command fails\n */\nexport class GitCommandError extends GitError {\n public readonly stderr: string;\n public readonly stdout?: string | undefined;\n public readonly command?: string | undefined;\n\n constructor(message: string, stderr: string = '', command?: string | undefined, stdout?: string) {\n super(message);\n this.name = 'GitCommandError';\n this.stderr = stderr;\n this.stdout = stdout;\n this.command = command;\n Object.setPrototypeOf(this, GitCommandError.prototype);\n }\n}\n\n/**\n * Error thrown when a branch does not exist\n */\nexport class BranchNotFoundError extends GitError {\n public readonly branchName: string;\n\n constructor(branchName: string) {\n super(`Branch not found: ${branchName}`);\n this.name = 'BranchNotFoundError';\n this.branchName = branchName;\n Object.setPrototypeOf(this, BranchNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when a file does not exist in a commit\n */\nexport class FileNotFoundError extends GitError {\n public readonly filePath: string;\n public readonly commitHash: string;\n\n constructor(filePath: string, commitHash: string) {\n super(`File not found: ${filePath} in commit ${commitHash}`);\n this.name = 'FileNotFoundError';\n this.filePath = filePath;\n this.commitHash = commitHash;\n Object.setPrototypeOf(this, FileNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when a merge conflict occurs\n */\nexport class MergeConflictError extends GitError {\n public readonly conflictedFiles: string[];\n\n constructor(conflictedFiles: string[]) {\n super(`Merge conflict detected in ${conflictedFiles.length} file(s)`);\n this.name = 'MergeConflictError';\n this.conflictedFiles = conflictedFiles;\n Object.setPrototypeOf(this, MergeConflictError.prototype);\n }\n}\n\n/**\n * Error thrown when a rebase conflict occurs\n */\nexport class RebaseConflictError extends GitError {\n public readonly conflictedFiles: string[];\n\n constructor(conflictedFiles: string[]) {\n super(`Rebase conflict detected in ${conflictedFiles.length} file(s)`);\n this.name = 'RebaseConflictError';\n this.conflictedFiles = conflictedFiles;\n Object.setPrototypeOf(this, RebaseConflictError.prototype);\n }\n}\n\n/**\n * Error thrown when trying to continue/abort a rebase that is not in progress\n */\nexport class RebaseNotInProgressError extends GitError {\n constructor() {\n super('No rebase in progress');\n this.name = 'RebaseNotInProgressError';\n Object.setPrototypeOf(this, RebaseNotInProgressError.prototype);\n }\n}\n\n/**\n * Error thrown when trying to create a branch that already exists\n */\nexport class BranchAlreadyExistsError extends GitError {\n public readonly branchName: string;\n\n constructor(branchName: string) {\n super(`Branch already exists: ${branchName}`);\n this.name = 'BranchAlreadyExistsError';\n this.branchName = branchName;\n Object.setPrototypeOf(this, BranchAlreadyExistsError.prototype);\n }\n}\n\n","/**\n * LocalGitModule - Local Git Operations via CLI\n *\n * This module provides a business-agnostic abstraction layer for interacting\n * with the local Git repository. It exposes semantic methods instead of raw\n * Git commands, with comprehensive error handling and type safety.\n *\n * Uses execCommand (injected) to run git CLI commands.\n *\n * @module git/local\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport type { IGitModule } from '..';\nimport type {\n GitModuleDependencies,\n ExecOptions,\n ExecResult,\n GetCommitHistoryOptions,\n CommitInfo,\n ChangedFile,\n CommitAuthor,\n} from '../types';\nimport {\n GitCommandError,\n BranchNotFoundError,\n BranchAlreadyExistsError,\n FileNotFoundError,\n MergeConflictError,\n RebaseConflictError,\n RebaseNotInProgressError,\n} from '../errors';\nimport { createLogger } from '../../logger/logger';\n\nconst logger = createLogger('[LocalGitModule] ');\n\n/**\n * LocalGitModule - CLI-based implementation of IGitModule\n *\n * All operations are async and use dependency injection for testability.\n * Errors are transformed into typed exceptions for better handling.\n *\n * For unit tests without git, use MemoryGitModule instead.\n */\nexport class LocalGitModule implements IGitModule {\n private repoRoot: string;\n private execCommand: (\n command: string,\n args: string[],\n options?: ExecOptions\n ) => Promise<ExecResult>;\n\n /**\n * Creates a new LocalGitModule instance\n *\n * @param dependencies - Required dependencies (execCommand) and optional config (repoRoot)\n * @throws Error if execCommand is not provided\n */\n constructor(dependencies: GitModuleDependencies) {\n if (!dependencies.execCommand) {\n throw new Error('execCommand is required for LocalGitModule');\n }\n\n this.execCommand = dependencies.execCommand;\n this.repoRoot = dependencies.repoRoot || '';\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // PRIVATE HELPERS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Ensures that repoRoot is set, auto-detecting it if necessary\n * \n * @returns Path to repository root\n * @throws GitCommandError if not in a Git repository\n */\n private async ensureRepoRoot(): Promise<string> {\n if (!this.repoRoot) {\n const result = await this.execCommand('git', ['rev-parse', '--show-toplevel']);\n if (result.exitCode !== 0) {\n throw new GitCommandError('Not in a Git repository', result.stderr);\n }\n this.repoRoot = result.stdout.trim();\n }\n return this.repoRoot;\n }\n\n /**\n * Executes a Git command with standardized error handling\n * \n * @param args - Git command arguments\n * @param options - Execution options\n * @returns Command result\n * @throws GitCommandError if command fails\n */\n private async execGit(args: string[], options?: ExecOptions): Promise<ExecResult> {\n const cwd = options?.cwd || await this.ensureRepoRoot();\n const result = await this.execCommand('git', args, { ...options, cwd });\n return result;\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // PUBLIC COMMAND EXECUTION\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Executes an arbitrary shell command with the repository as working directory.\n *\n * This method is intended for advanced use cases where the existing\n * semantic methods don't cover the needed functionality. Use with caution.\n *\n * @param command - The command to execute (e.g., 'git')\n * @param args - Command arguments\n * @param options - Optional execution options\n * @returns Command execution result with exitCode, stdout, stderr\n *\n * @example\n * const result = await gitModule.exec('git', ['diff', '--name-only', 'HEAD~1..HEAD']);\n * if (result.exitCode === 0) {\n * const files = result.stdout.split('\\n');\n * }\n */\n async exec(\n command: string,\n args: string[],\n options?: ExecOptions\n ): Promise<ExecResult> {\n const cwd = options?.cwd || await this.ensureRepoRoot();\n return this.execCommand(command, args, { ...options, cwd });\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // INITIALIZATION\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Initializes a new Git repository in the current directory\n *\n * Creates the `.git/` directory structure and sets up initial configuration.\n * Useful for testing and for commands that require a fresh repository.\n *\n * @throws GitCommandError if directory is already a Git repository\n *\n * @example\n * await gitModule.init();\n * // Repository initialized with default branch (main or master)\n */\n async init(): Promise<void> {\n const cwd = this.repoRoot || process.cwd();\n\n // Check if already in a Git repository\n try {\n const checkResult = await this.execCommand('git', ['rev-parse', '--git-dir'], {\n cwd,\n });\n\n if (checkResult.exitCode === 0) {\n throw new GitCommandError(\n 'Directory is already a Git repository',\n `Git directory exists at ${checkResult.stdout.trim()}`\n );\n }\n } catch (error) {\n // If not a repo, this is what we want - continue with init\n if (error instanceof GitCommandError && error.message === 'Directory is already a Git repository') {\n throw error;\n }\n // Other errors mean it's not a repo, which is good\n }\n\n // Initialize the repository\n const result = await this.execCommand('git', ['init'], {\n cwd,\n });\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to initialize Git repository', result.stderr);\n }\n\n // Update repoRoot if it wasn't set\n if (!this.repoRoot) {\n const rootResult = await this.execCommand('git', ['rev-parse', '--show-toplevel'], { cwd });\n if (rootResult.exitCode === 0) {\n this.repoRoot = rootResult.stdout.trim();\n }\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // READ OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Returns the absolute path to the current Git repository root\n * \n * @returns Repository root path\n * @throws GitCommandError if not in a Git repository\n * \n * @example\n * const repoRoot = await gitModule.getRepoRoot();\n * // => \"/home/user/my-project\"\n */\n async getRepoRoot(): Promise<string> {\n return await this.ensureRepoRoot();\n }\n\n /**\n * Returns the name of the current branch (HEAD)\n * \n * @returns Current branch name\n * @throws GitCommandError if in detached HEAD state or other error\n * \n * @example\n * const branch = await gitModule.getCurrentBranch();\n * // => \"main\"\n */\n async getCurrentBranch(): Promise<string> {\n const result = await this.execGit(['rev-parse', '--abbrev-ref', 'HEAD']);\n\n if (result.exitCode !== 0) {\n // Fallback: Try reading .git/HEAD directly (works for orphan branches)\n try {\n const repoRoot = await this.ensureRepoRoot();\n const headPath = path.join(repoRoot, '.git', 'HEAD');\n const headContent = fs.readFileSync(headPath, 'utf-8').trim();\n\n if (headContent.startsWith('ref: refs/heads/')) {\n return headContent.replace('ref: refs/heads/', '');\n }\n } catch (fallbackError) {\n // Fallback failed, throw original error\n }\n\n throw new GitCommandError('Failed to get current branch', result.stderr);\n }\n\n const branch = result.stdout.trim();\n\n if (branch === 'HEAD') {\n throw new GitCommandError('In detached HEAD state', '');\n }\n\n return branch;\n }\n\n /**\n * Get commit hash for a given reference (branch, tag, HEAD, etc.)\n * \n * Used by test helpers and sync operations to get commit SHAs.\n * Returns the full 40-character SHA-1 hash of the commit.\n * \n * @param ref Git reference (default: \"HEAD\"). Can be:\n * - \"HEAD\" for current commit\n * - Branch name (e.g., \"main\", \"gitgov-state\")\n * - Tag name (e.g., \"v1.0.0\")\n * - Commit hash (returns the same hash)\n * - Relative refs (e.g., \"HEAD~1\", \"main^\")\n * @returns Commit SHA hash (full 40-character hash)\n * @throws GitCommandError if ref does not exist\n * \n * @example\n * const headHash = await git.getCommitHash(\"HEAD\");\n * // => \"a1b2c3d4e5f6...\"\n * \n * const mainHash = await git.getCommitHash(\"main\");\n * // => \"f6e5d4c3b2a1...\"\n * \n * const parentHash = await git.getCommitHash(\"HEAD~1\");\n * // => \"9876543210ab...\"\n */\n async getCommitHash(ref: string = \"HEAD\"): Promise<string> {\n const result = await this.execGit([\"rev-parse\", ref]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to get commit hash for ref \"${ref}\"`,\n result.stderr\n );\n }\n\n const hash = result.stdout.trim();\n logger.debug(`Got commit hash for ${ref}: ${hash.substring(0, 8)}...`);\n return hash;\n }\n\n /**\n * Set a Git configuration value.\n * Used for configuring repository settings like user.name, core.editor, etc.\n *\n * [EARS-F1, EARS-F2]\n *\n * @param key - Configuration key (e.g., \"user.name\", \"core.editor\")\n * @param value - Configuration value\n * @param scope - Configuration scope: \"local\" (default), \"global\", or \"system\"\n * @throws GitCommandError if configuration fails\n *\n * @example\n * ```typescript\n * // Set local config (repository-specific)\n * await git.setConfig('core.editor', 'vim');\n *\n * // Set global config (user-wide)\n * await git.setConfig('user.name', 'John Doe', 'global');\n *\n * // Set system config (machine-wide, requires permissions)\n * await git.setConfig('credential.helper', 'cache', 'system');\n * ```\n */\n async setConfig(\n key: string,\n value: string,\n scope: 'local' | 'global' | 'system' = 'local'\n ): Promise<void> {\n logger.debug(`Setting Git config: ${key} = ${value} (scope: ${scope})`);\n\n const args = ['config'];\n\n // Add scope flag\n if (scope === 'global') {\n args.push('--global');\n } else if (scope === 'system') {\n args.push('--system');\n } else {\n args.push('--local');\n }\n\n args.push(key, value);\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to set Git config ${key} to ${value}`,\n result.stderr\n );\n }\n\n logger.debug(`Git config ${key} set successfully`);\n }\n\n /**\n * Finds the most recent common ancestor between two branches\n * \n * @param branchA - First branch name\n * @param branchB - Second branch name\n * @returns Commit hash of the merge base\n * @throws BranchNotFoundError if either branch does not exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * const mergeBase = await gitModule.getMergeBase(\"main\", \"feature\");\n * // => \"a1b2c3d4e5f6...\"\n */\n async getMergeBase(branchA: string, branchB: string): Promise<string> {\n // Verify both branches exist\n if (!(await this.branchExists(branchA))) {\n throw new BranchNotFoundError(branchA);\n }\n if (!(await this.branchExists(branchB))) {\n throw new BranchNotFoundError(branchB);\n }\n\n const result = await this.execGit(['merge-base', branchA, branchB]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to find merge base between ${branchA} and ${branchB}`,\n result.stderr\n );\n }\n\n return result.stdout.trim();\n }\n\n /**\n * Returns a list of files changed between two commits\n * \n * @param fromCommit - Source commit or reference\n * @param toCommit - Target commit or reference\n * @param pathFilter - Optional path filter (e.g., \".gitgov/\")\n * @returns Array of changed files with their status\n * @throws GitCommandError if operation fails\n * \n * @example\n * const changes = await gitModule.getChangedFiles(\"HEAD~1\", \"HEAD\", \".gitgov/\");\n * // => [{ status: \"M\", file: \".gitgov/tasks/123.json\" }]\n */\n async getChangedFiles(\n fromCommit: string,\n toCommit: string,\n pathFilter: string\n ): Promise<ChangedFile[]> {\n const args = [\n 'diff',\n '--name-status',\n `${fromCommit}..${toCommit}`,\n '--',\n pathFilter,\n ];\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get changed files', result.stderr);\n }\n\n // Parse output: \"M\\tfile.txt\\nA\\tfile2.txt\"\n return result.stdout\n .trim()\n .split('\\n')\n .filter((line) => line.length > 0)\n .map((line) => {\n const parts = line.split('\\t');\n if (parts.length < 2) {\n throw new GitCommandError('Invalid git diff output format', line);\n }\n return {\n status: parts[0]! as 'A' | 'M' | 'D',\n file: parts[1]!,\n };\n });\n }\n\n /**\n * Get list of staged files (in staging area / index)\n * \n * Used during conflict resolution to identify which files the user resolved and staged.\n * \n * @returns Array of file paths that are currently staged\n * @throws GitCommandError if operation fails\n * \n * @example\n * // After user resolves conflict and does: git add .gitgov/tasks/123.json\n * const staged = await gitModule.getStagedFiles();\n * // => [\".gitgov/tasks/123.json\"]\n */\n async getStagedFiles(): Promise<string[]> {\n const args = ['diff', '--cached', '--name-only'];\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get staged files', result.stderr);\n }\n\n // Parse output: \"file1.txt\\nfile2.txt\\n\"\n const files = result.stdout\n .trim()\n .split('\\n')\n .filter((line) => line.length > 0);\n\n return files;\n }\n\n /**\n * Retrieves the content of a file at a specific point in history\n * \n * @param commitHash - Commit hash\n * @param filePath - File path relative to repository root\n * @returns File content as string\n * @throws FileNotFoundError if file doesn't exist in that commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const content = await gitModule.getFileContent(\"abc123\", \".gitgov/config.json\");\n * // => '{\"version\": \"1.0.0\"}'\n */\n async getFileContent(commitHash: string, filePath: string): Promise<string> {\n const result = await this.execGit(['show', `${commitHash}:${filePath}`]);\n\n if (result.exitCode !== 0) {\n // Check if error is due to file not existing\n if (result.stderr.includes('does not exist') || result.stderr.includes('exists on disk, but not in')) {\n throw new FileNotFoundError(filePath, commitHash);\n }\n throw new GitCommandError(`Failed to get file content for ${filePath}`, result.stderr);\n }\n\n return result.stdout;\n }\n\n /**\n * Retrieves the commit history for a branch\n * \n * @param branch - Branch name\n * @param options - Filtering and formatting options\n * @returns Array of commits ordered from newest to oldest\n * @throws GitCommandError if operation fails\n * \n * @example\n * const history = await gitModule.getCommitHistory(\"main\", { maxCount: 10 });\n * // => [{ hash: \"abc123\", message: \"Initial commit\", author: \"User <email>\", date: \"2025-01-01T00:00:00Z\" }]\n */\n async getCommitHistory(\n branch: string,\n options?: GetCommitHistoryOptions\n ): Promise<CommitInfo[]> {\n const args = ['log', branch, '--format=%H|%s|%an <%ae>|%aI'];\n\n if (options?.maxCount) {\n args.push(`--max-count=${options.maxCount}`);\n }\n\n if (options?.pathFilter) {\n args.push('--', options.pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to get commit history for ${branch}`, result.stderr);\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n // Parse output: \"hash|message|author|date\"\n return result.stdout\n .trim()\n .split('\\n')\n .map((line) => {\n const parts = line.split('|');\n if (parts.length < 4) {\n throw new GitCommandError('Invalid git log output format', line);\n }\n return {\n hash: parts[0]!,\n message: parts[1]!,\n author: parts[2]!,\n date: parts[3]!,\n };\n });\n }\n\n /**\n * Retrieves commit history in a specific range\n * \n * @param fromHash - Starting commit hash (exclusive)\n * @param toHash - Ending commit hash (inclusive)\n * @param options - Filtering and formatting options\n * @returns Array of commits in the specified range\n * @throws GitCommandError if either commit doesn't exist\n * \n * @example\n * const commits = await gitModule.getCommitHistoryRange(\"abc123\", \"def456\");\n * // => [{ hash: \"def456\", ... }, { hash: \"cba321\", ... }]\n */\n async getCommitHistoryRange(\n fromHash: string,\n toHash: string,\n options?: GetCommitHistoryOptions\n ): Promise<CommitInfo[]> {\n const args = ['log', `${fromHash}..${toHash}`, '--format=%H|%s|%an <%ae>|%aI'];\n\n if (options?.maxCount) {\n args.push(`--max-count=${options.maxCount}`);\n }\n\n if (options?.pathFilter) {\n args.push('--', options.pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to get commit history range ${fromHash}..${toHash}`,\n result.stderr\n );\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n // Parse output: \"hash|message|author|date\"\n return result.stdout\n .trim()\n .split('\\n')\n .map((line) => {\n const parts = line.split('|');\n if (parts.length < 4) {\n throw new GitCommandError('Invalid git log output format', line);\n }\n return {\n hash: parts[0]!,\n message: parts[1]!,\n author: parts[2]!,\n date: parts[3]!,\n };\n });\n }\n\n /**\n * Retrieves the full commit message for a specific commit\n * \n * @param commitHash - Commit hash\n * @returns Full commit message as string\n * @throws GitCommandError if commit doesn't exist\n * \n * @example\n * const message = await gitModule.getCommitMessage(\"abc123\");\n * // => \"feat: add new feature\\n\\nDetailed description...\"\n */\n async getCommitMessage(commitHash: string): Promise<string> {\n const result = await this.execGit(['show', commitHash, '--format=%B', '--no-patch']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to get commit message for ${commitHash}`, result.stderr);\n }\n\n return result.stdout.trim();\n }\n\n /**\n * Checks if there are uncommitted changes in the working directory\n * \n * @param pathFilter - Optional path filter (e.g., \".gitgov/\")\n * @returns true if there are uncommitted changes, false otherwise\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hasChanges = await gitModule.hasUncommittedChanges(\".gitgov/\");\n * // => true\n */\n async hasUncommittedChanges(pathFilter?: string): Promise<boolean> {\n const args = ['status', '--porcelain'];\n\n if (pathFilter) {\n args.push('--', pathFilter);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to check for uncommitted changes', result.stderr);\n }\n\n return result.stdout.trim().length > 0;\n }\n\n /**\n * Checks if a rebase operation is currently in progress\n * \n * @returns true if rebase is in progress, false otherwise\n * \n * @example\n * const inRebase = await gitModule.isRebaseInProgress();\n * // => false\n */\n async isRebaseInProgress(): Promise<boolean> {\n const repoRoot = await this.ensureRepoRoot();\n const rebaseMergePath = path.join(repoRoot, '.git', 'rebase-merge');\n const rebaseApplyPath = path.join(repoRoot, '.git', 'rebase-apply');\n\n return fs.existsSync(rebaseMergePath) || fs.existsSync(rebaseApplyPath);\n }\n\n /**\n * Checks if a branch exists locally\n * \n * @param branchName - Branch name to check\n * @returns true if branch exists, false otherwise\n * \n * @example\n * const exists = await gitModule.branchExists(\"feature-branch\");\n * // => true\n */\n async branchExists(branchName: string): Promise<boolean> {\n const result = await this.execGit(['branch', '--list', branchName]);\n\n if (result.exitCode !== 0) {\n return false;\n }\n\n return result.stdout.trim().length > 0;\n }\n\n /**\n * Lists all remote branches for a given remote\n * \n * @param remoteName - Name of the remote (e.g., \"origin\")\n * @returns Array of remote branch names without the remote prefix\n * @throws GitCommandError if operation fails\n * \n * @example\n * const branches = await gitModule.listRemoteBranches(\"origin\");\n * // => [\"main\", \"develop\", \"gitgov-state\"]\n * \n * @note This method only returns the branch names, not the full \"origin/branch\" format\n */\n async listRemoteBranches(remoteName: string): Promise<string[]> {\n const result = await this.execGit(['branch', '-r', '--list', `${remoteName}/*`]);\n\n if (result.exitCode !== 0) {\n // If command fails, return empty array (e.g., remote doesn't exist)\n return [];\n }\n\n const output = result.stdout.trim();\n if (!output) {\n return [];\n }\n\n // Parse output: \" origin/main\\n origin/develop\"\n // Strip \"origin/\" prefix and whitespace\n return output\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0)\n .map(line => {\n // Remove \"remoteName/\" prefix\n const prefix = `${remoteName}/`;\n if (line.startsWith(prefix)) {\n return line.substring(prefix.length);\n }\n return line;\n })\n .filter(branch => branch.length > 0);\n }\n\n /**\n * Checks if a remote is configured in the git repository.\n *\n * @param remoteName - Name of the remote to check (e.g., \"origin\")\n * @returns true if the remote is configured, false otherwise\n *\n * @example\n * const hasOrigin = await gitModule.isRemoteConfigured(\"origin\");\n * // => true\n */\n async isRemoteConfigured(remoteName: string): Promise<boolean> {\n const result = await this.execGit(['remote']);\n\n if (result.exitCode !== 0) {\n return false;\n }\n\n const remotes = result.stdout.trim().split('\\n').filter(Boolean);\n return remotes.includes(remoteName);\n }\n\n /**\n * Retrieves the tracking remote for a branch\n *\n * @param branchName - Branch name\n * @returns Remote name or null if not configured\n * @throws BranchNotFoundError if branch doesn't exist\n *\n * @example\n * const remote = await gitModule.getBranchRemote(\"main\");\n * // => \"origin\"\n */\n async getBranchRemote(branchName: string): Promise<string | null> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit(['config', `branch.${branchName}.remote`]);\n\n if (result.exitCode !== 0) {\n return null;\n }\n\n return result.stdout.trim() || null;\n }\n\n /**\n * Retrieves the list of conflicted files during a rebase or merge\n * \n * @returns Array of file paths in conflict\n * @throws GitCommandError if no rebase/merge in progress\n * \n * @example\n * const conflicts = await gitModule.getConflictedFiles();\n * // => [\".gitgov/tasks/123.json\", \".gitgov/tasks/456.json\"]\n */\n async getConflictedFiles(): Promise<string[]> {\n const result = await this.execGit(['diff', '--name-only', '--diff-filter=U']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to get conflicted files', result.stderr);\n }\n\n if (!result.stdout.trim()) {\n return [];\n }\n\n return result.stdout.trim().split('\\n');\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // WRITE OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Switches to the specified branch\n * \n * @param branchName - Branch name to checkout\n * @throws BranchNotFoundError if branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.checkoutBranch(\"feature-branch\");\n */\n async checkoutBranch(branchName: string): Promise<void> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit(['checkout', branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to checkout branch ${branchName}`, result.stderr);\n }\n }\n\n /**\n * Stash uncommitted changes\n * \n * @param message - Optional message for the stash\n * @returns Stash hash if changes were stashed, null if nothing to stash\n */\n async stash(message?: string): Promise<string | null> {\n const hasChanges = await this.hasUncommittedChanges();\n if (!hasChanges) {\n return null; // Nothing to stash\n }\n\n const args = ['stash', 'push'];\n if (message) {\n args.push('-m', message);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to stash changes', result.stderr);\n }\n\n // Get the hash of the stash we just created\n const listResult = await this.execGit(['stash', 'list', '-n', '1', '--format=%H']);\n return listResult.stdout.trim() || null;\n }\n\n /**\n * Pop the most recent stash\n * \n * @returns true if stash was popped successfully, false if no stash exists\n */\n async stashPop(): Promise<boolean> {\n // Check if there are any stashes\n const listResult = await this.execGit(['stash', 'list']);\n if (!listResult.stdout.trim()) {\n return false; // No stashes to pop\n }\n\n const result = await this.execGit(['stash', 'pop']);\n\n if (result.exitCode !== 0) {\n // If pop fails, it might be due to conflicts - this is okay, we'll leave it stashed\n throw new GitCommandError('Failed to pop stash (conflicts may exist)', result.stderr);\n }\n\n return true;\n }\n\n /**\n * Drop a specific stash or the most recent one\n * \n * @param stashHash - Optional stash hash to drop, defaults to most recent\n */\n async stashDrop(stashHash?: string): Promise<void> {\n const args = ['stash', 'drop'];\n if (stashHash) {\n args.push(stashHash);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to drop stash', result.stderr);\n }\n }\n\n /**\n * Creates an orphan branch (no history) and switches to it\n * \n * @param branchName - Orphan branch name to create\n * @throws GitCommandError if branch already exists or operation fails\n * \n * @example\n * await gitModule.checkoutOrphanBranch(\"gitgov-state\");\n */\n async checkoutOrphanBranch(branchName: string): Promise<void> {\n const result = await this.execGit(['checkout', '--orphan', branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to create orphan branch ${branchName}`, result.stderr);\n }\n }\n\n /**\n * Fetches the latest changes from a remote repository\n * \n * @param remote - Remote name (e.g., \"origin\")\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.fetch(\"origin\");\n */\n async fetch(remote: string): Promise<void> {\n const result = await this.execGit(['fetch', remote]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to fetch from ${remote}`, result.stderr);\n }\n }\n\n /**\n * Pulls and merges a remote branch\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws MergeConflictError if merge conflicts occur\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pull(\"origin\", \"main\");\n */\n async pull(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['pull', '--no-rebase', remote, branchName]);\n\n if (result.exitCode !== 0) {\n // Check if conflict occurred (check both stdout and stderr)\n const output = result.stdout + result.stderr;\n if (output.includes('CONFLICT') || output.includes('Automatic merge failed') || output.includes('fix conflicts')) {\n const conflictedFiles = await this.getConflictedFiles();\n throw new MergeConflictError(conflictedFiles);\n }\n throw new GitCommandError(`Failed to pull from ${remote}/${branchName}`, result.stderr);\n }\n }\n\n /**\n * Pulls and rebases a remote branch\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws RebaseConflictError if rebase conflicts occur\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pullRebase(\"origin\", \"main\");\n */\n async pullRebase(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['pull', '--rebase', remote, branchName]);\n\n if (result.exitCode !== 0) {\n // Check if conflict occurred (check both stdout and stderr)\n const output = result.stdout + result.stderr;\n if (output.includes('CONFLICT') || output.includes('could not apply') || output.includes('fix conflicts') || output.includes('Resolve all conflicts')) {\n const conflictedFiles = await this.getConflictedFiles();\n throw new RebaseConflictError(conflictedFiles);\n }\n throw new GitCommandError(`Failed to pull --rebase from ${remote}/${branchName}`, result.stderr);\n }\n }\n\n /**\n * Resets the current branch to a specific commit, discarding all local changes\n * \n * @param target - Commit hash or branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.resetHard(\"HEAD~1\");\n */\n async resetHard(target: string): Promise<void> {\n const result = await this.execGit(['reset', '--hard', target]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to reset --hard to ${target}`, result.stderr);\n }\n }\n\n /**\n * Checks out specific files from another branch into the current staging area\n * \n * @param sourceBranch - Source branch name\n * @param filePaths - Array of file paths to checkout\n * @throws BranchNotFoundError if source branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.checkoutFilesFromBranch(\"main\", [\".gitgov/tasks/123.json\"]);\n */\n async checkoutFilesFromBranch(sourceBranch: string, filePaths: string[]): Promise<void> {\n if (!(await this.branchExists(sourceBranch))) {\n throw new BranchNotFoundError(sourceBranch);\n }\n\n const result = await this.execGit(['checkout', sourceBranch, '--', ...filePaths]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to checkout files from ${sourceBranch}`,\n result.stderr\n );\n }\n }\n\n /**\n * Adds files to the staging area\n *\n * @param filePaths - Array of file paths to add\n * @param options - Optional settings (force: add ignored files)\n * @throws GitCommandError if operation fails\n *\n * @example\n * await gitModule.add([\".gitgov/tasks/123.json\"]);\n * await gitModule.add([\".gitgov\"], { force: true }); // Add ignored files\n */\n async add(filePaths: string[], options?: { force?: boolean; contentMap?: Record<string, string> }): Promise<void> {\n const args = ['add'];\n if (options?.force) {\n args.push('--force');\n }\n args.push(...filePaths);\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to add files', result.stderr);\n }\n }\n\n /**\n * Removes files from both working directory and staging area\n * \n * @param filePaths - Array of file paths to remove\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.rm([\".gitgov/tasks/123.json\"]);\n */\n async rm(filePaths: string[]): Promise<void> {\n const result = await this.execGit(['rm', ...filePaths]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to remove files', result.stderr);\n }\n }\n\n /**\n * Creates a new commit with staged files\n * \n * @param message - Commit message\n * @param author - Optional commit author\n * @returns Commit hash of the created commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.commit(\"feat: add new task\");\n * // => \"abc123def456...\"\n */\n async commit(message: string, author?: CommitAuthor): Promise<string> {\n // Use multiple -m arguments for multi-line messages\n // Git concatenates them with newlines\n const lines = message.split('\\n');\n const args = ['commit'];\n\n // Add each line as a separate -m argument\n for (const line of lines) {\n args.push('-m', line);\n }\n\n if (author) {\n args.push('--author', `${author.name} <${author.email}>`);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n // Include both stdout and stderr in error for better diagnostics\n // (git commit outputs \"nothing to commit\" to stdout, not stderr)\n throw new GitCommandError('Failed to create commit', result.stderr, undefined, result.stdout);\n }\n\n // Get the commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n return hashResult.stdout.trim();\n }\n\n /**\n * Creates an empty commit (no changes required)\n * \n * @param message - Commit message\n * @param author - Optional commit author\n * @returns Commit hash of the created commit\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.commitAllowEmpty(\"chore: initialize state branch\");\n * // => \"abc123def456...\"\n */\n async commitAllowEmpty(message: string, author?: CommitAuthor): Promise<string> {\n const args = ['commit', '--allow-empty', '-m', message];\n\n if (author) {\n args.push('--author', `${author.name} <${author.email}>`);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to create empty commit', result.stderr);\n }\n\n // Get the commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n return hashResult.stdout.trim();\n }\n\n /**\n * Pushes a local branch to a remote repository\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.push(\"origin\", \"main\");\n */\n async push(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['push', remote, branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to push ${branchName} to ${remote}`, result.stderr);\n }\n }\n\n /**\n * Pushes a local branch to a remote repository and sets up tracking\n * \n * @param remote - Remote name\n * @param branchName - Branch name\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.pushWithUpstream(\"origin\", \"feature-branch\");\n */\n async pushWithUpstream(remote: string, branchName: string): Promise<void> {\n const result = await this.execGit(['push', '-u', remote, branchName]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to push ${branchName} to ${remote} with upstream`,\n result.stderr\n );\n }\n }\n\n /**\n * Configures tracking for a local branch with a remote branch\n * \n * @param branchName - Local branch name\n * @param remote - Remote name\n * @param remoteBranch - Remote branch name\n * @throws BranchNotFoundError if local branch doesn't exist\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.setUpstream(\"feature-branch\", \"origin\", \"feature-branch\");\n */\n async setUpstream(\n branchName: string,\n remote: string,\n remoteBranch: string\n ): Promise<void> {\n if (!(await this.branchExists(branchName))) {\n throw new BranchNotFoundError(branchName);\n }\n\n const result = await this.execGit([\n 'branch',\n '--set-upstream-to',\n `${remote}/${remoteBranch}`,\n branchName,\n ]);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(`Failed to set upstream for ${branchName}`, result.stderr);\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // REBASE OPERATIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n /**\n * Continues a rebase after resolving conflicts\n * \n * @returns Commit hash of the rebased commit\n * @throws RebaseNotInProgressError if no rebase is in progress\n * @throws GitCommandError if operation fails\n * \n * @example\n * const hash = await gitModule.rebaseContinue();\n * // => \"abc123def456...\"\n */\n async rebaseContinue(): Promise<string> {\n if (!(await this.isRebaseInProgress())) {\n throw new RebaseNotInProgressError();\n }\n\n logger.debug('Continuing rebase...');\n const result = await this.execGit(['rebase', '--continue']);\n\n if (result.exitCode !== 0) {\n logger.error(`Rebase continue failed: ${result.stderr}`);\n throw new GitCommandError('Failed to continue rebase', result.stderr);\n }\n\n // Get the current commit hash\n const hashResult = await this.execGit(['rev-parse', 'HEAD']);\n const commitHash = hashResult.stdout.trim();\n logger.info(`Rebase continued successfully, commit: ${commitHash.substring(0, 8)}...`);\n return commitHash;\n }\n\n /**\n * Aborts an ongoing rebase\n * \n * @throws RebaseNotInProgressError if no rebase is in progress\n * @throws GitCommandError if operation fails\n * \n * @example\n * await gitModule.rebaseAbort();\n */\n async rebaseAbort(): Promise<void> {\n if (!(await this.isRebaseInProgress())) {\n throw new RebaseNotInProgressError();\n }\n\n const result = await this.execGit(['rebase', '--abort']);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError('Failed to abort rebase', result.stderr);\n }\n }\n\n /**\n * Creates a new branch and switches to it (git checkout -b)\n * \n * @param branchName - Name of the branch to create\n * @param startPoint - Optional starting point (commit hash or branch name)\n * @throws GitCommandError if branch already exists or operation fails\n * @throws BranchAlreadyExistsError if the branch already exists locally\n */\n async createBranch(branchName: string, startPoint?: string): Promise<void> {\n // Check if branch already exists\n const exists = await this.branchExists(branchName);\n if (exists) {\n throw new BranchAlreadyExistsError(branchName);\n }\n\n const args = ['checkout', '-b', branchName];\n if (startPoint) {\n args.push(startPoint);\n }\n\n const result = await this.execGit(args);\n\n if (result.exitCode !== 0) {\n throw new GitCommandError(\n `Failed to create branch ${branchName}`,\n result.stderr\n );\n }\n\n logger.debug(`Created and checked out branch: ${branchName}`);\n }\n\n /**\n * Rebases current branch onto target branch (git rebase)\n * \n * @param targetBranch - Branch to rebase onto\n * @throws GitCommandError if rebase fails\n * @throws RebaseConflictError if conflicts are detected during rebase\n */\n async rebase(targetBranch: string): Promise<void> {\n const result = await this.execGit(['rebase', targetBranch]);\n\n if (result.exitCode !== 0) {\n // Check if it's a conflict\n if (result.stderr.includes('CONFLICT') || result.stderr.includes('conflict')) {\n // Get conflicted files if possible\n try {\n const conflictedFiles = await this.getConflictedFiles();\n throw new RebaseConflictError(conflictedFiles);\n } catch {\n // If we can't get files, throw with empty array\n throw new RebaseConflictError([]);\n }\n }\n\n throw new GitCommandError(\n `Failed to rebase onto ${targetBranch}`,\n result.stderr\n );\n }\n\n logger.debug(`Rebased onto: ${targetBranch}`);\n }\n}\n\n","/**\n * Project Discovery Utilities\n *\n * Filesystem-based utilities for discovering GitGovernance project roots.\n * Used at CLI bootstrap to resolve projectRoot before injecting it via DI.\n *\n * NOTE: These functions should only be called at the CLI/bootstrap level.\n * Core modules receive projectRoot via constructor injection.\n */\n\nimport * as path from 'path';\nimport { existsSync } from 'fs';\n\n// Project root cache for performance\nlet projectRootCache: string | null = null;\nlet lastSearchPath: string | null = null;\n\n/**\n * Finds the project root by searching upwards for a .git directory.\n * Caches the result for subsequent calls.\n *\n * @param startPath - Starting path (default: process.cwd())\n * @returns Path to project root, or null if not found\n */\nexport function findProjectRoot(startPath: string = process.cwd()): string | null {\n // In test environment, allow cache reset via global\n if (typeof (global as any).projectRoot !== 'undefined' && (global as any).projectRoot === null) {\n projectRootCache = null;\n lastSearchPath = null;\n }\n\n // Reset cache if we're searching from a different directory\n if (lastSearchPath && lastSearchPath !== startPath) {\n projectRootCache = null;\n lastSearchPath = null;\n }\n\n if (projectRootCache && lastSearchPath === startPath) {\n return projectRootCache;\n }\n\n lastSearchPath = startPath;\n\n let currentPath = startPath;\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.git'))) {\n projectRootCache = currentPath;\n return projectRootCache;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at the root directory\n if (existsSync(path.join(currentPath, '.git'))) {\n projectRootCache = currentPath;\n return projectRootCache;\n }\n\n return null;\n}\n\n/**\n * Finds the project root by searching upwards.\n * First looks for .gitgov (initialized project), then .git (for init).\n *\n * @param startPath - Starting path (default: process.cwd())\n * @returns Path to project root, or null if not found\n */\nexport function findGitgovRoot(startPath: string = process.cwd()): string | null {\n let currentPath = startPath;\n\n // First pass: Look for .gitgov (initialized GitGovernance project)\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.gitgov'))) {\n return currentPath;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at root for .gitgov\n if (existsSync(path.join(currentPath, '.gitgov'))) {\n return currentPath;\n }\n\n // Second pass: Look for .git (for init command)\n currentPath = startPath;\n while (currentPath !== path.parse(currentPath).root) {\n if (existsSync(path.join(currentPath, '.git'))) {\n return currentPath;\n }\n currentPath = path.dirname(currentPath);\n }\n\n // Final check at root for .git\n if (existsSync(path.join(currentPath, '.git'))) {\n return currentPath;\n }\n\n return null;\n}\n\n/**\n * Gets the .gitgov directory path from project root.\n *\n * @throws Error if not inside a GitGovernance project\n */\nexport function getGitgovPath(): string {\n const root = findGitgovRoot();\n if (!root) {\n throw new Error(\"Could not find project root. Make sure you are inside a GitGovernance repository.\");\n }\n return path.join(root, '.gitgov');\n}\n\n/**\n * Checks if current directory is inside a GitGovernance project.\n */\nexport function isGitgovProject(): boolean {\n try {\n const gitgovPath = getGitgovPath();\n return existsSync(gitgovPath);\n } catch {\n return false;\n }\n}\n\n/**\n * Reset the project root cache.\n * Useful for testing when switching between project contexts.\n */\nexport function resetDiscoveryCache(): void {\n projectRootCache = null;\n lastSearchPath = null;\n}\n","/**\n * Base error class for all sync-related errors\n */\nexport class SyncStateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SyncStateError\";\n Object.setPrototypeOf(this, SyncStateError.prototype);\n }\n}\n\n/**\n * Error thrown when attempting to push from gitgov-state branch\n */\nexport class PushFromStateBranchError extends SyncStateError {\n public branch: string;\n\n constructor(branchName: string) {\n super(\n `Cannot push from ${branchName} branch. ` +\n `Please switch to a working branch before pushing state.`\n );\n this.name = \"PushFromStateBranchError\";\n this.branch = branchName;\n Object.setPrototypeOf(this, PushFromStateBranchError.prototype);\n }\n}\n\n/**\n * Error thrown when integrity violations are detected during audit\n */\nexport class IntegrityViolationError extends SyncStateError {\n constructor(\n public violations: Array<{\n type: \"resolution\" | \"signature\" | \"checksum\" | \"missing_file\";\n details: string;\n }>\n ) {\n const violationSummary = violations\n .map((v) => `${v.type}: ${v.details}`)\n .join(\"; \");\n super(`Integrity violations detected: ${violationSummary}`);\n this.name = \"IntegrityViolationError\";\n Object.setPrototypeOf(this, IntegrityViolationError.prototype);\n }\n}\n\n/**\n * Error thrown when conflict markers are still present in files\n */\nexport class ConflictMarkersPresentError extends SyncStateError {\n constructor(public filesWithMarkers: string[]) {\n super(\n `Conflict markers still present in ${filesWithMarkers.length} file(s). ` +\n `Please resolve all conflicts before continuing.`\n );\n this.name = \"ConflictMarkersPresentError\";\n Object.setPrototypeOf(this, ConflictMarkersPresentError.prototype);\n }\n}\n\n/**\n * Error thrown when attempting to resolve conflict without rebase in progress\n */\nexport class NoRebaseInProgressError extends SyncStateError {\n constructor() {\n super(\n `No rebase in progress. Cannot resolve conflict without an active rebase. ` +\n `Use 'pullState' or 'pushState' to trigger synchronization first.`\n );\n this.name = \"NoRebaseInProgressError\";\n Object.setPrototypeOf(this, NoRebaseInProgressError.prototype);\n }\n}\n\n/**\n * Error thrown when CryptoModule is required but not available\n */\nexport class CryptoModuleRequiredError extends SyncStateError {\n constructor(operation: string) {\n super(\n `CryptoModule is required for ${operation} operation. ` +\n `Please provide crypto_module in SyncStateModuleDependencies.`\n );\n this.name = \"CryptoModuleRequiredError\";\n Object.setPrototypeOf(this, CryptoModuleRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when state branch cannot be created or configured\n */\nexport class StateBranchSetupError extends SyncStateError {\n constructor(\n public reason: string,\n public underlyingError?: Error\n ) {\n super(`Failed to setup state branch: ${reason}`);\n this.name = \"StateBranchSetupError\";\n Object.setPrototypeOf(this, StateBranchSetupError.prototype);\n }\n}\n\n/**\n * Error thrown when the provided actorId doesn't match the authenticated identity.\n *\n * This prevents impersonation: you can only push/resolve as the actor whose\n * private key you hold.\n */\nexport class ActorIdentityMismatchError extends SyncStateError {\n public requestedActorId: string;\n public authenticatedActorId: string;\n\n constructor(requestedActorId: string, authenticatedActorId: string) {\n super(\n `Actor identity mismatch: requested '${requestedActorId}' but authenticated as '${authenticatedActorId}'. ` +\n `You can only operate as the actor whose private key you hold.`\n );\n this.name = \"ActorIdentityMismatchError\";\n this.requestedActorId = requestedActorId;\n this.authenticatedActorId = authenticatedActorId;\n Object.setPrototypeOf(this, ActorIdentityMismatchError.prototype);\n }\n}\n\n/**\n * Error thrown when uncommitted changes exist in state branch\n */\nexport class UncommittedChangesError extends SyncStateError {\n public branch: string;\n\n constructor(branchName: string) {\n super(\n `Uncommitted changes detected in ${branchName}. ` +\n `Please commit or stash changes before synchronizing.`\n );\n this.name = \"UncommittedChangesError\";\n this.branch = branchName;\n Object.setPrototypeOf(this, UncommittedChangesError.prototype);\n }\n}\n\n/**\n * Type guards for error handling\n * \n * These functions enable type-safe error handling by narrowing the error type.\n * They are additive and don't break any existing code.\n * \n * Example usage:\n * ```typescript\n * try {\n * await syncModule.pushState(options);\n * } catch (error) {\n * if (isPushFromStateBranchError(error)) {\n * // TypeScript knows error.branch exists here\n * console.log(`Cannot push from ${error.branch}`);\n * }\n * }\n * ```\n */\n\nexport function isSyncStateError(error: unknown): error is SyncStateError {\n return error instanceof SyncStateError;\n}\n\nexport function isPushFromStateBranchError(\n error: unknown\n): error is PushFromStateBranchError {\n return error instanceof PushFromStateBranchError;\n}\n\nexport function isIntegrityViolationError(\n error: unknown\n): error is IntegrityViolationError {\n return error instanceof IntegrityViolationError;\n}\n\nexport function isConflictMarkersPresentError(\n error: unknown\n): error is ConflictMarkersPresentError {\n return error instanceof ConflictMarkersPresentError;\n}\n\nexport function isUncommittedChangesError(\n error: unknown\n): error is UncommittedChangesError {\n return error instanceof UncommittedChangesError;\n}\n\nexport function isNoRebaseInProgressError(\n error: unknown\n): error is NoRebaseInProgressError {\n return error instanceof NoRebaseInProgressError;\n}\n\nexport function isStateBranchSetupError(\n error: unknown\n): error is StateBranchSetupError {\n return error instanceof StateBranchSetupError;\n}\n\nexport function isCryptoModuleRequiredError(\n error: unknown\n): error is CryptoModuleRequiredError {\n return error instanceof CryptoModuleRequiredError;\n}\n\nexport function isActorIdentityMismatchError(\n error: unknown\n): error is ActorIdentityMismatchError {\n return error instanceof ActorIdentityMismatchError;\n}\n\n","import type { IGitModule } from '../git';\nimport type { ConfigManager } from \"../config_manager\";\nimport type { IIdentityAdapter } from \"../adapters/identity_adapter\";\nimport type { LintReport } from \"../lint\";\nimport type { ILintModule } from \"../lint\";\nimport type { IIndexerAdapter } from \"../adapters/indexer_adapter\";\n\n/**\n * SyncStateModule Dependencies\n */\nexport type SyncStateModuleDependencies = {\n /** Low-level Git module (required) */\n git: IGitModule;\n /** Configuration manager (required) */\n config: ConfigManager;\n /** Identity adapter for signature verification and signing (required) */\n identity: IIdentityAdapter;\n /** Lint module for record validation (required) */\n lint: ILintModule;\n /** Indexer adapter for automatic re-indexing after pull/resolve (required) */\n indexer: IIndexerAdapter;\n}\n\n/**\n * Options for pushState operation\n */\nexport type SyncStatePushOptions = {\n /** Branch to push from (default: current branch) */\n sourceBranch?: string;\n /** Actor ID publishing the state (required) */\n actorId: string;\n /** Simulate operation without making real changes */\n dryRun?: boolean;\n /** Force push even if there are unsynced remote changes */\n force?: boolean;\n}\n\n/**\n * Result of pushState operation\n */\nexport type SyncStatePushResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Number of files synced */\n filesSynced: number;\n /** Name of the branch pushed from */\n sourceBranch: string;\n /** Created commit hash (null if no changes or dry-run) */\n commitHash: string | null;\n /** Created commit message */\n commitMessage: string | null;\n /** Indicates if a conflict was detected during reconciliation */\n conflictDetected: boolean;\n /** Conflict information if detected */\n conflictInfo?: ConflictInfo;\n /** Error message if operation failed */\n error?: string;\n /** [EARS-B16] Implicit pull results when push does reconciliation with remote */\n implicitPull?: {\n /** Whether changes were pulled from remote */\n hasChanges: boolean;\n /** Number of files updated from remote */\n filesUpdated: number;\n /** Whether index was regenerated */\n reindexed: boolean;\n };\n}\n\n/**\n * Options for pullState operation\n */\nexport type SyncStatePullOptions = {\n /** Force re-indexing even if there are no new changes */\n forceReindex?: boolean;\n /** [EARS-C11] Force pull even if local changes would be overwritten */\n force?: boolean;\n}\n\n/**\n * Result of pullState operation\n */\nexport type SyncStatePullResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Indicates if there were new remote changes */\n hasChanges: boolean;\n /** Number of files updated */\n filesUpdated: number;\n /** Indicates if re-indexing was executed */\n reindexed: boolean;\n /** Indicates if a conflict was detected during pull */\n conflictDetected: boolean;\n /** Conflict information if detected */\n conflictInfo?: ConflictInfo;\n /** Error message if operation failed */\n error?: string;\n /** [EARS-C11] Files that were forcefully overwritten (when force: true) */\n forcedOverwrites?: string[];\n}\n\n/**\n * Options for resolveConflict operation\n */\nexport type SyncStateResolveOptions = {\n /** Justification for the conflict resolution (required) */\n reason: string;\n /** Actor ID resolving the conflict (required) */\n actorId: string;\n}\n\n/**\n * Result of resolveConflict operation\n */\nexport type SyncStateResolveResult = {\n /** Indicates if the operation was successful */\n success: boolean;\n /** Commit hash of the created rebase commit */\n rebaseCommitHash: string;\n /** Commit hash of the signed resolution commit */\n resolutionCommitHash: string;\n /** Number of conflicts resolved */\n conflictsResolved: number;\n /** Actor ID who resolved the conflict */\n resolvedBy: string;\n /** Reason for resolution */\n reason: string;\n /** Error message if operation failed */\n error?: string;\n}\n\n/**\n * Detailed information about a detected conflict\n */\nexport type ConflictInfo = {\n /** Type of conflict detected */\n type: ConflictType;\n /** Files affected by the conflict */\n affectedFiles: string[];\n /** Descriptive message of the conflict */\n message: string;\n /** Instructions to resolve the conflict */\n resolutionSteps: string[];\n}\n\n/**\n * Auxiliary type to identify the conflict type\n *\n * Git-Native conflict model (post-refactor):\n * - rebase_conflict: Used for all Git-level conflicts during push/pull\n * - local_changes_conflict: Used when pull would overwrite local changes (EARS-C10)\n * - integrity_violation: Used when resolution commits are missing\n */\nexport type ConflictType =\n | \"rebase_conflict\" // Conflict during automatic rebase (Git-native, includes EARS-B23 scenarios)\n | \"integrity_violation\" // Integrity violation (rebase without resolution commit)\n | \"local_changes_conflict\"; // [EARS-C10] Local changes would be overwritten by pull\n\n/**\n * Information about a detected integrity violation\n */\nexport type IntegrityViolation = {\n /** Commit hash of the rebase commit without resolution */\n rebaseCommitHash: string;\n /** Message of the rebase commit */\n commitMessage: string;\n /** Timestamp of the commit */\n timestamp: string;\n /** Author of the commit */\n author: string;\n}\n\n/**\n * Verification scope for state audit\n */\nexport type AuditScope =\n | \"current\" // Only verify Records in the current branch (useful for pre-push)\n | \"state-branch\" // Only verify Records in gitgov-state (useful for remote audit)\n | \"all\"; // Verify both (useful for complete audit)\n\n/**\n * Scope for expected files verification\n */\nexport type ExpectedFilesScope =\n | \"head\" // Only verify in HEAD of gitgov-state (default, faster)\n | \"all-commits\"; // Verify in all commits (more exhaustive, slower)\n\n/**\n * Options for state audit\n */\nexport type AuditStateOptions = {\n /** Verification scope: which Records to verify (default: \"all\") */\n scope?: AuditScope;\n /** Verify signatures in Records (default: true) */\n verifySignatures?: boolean;\n /** Verify checksums of Records (default: true) */\n verifyChecksums?: boolean;\n /** Verify that expected files exist (default: true) */\n verifyExpectedFiles?: boolean;\n /** Scope for expected files verification (default: \"head\") */\n expectedFilesScope?: ExpectedFilesScope;\n /** Path of specific files to audit (default: all in .gitgov/) */\n filePaths?: string[];\n}\n\n/**\n * Conflict diff information for a file\n */\nexport type ConflictFileDiff = {\n /** Path of the conflicted file */\n filePath: string;\n /** Content of the local version (ours) */\n localContent: string;\n /** Content of the remote version (theirs) */\n remoteContent: string;\n /** Base content (common ancestor) */\n baseContent: string | null;\n /** Lines with conflict markers (if they still exist) */\n conflictMarkers?: Array<{\n line: number;\n marker: string; // \"<<<<<\", \"=====\", \">>>>>\"\n }>;\n}\n\n/**\n * Structured conflict diff\n */\nexport type ConflictDiff = {\n /** Conflicted files with their diff */\n files: ConflictFileDiff[];\n /** Descriptive message of the conflict */\n message: string;\n /** Instructions to resolve */\n resolutionSteps: string[];\n}\n\n/**\n * Complete state audit report\n * \n * This report combines SyncStateModule-specific audits (rebase integrity, commits)\n * with structural validation from LintModule (signatures, checksums, schemas).\n */\nexport type AuditStateReport = {\n /** Indicates if the audit passed without violations */\n passed: boolean;\n /** Scope used for the audit */\n scope: AuditScope;\n /** Total commits analyzed */\n totalCommits: number;\n /** Rebase commits found */\n rebaseCommits: number;\n /** Resolution commits found */\n resolutionCommits: number;\n /** Integrity violations of resolutions (SyncStateModule-specific) */\n integrityViolations: IntegrityViolation[];\n /** Summary message of the audit */\n summary: string;\n /** Complete LintModule report for structural validation (signatures, checksums, schemas, etc.) */\n lintReport?: LintReport;\n}\n\n/**\n * Information of a changed file in the delta\n */\nexport type StateDeltaFile = {\n /** File status: Added, Modified, Deleted */\n status: \"A\" | \"M\" | \"D\";\n /** File path */\n file: string;\n}\n\n/**\n * Whitelist of files and directories allowed for synchronization.\n * Only these paths will be copied from .gitgov/ to gitgov-state.\n * \n * [EARS-B9] Explicitly defines what gets synced, avoiding temporary files,\n * builds, scripts, and local configurations like .gitignore\n * \n * Excluded (not in whitelist):\n * - builds/ (local build artifacts)\n * - scripts/ (local helper scripts)\n * - .gitignore (per-branch file, should not be synced)\n * - *.backup-* (backup files)\n * - *.tmp (temporary files)\n * - .DS_Store (macOS metadata)\n */\n/**\n * Directories to SYNC to gitgov-state branch (shared state)\n * Only *.json files within these directories will be synced\n */\nexport const SYNC_DIRECTORIES = [\n 'tasks',\n 'cycles',\n 'actors',\n 'agents',\n 'feedbacks',\n 'executions',\n 'changelogs',\n 'workflows',\n] as const;\n\n/**\n * Root-level files to SYNC to gitgov-state\n */\nexport const SYNC_ROOT_FILES = [\n 'config.json',\n] as const;\n\n/**\n * File extensions that are ALLOWED to be synced\n * Only these extensions will be copied to gitgov-state\n */\nexport const SYNC_ALLOWED_EXTENSIONS = ['.json'] as const;\n\n/**\n * File patterns that are NEVER synced (even if they match allowed extensions)\n * These are excluded from gitgov-state branch\n */\nexport const SYNC_EXCLUDED_PATTERNS = [\n /\\.key$/, // Private keys (e.g., actors/*.key)\n /\\.backup$/, // Backup files from lint\n /\\.backup-\\d+$/, // Numbered backup files\n /\\.tmp$/, // Temporary files\n /\\.bak$/, // Backup files\n] as const;\n\n/**\n * Files/directories that are LOCAL-ONLY (never synced to gitgov-state)\n * These are regenerated or machine-specific\n */\nexport const LOCAL_ONLY_FILES = [\n 'index.json', // Generated index, rebuilt on each machine\n '.session.json', // Local session state for current user/agent\n 'gitgov', // Local binary/script\n] as const;\n\n","import type { IGitModule } from '../../git';\nimport type { ConfigManager } from \"../../config_manager\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\nimport type { ILintModule } from \"../../lint\";\nimport type { IIndexerAdapter } from \"../../adapters/indexer_adapter\";\nimport { createLogger } from \"../../logger/logger\";\nimport type { EmbeddedMetadataRecord, GitGovRecordPayload } from \"../../record_types\";\nimport {\n SyncStateError,\n PushFromStateBranchError,\n ConflictMarkersPresentError,\n NoRebaseInProgressError,\n StateBranchSetupError,\n UncommittedChangesError,\n ActorIdentityMismatchError,\n} from \"../sync_state.errors\";\nimport type { ISyncStateModule } from \"../sync_state\";\nimport type {\n SyncStateModuleDependencies,\n SyncStatePushOptions,\n SyncStatePushResult,\n SyncStatePullOptions,\n SyncStatePullResult,\n SyncStateResolveOptions,\n SyncStateResolveResult,\n IntegrityViolation,\n AuditStateOptions,\n AuditStateReport,\n ConflictDiff,\n ConflictFileDiff,\n StateDeltaFile,\n} from \"../sync_state.types\";\nimport { readFileSync, existsSync, promises as fs, writeFileSync } from \"fs\";\nimport { join } from \"path\";\nimport path from \"path\";\nimport { exec } from \"child_process\";\nimport { promisify } from \"util\";\nimport os from \"os\";\nimport { SYNC_DIRECTORIES, SYNC_ROOT_FILES, SYNC_ALLOWED_EXTENSIONS, SYNC_EXCLUDED_PATTERNS, LOCAL_ONLY_FILES } from \"../sync_state.types\";\n\n// Create reusable helper\nconst execAsync = promisify(exec);\n\nconst logger = createLogger(\"[SyncStateModule] \");\n\n/**\n * Helper: Check if a file should be synced to gitgov-state\n * Returns true only for allowed *.json files in SYNC_DIRECTORIES or SYNC_ROOT_FILES\n *\n * Accepts paths in multiple formats:\n * - .gitgov/tasks/foo.json (git ls-files output)\n * - /absolute/path/.gitgov/tasks/foo.json\n * - /tmp/tempdir/tasks/foo.json (tempDir copy without .gitgov)\n * - tasks/foo.json (relative to .gitgov)\n */\nfunction shouldSyncFile(filePath: string): boolean {\n const fileName = path.basename(filePath);\n const ext = path.extname(filePath);\n\n // Check if extension is allowed\n if (!SYNC_ALLOWED_EXTENSIONS.includes(ext as typeof SYNC_ALLOWED_EXTENSIONS[number])) {\n return false;\n }\n\n // Check if file matches any excluded pattern (.key, .backup, etc.)\n for (const pattern of SYNC_EXCLUDED_PATTERNS) {\n if (pattern.test(fileName)) {\n return false;\n }\n }\n\n // Check if it's a local-only file (.session.json, index.json, gitgov)\n if (LOCAL_ONLY_FILES.includes(fileName as typeof LOCAL_ONLY_FILES[number])) {\n return false;\n }\n\n // CRITICAL: Verify file is in an allowed sync directory or is a root sync file\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n const parts = normalizedPath.split('/');\n\n // Find .gitgov in path and get the part after it\n const gitgovIndex = parts.findIndex(p => p === '.gitgov');\n\n let relativeParts: string[];\n if (gitgovIndex !== -1) {\n // Path contains .gitgov: .gitgov/tasks/foo.json or /path/.gitgov/tasks/foo.json\n relativeParts = parts.slice(gitgovIndex + 1);\n } else {\n // Path is relative to .gitgov or from tempDir: tasks/foo.json or /tmp/tempdir/tasks/foo.json\n // Check if any part matches a sync directory\n const syncDirIndex = parts.findIndex(p =>\n SYNC_DIRECTORIES.includes(p as typeof SYNC_DIRECTORIES[number])\n );\n if (syncDirIndex !== -1) {\n relativeParts = parts.slice(syncDirIndex);\n } else if (SYNC_ROOT_FILES.includes(fileName as typeof SYNC_ROOT_FILES[number])) {\n // It's a root sync file like config.json\n return true;\n } else {\n return false;\n }\n }\n\n if (relativeParts.length === 1) {\n // Root file: config.json\n return SYNC_ROOT_FILES.includes(relativeParts[0] as typeof SYNC_ROOT_FILES[number]);\n } else if (relativeParts.length >= 2) {\n // Directory file: tasks/foo.json\n const dirName = relativeParts[0];\n return SYNC_DIRECTORIES.includes(dirName as typeof SYNC_DIRECTORIES[number]);\n }\n\n return false;\n}\n\n/**\n * Helper: Recursively get all files in a directory\n */\nasync function getAllFiles(dir: string, baseDir: string = dir): Promise<string[]> {\n const files: string[] = [];\n\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n const subFiles = await getAllFiles(fullPath, baseDir);\n files.push(...subFiles);\n } else if (entry.isFile()) {\n files.push(path.relative(baseDir, fullPath));\n }\n }\n } catch {\n // Directory doesn't exist\n }\n\n return files;\n}\n\n/**\n * Helper: Copy only syncable files from source directory to destination\n * Filters to only copy *.json files, excluding keys, backups, etc.\n *\n * @param sourceDir - Source directory (tempDir with user's local files)\n * @param destDir - Destination directory (.gitgov in gitgov-state)\n * @param log - Logging function\n * @param excludeFiles - [EARS-B23] Files to exclude from copying (remote-only changes to preserve)\n */\nasync function copySyncableFiles(\n sourceDir: string,\n destDir: string,\n log: (msg: string) => void,\n excludeFiles: Set<string> = new Set()\n): Promise<number> {\n let copiedCount = 0;\n\n // Copy sync directories (only *.json files)\n for (const dirName of SYNC_DIRECTORIES) {\n const sourcePath = path.join(sourceDir, dirName);\n const destPath = path.join(destDir, dirName);\n\n try {\n const stat = await fs.stat(sourcePath);\n if (!stat.isDirectory()) continue;\n\n // Get all files recursively\n const allFiles = await getAllFiles(sourcePath);\n\n for (const relativePath of allFiles) {\n const fullSourcePath = path.join(sourcePath, relativePath);\n const fullDestPath = path.join(destPath, relativePath);\n // [EARS-B23] Check if this file should be excluded (remote-only change)\n const gitgovRelativePath = `.gitgov/${dirName}/${relativePath}`;\n\n if (excludeFiles.has(gitgovRelativePath)) {\n log(`[EARS-B23] Skipped (remote-only change preserved): ${gitgovRelativePath}`);\n continue;\n }\n\n if (shouldSyncFile(fullSourcePath)) {\n await fs.mkdir(path.dirname(fullDestPath), { recursive: true });\n await fs.copyFile(fullSourcePath, fullDestPath);\n log(`Copied: ${dirName}/${relativePath}`);\n copiedCount++;\n } else {\n log(`Skipped (not syncable): ${dirName}/${relativePath}`);\n }\n }\n } catch (error) {\n const errCode = (error as NodeJS.ErrnoException).code;\n if (errCode !== 'ENOENT') {\n log(`Error processing ${dirName}: ${error}`);\n }\n }\n }\n\n // Copy root-level sync files\n for (const fileName of SYNC_ROOT_FILES) {\n const sourcePath = path.join(sourceDir, fileName);\n const destPath = path.join(destDir, fileName);\n // [EARS-B23] Check if this file should be excluded\n const gitgovRelativePath = `.gitgov/${fileName}`;\n\n if (excludeFiles.has(gitgovRelativePath)) {\n log(`[EARS-B23] Skipped (remote-only change preserved): ${gitgovRelativePath}`);\n continue;\n }\n\n try {\n await fs.copyFile(sourcePath, destPath);\n log(`Copied root file: ${fileName}`);\n copiedCount++;\n } catch (error) {\n const errCode = (error as NodeJS.ErrnoException).code;\n if (errCode !== 'ENOENT') {\n log(`Error copying ${fileName}: ${error}`);\n }\n }\n }\n\n return copiedCount;\n}\n\n/**\n * FsSyncStateModule - Manages state synchronization between local environment and gitgov-state branch\n *\n * Responsibilities:\n * - Create and maintain the gitgov-state branch (local and remote)\n * - Publish local changes (pushState)\n * - Pull remote changes (pullState)\n * - Resolve conflicts in a governed manner (resolveConflict)\n * - Audit state integrity (auditState)\n *\n * Philosophy:\n * - Pipeline Pattern: Sequential operations with validation at each phase\n * - Fail-Fast: Early verifications to avoid costly operations\n * - Strict Dependencies: All dependencies (git, config, identity, lint, indexer) are required for robust operations\n */\nexport class FsSyncStateModule implements ISyncStateModule {\n private git: IGitModule;\n private config: ConfigManager;\n private identity: IIdentityAdapter;\n private lint: ILintModule;\n private indexer: IIndexerAdapter;\n\n /**\n * Constructor with dependency injection\n */\n constructor(dependencies: SyncStateModuleDependencies) {\n // Validate required dependencies\n if (!dependencies.git) {\n throw new Error('IGitModule is required for SyncStateModule');\n }\n if (!dependencies.config) {\n throw new Error(\"ConfigManager is required for SyncStateModule\");\n }\n if (!dependencies.identity) {\n throw new Error(\"IdentityAdapter is required for SyncStateModule\");\n }\n if (!dependencies.lint) {\n throw new Error(\"LintModule is required for SyncStateModule\");\n }\n if (!dependencies.indexer) {\n throw new Error(\"IndexerAdapter is required for SyncStateModule\");\n }\n\n this.git = dependencies.git;\n this.config = dependencies.config;\n this.identity = dependencies.identity;\n this.lint = dependencies.lint;\n this.indexer = dependencies.indexer;\n }\n\n /**\n * Static method to bootstrap .gitgov/ from gitgov-state branch.\n * Used when cloning a repo that has gitgov-state but .gitgov/ is not in the work branch.\n *\n * This method only requires GitModule and can be called before full SyncStateModule initialization.\n *\n * @param gitModule - GitModule instance for git operations\n * @param stateBranch - Name of the state branch (default: \"gitgov-state\")\n * @returns Promise<{ success: boolean; error?: string }>\n */\n static async bootstrapFromStateBranch(\n gitModule: IGitModule,\n stateBranch: string = \"gitgov-state\"\n ): Promise<{ success: boolean; error?: string }> {\n try {\n const repoRoot = await gitModule.getRepoRoot();\n\n // 1. Check if gitgov-state branch exists (local or remote)\n const hasLocalBranch = await gitModule.branchExists(stateBranch);\n\n let hasRemoteBranch = false;\n try {\n const remoteBranches = await gitModule.listRemoteBranches(\"origin\");\n hasRemoteBranch = remoteBranches.includes(stateBranch);\n } catch {\n // Remote might not be configured, continue with local check\n }\n\n if (!hasLocalBranch && !hasRemoteBranch) {\n return {\n success: false,\n error: `State branch '${stateBranch}' does not exist locally or remotely`,\n };\n }\n\n // 2. If only remote exists, fetch it\n if (!hasLocalBranch && hasRemoteBranch) {\n try {\n const currentBranch = await gitModule.getCurrentBranch();\n await gitModule.fetch(\"origin\");\n await execAsync(`git checkout -b ${stateBranch} origin/${stateBranch}`, { cwd: repoRoot });\n // Return to previous branch\n if (currentBranch && currentBranch !== stateBranch) {\n await gitModule.checkoutBranch(currentBranch);\n }\n } catch (error) {\n return {\n success: false,\n error: `Failed to fetch state branch: ${(error as Error).message}`,\n };\n }\n }\n\n // 3. Check if .gitgov/ exists in gitgov-state\n try {\n const { stdout } = await execAsync(`git ls-tree -r ${stateBranch} --name-only .gitgov/`, { cwd: repoRoot });\n if (!stdout.trim()) {\n return {\n success: false,\n error: `No .gitgov/ directory found in '${stateBranch}' branch`,\n };\n }\n } catch {\n return {\n success: false,\n error: `Failed to check .gitgov/ in '${stateBranch}' branch`,\n };\n }\n\n // 4. Copy .gitgov/ from gitgov-state to filesystem\n try {\n await execAsync(`git checkout ${stateBranch} -- .gitgov/`, { cwd: repoRoot });\n // Unstage the files (keep them untracked if .gitgov/ is ignored)\n await execAsync(\"git reset HEAD .gitgov/\", { cwd: repoRoot });\n logger.info(`[bootstrapFromStateBranch] Successfully restored .gitgov/ from ${stateBranch}`);\n } catch (error) {\n return {\n success: false,\n error: `Failed to copy .gitgov/ from state branch: ${(error as Error).message}`,\n };\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: `Bootstrap failed: ${(error as Error).message}`,\n };\n }\n }\n\n /**\n * Gets the state branch name from configuration.\n * Default: \"gitgov-state\"\n *\n * [EARS-A4]\n */\n async getStateBranchName(): Promise<string> {\n try {\n const config = await this.config.loadConfig();\n return config?.state?.branch ?? \"gitgov-state\";\n } catch {\n // If config loading fails, use default\n return \"gitgov-state\";\n }\n }\n\n /**\n * Ensures that the gitgov-state branch exists both locally and remotely.\n * If it doesn't exist, creates it as an orphan branch.\n *\n * Use cases (4 edge cases):\n * 1. Doesn't exist locally or remotely → Create orphan branch + initial commit + push\n * 2. Exists remotely, not locally → Fetch + create local + set tracking\n * 3. Exists locally, not remotely → Push + set tracking\n * 4. Exists both → Verify tracking\n *\n * [EARS-A1, EARS-A2, EARS-A3]\n */\n async ensureStateBranch(): Promise<void> {\n const stateBranch = await this.getStateBranchName();\n const remoteName = \"origin\";\n\n try {\n // Check local and remote existence\n const existsLocal = await this.git.branchExists(stateBranch);\n\n // Fetch to update remote references\n try {\n await this.git.fetch(remoteName);\n } catch {\n // If fetch fails (e.g., no remote configured), continue with local logic\n }\n\n // Check remote branch existence using GitModule\n const remoteBranches = await this.git.listRemoteBranches(remoteName);\n const existsRemote = remoteBranches.includes(stateBranch);\n\n // CASE 1: Doesn't exist locally or remotely → Create orphan branch + initial commit + push\n if (!existsLocal && !existsRemote) {\n await this.createOrphanStateBranch(stateBranch, remoteName);\n return;\n }\n\n // CASE 2: Exists remotely, not locally → Create local tracking remote\n if (!existsLocal && existsRemote) {\n const currentBranch = await this.git.getCurrentBranch();\n\n // Create local branch tracking remote\n // Use git checkout -b instead of checkoutOrphanBranch to create a tracking branch\n const repoRoot = await this.git.getRepoRoot();\n\n try {\n // Create local branch tracking the remote branch\n await execAsync(`git checkout -b ${stateBranch} ${remoteName}/${stateBranch}`, { cwd: repoRoot });\n\n // Branch is now created and tracking remote, return to original branch\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(currentBranch);\n }\n } catch (checkoutError) {\n // If checkout fails, try to return to original branch\n try {\n await this.git.checkoutBranch(currentBranch);\n } catch {\n // Ignore rollback error\n }\n throw checkoutError;\n }\n\n return;\n }\n\n // CASE 3: Exists locally, not remotely → Push + set tracking\n if (existsLocal && !existsRemote) {\n // Checkout to the branch to be able to push\n const currentBranch = await this.git.getCurrentBranch();\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(stateBranch);\n }\n\n try {\n await this.git.pushWithUpstream(remoteName, stateBranch);\n } catch {\n // If push fails (e.g., no remote configured), continue without error\n // Local branch remains available for local use\n }\n\n // Return to the original branch if it was different\n if (currentBranch !== stateBranch) {\n await this.git.checkoutBranch(currentBranch);\n }\n return;\n }\n\n // CASE 4: Exists both → Verify tracking\n if (existsLocal && existsRemote) {\n const upstreamBranch = await this.git.getBranchRemote(stateBranch);\n if (!upstreamBranch || upstreamBranch !== `${remoteName}/${stateBranch}`) {\n await this.git.setUpstream(stateBranch, remoteName, stateBranch);\n }\n return;\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new StateBranchSetupError(\n `Failed to ensure state branch ${stateBranch}: ${errorMessage}`,\n error as Error\n );\n }\n }\n\n /**\n * Creates the gitgov-state orphan branch with an empty initial commit.\n * Used by ensureStateBranch when the branch doesn't exist locally or remotely.\n *\n * [EARS-A1]\n */\n private async createOrphanStateBranch(\n stateBranch: string,\n remoteName: string\n ): Promise<void> {\n const currentBranch = await this.git.getCurrentBranch();\n const repoRoot = await this.git.getRepoRoot();\n\n // Check if current branch has any commits (required to return after creating orphan)\n const currentBranchHasCommits = await this.git.branchExists(currentBranch);\n if (!currentBranchHasCommits) {\n throw new Error(\n `Cannot initialize GitGovernance: branch '${currentBranch}' has no commits. ` +\n `Please create an initial commit first (e.g., 'git commit --allow-empty -m \"Initial commit\"').`\n );\n }\n\n try {\n // 1. Create orphan branch\n await this.git.checkoutOrphanBranch(stateBranch);\n\n // 2. Clean staging area and create initial commit\n // After `git checkout --orphan`, all files from previous branch are staged\n // We need to clear them and create an empty initial commit\n\n try {\n // Remove all staged files\n await execAsync(\"git rm -rf . 2>/dev/null || true\", { cwd: repoRoot });\n\n // [EARS-C10] Create .gitignore for LOCAL_ONLY_FILES and SYNC_EXCLUDED_PATTERNS\n // This prevents these files from appearing as untracked in gitgov-state\n const gitignoreContent = `# GitGovernance State Branch .gitignore\n# This file is auto-generated during gitgov init\n# These files are machine-specific and should NOT be synced\n\n# Local-only files (regenerated/machine-specific)\nindex.json\n.session.json\ngitgov\n\n# Private keys (never synced for security)\n*.key\n\n# Backup and temporary files\n*.backup\n*.backup-*\n*.tmp\n*.bak\n`;\n const gitignorePath = path.join(repoRoot, '.gitignore');\n await fs.writeFile(gitignorePath, gitignoreContent, 'utf-8');\n await execAsync('git add .gitignore', { cwd: repoRoot });\n\n // Create initial commit directly with exec (more reliable than GitModule methods for orphan branch)\n await execAsync('git commit -m \"Initialize state branch with .gitignore\"', { cwd: repoRoot });\n } catch (commitError) {\n const error = commitError as { stderr?: string; message?: string };\n throw new Error(`Failed to create initial commit on orphan branch: ${error.stderr || error.message}`);\n }\n\n // 5. Push with upstream (if remote is configured)\n // First check if the remote is actually configured\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n\n if (hasRemote) {\n try {\n await this.git.pushWithUpstream(remoteName, stateBranch);\n } catch (pushError) {\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n // Only ignore error if it's a remote connectivity issue\n // All other errors should be investigated/thrown\n const isRemoteError =\n pushErrorMsg.includes(\"does not appear to be\") ||\n pushErrorMsg.includes(\"Could not read from remote\") ||\n pushErrorMsg.includes(\"repository not found\");\n\n if (!isRemoteError) {\n // For other errors, propagate them (something went wrong)\n throw new Error(`Failed to push state branch to remote: ${pushErrorMsg}`);\n }\n // If remote connectivity issue, continue - local branch is functional\n logger.info(`Remote '${remoteName}' not reachable, gitgov-state branch created locally only`);\n }\n } else {\n // No remote configured, continue - local branch is functional\n logger.info(`No remote '${remoteName}' configured, gitgov-state branch created locally only`);\n }\n\n // 6. Return to original branch\n await this.git.checkoutBranch(currentBranch);\n } catch (error) {\n // Rollback: try to return to original branch\n try {\n await this.git.checkoutBranch(currentBranch);\n } catch {\n // Ignore rollback error\n }\n throw error;\n }\n }\n\n /**\n * Calculates the file delta in .gitgov/ between the current branch and gitgov-state.\n *\n * [EARS-A5]\n */\n async calculateStateDelta(sourceBranch: string): Promise<StateDeltaFile[]> {\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n\n try {\n // Get changes between stateBranch and sourceBranch, filtering only .gitgov/\n const changedFiles = await this.git.getChangedFiles(\n stateBranch,\n sourceBranch,\n \".gitgov/\"\n );\n\n return changedFiles.map((file) => ({\n status: file.status,\n file: file.file,\n }));\n } catch (error) {\n throw new SyncStateError(\n `Failed to calculate state delta: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * [EARS-B23] Detect file-level conflicts and identify remote-only changes.\n *\n * A conflict exists when:\n * 1. A file was modified by the remote during implicit pull\n * 2. AND the LOCAL USER also modified that same file (content in tempDir differs from what was in git before pull)\n *\n * This catches conflicts that git rebase can't detect because we copy files AFTER the pull.\n *\n * @param tempDir - Directory containing local .gitgov/ files (preserved before checkout)\n * @param repoRoot - Repository root path\n /**\n * Checks if a rebase is in progress.\n *\n * [EARS-D6]\n */\n async isRebaseInProgress(): Promise<boolean> {\n return await this.git.isRebaseInProgress();\n }\n\n /**\n * Checks for absence of conflict markers in specified files.\n * Returns list of files that still have markers.\n *\n * [EARS-D7]\n */\n async checkConflictMarkers(filePaths: string[]): Promise<string[]> {\n const repoRoot = await this.git.getRepoRoot();\n const filesWithMarkers: string[] = [];\n\n for (const filePath of filePaths) {\n try {\n const fullPath = join(repoRoot, filePath);\n if (!existsSync(fullPath)) {\n continue;\n }\n\n const content = readFileSync(fullPath, \"utf-8\");\n const hasMarkers =\n content.includes(\"<<<<<<<\") ||\n content.includes(\"=======\") ||\n content.includes(\">>>>>>>\");\n\n if (hasMarkers) {\n filesWithMarkers.push(filePath);\n }\n } catch {\n // If read fails, assume no markers\n continue;\n }\n }\n\n return filesWithMarkers;\n }\n\n /**\n * Gets the diff of conflicted files for manual analysis.\n * Useful so the actor can analyze conflicted changes before resolving.\n *\n * [EARS-E8]\n */\n async getConflictDiff(filePaths?: string[]): Promise<ConflictDiff> {\n try {\n // Get conflicted files\n let conflictedFiles: string[];\n if (filePaths && filePaths.length > 0) {\n conflictedFiles = filePaths;\n } else {\n conflictedFiles = await this.git.getConflictedFiles();\n }\n\n if (conflictedFiles.length === 0) {\n return {\n files: [],\n message: \"No conflicted files found\",\n resolutionSteps: [],\n };\n }\n\n const repoRoot = await this.git.getRepoRoot();\n const files: ConflictFileDiff[] = [];\n\n for (const filePath of conflictedFiles) {\n const fullPath = join(repoRoot, filePath);\n\n try {\n // Read current content (with conflict markers)\n const localContent = existsSync(fullPath)\n ? readFileSync(fullPath, \"utf-8\")\n : \"\";\n\n // For simplicity, remote and base content are left empty\n // In a complete implementation, git show :1:path and :3:path would be used\n const remoteContent = \"\";\n const baseContent: string | null = null;\n\n // Detect lines with markers\n const conflictMarkers: Array<{ line: number; marker: string }> = [];\n const lines = localContent.split(\"\\n\");\n lines.forEach((line, index) => {\n if (line.startsWith(\"<<<<<<<\")) {\n conflictMarkers.push({ line: index + 1, marker: \"<<<<<<\" });\n } else if (line.startsWith(\"=======\")) {\n conflictMarkers.push({ line: index + 1, marker: \"=======\" });\n } else if (line.startsWith(\">>>>>>>\")) {\n conflictMarkers.push({ line: index + 1, marker: \">>>>>>>\" });\n }\n });\n\n const fileDiff: ConflictFileDiff = {\n filePath,\n localContent,\n remoteContent,\n baseContent,\n };\n\n if (conflictMarkers.length > 0) {\n fileDiff.conflictMarkers = conflictMarkers;\n }\n\n files.push(fileDiff);\n } catch {\n // If reading a file fails, continue with the rest\n continue;\n }\n }\n\n return {\n files,\n message: `${files.length} file(s) in conflict`,\n resolutionSteps: [\n \"1. Review the conflict diff for each file\",\n \"2. Manually edit conflicted files to resolve conflicts\",\n \"3. Remove all conflict markers (<<<<<<<, =======, >>>>>>>)\",\n \"4. Run 'gitgov sync resolve' to complete the resolution\",\n ],\n };\n } catch (error) {\n throw new SyncStateError(\n `Failed to get conflict diff: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * Verifies integrity of previous resolutions in gitgov-state history.\n * Returns list of violations if any exist.\n *\n * [EARS-E1, EARS-E2, EARS-E3]\n */\n async verifyResolutionIntegrity(): Promise<IntegrityViolation[]> {\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n const violations: IntegrityViolation[] = [];\n\n try {\n // Check if state branch exists\n const branchExists = await this.git.branchExists(stateBranch);\n if (!branchExists) {\n // Branch doesn't exist yet - no violations\n return violations;\n }\n\n // Get commit history from gitgov-state\n let commits;\n try {\n commits = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1000, // Analyze last 1000 commits\n });\n } catch (error) {\n // If branch has no commits or getCommitHistory fails, return no violations\n return violations;\n }\n\n // Analyze history to detect rebase commits without resolution\n // A \"rebase commit\" is one created by git during rebase (contains conflict markers that were resolved)\n // A \"resolution commit\" is one created by gitgov sync resolve (starts with \"resolution:\")\n for (let i = 0; i < commits.length; i++) {\n const commit = commits[i];\n if (!commit) continue;\n\n const message = commit.message.toLowerCase();\n\n // Skip resolution commits - these are NOT rebase commits, they ARE the resolution\n if (message.startsWith(\"resolution:\")) {\n continue;\n }\n\n // Skip sync commits - these are normal sync operations\n if (message.startsWith(\"sync:\")) {\n continue;\n }\n\n // Detect explicit rebase-related commits (not our own commits)\n // Only flag commits that explicitly mention rebase operations\n const isExplicitRebaseCommit =\n message.includes(\"rebase\") ||\n message.includes(\"pick \");\n\n if (isExplicitRebaseCommit) {\n // Check if the next commit is a resolution\n const nextCommit = commits[i + 1];\n const isResolutionNext =\n nextCommit && nextCommit.message.toLowerCase().startsWith(\"resolution:\");\n\n if (!isResolutionNext) {\n violations.push({\n rebaseCommitHash: commit.hash,\n commitMessage: commit.message,\n timestamp: commit.date,\n author: commit.author,\n });\n }\n }\n }\n\n return violations;\n } catch (error) {\n // If verification fails for any reason, return empty violations\n // This prevents audit from blocking operations due to verification errors\n return violations;\n }\n }\n\n /**\n * Complete audit of gitgov-state status.\n * Verifies integrity of resolutions, signatures in Records, checksums and expected files.\n *\n * [EARS-E4, EARS-E5, EARS-E6, EARS-E7]\n */\n async auditState(\n options: AuditStateOptions = {}\n ): Promise<AuditStateReport> {\n const scope = options.scope ?? \"all\";\n const verifySignatures = options.verifySignatures ?? true;\n const verifyChecksums = options.verifyChecksums ?? true;\n\n const report: AuditStateReport = {\n passed: true,\n scope,\n totalCommits: 0,\n rebaseCommits: 0,\n resolutionCommits: 0,\n integrityViolations: [],\n summary: \"\",\n };\n\n try {\n // 1. Verify resolution integrity\n const integrityViolations = await this.verifyResolutionIntegrity();\n report.integrityViolations = integrityViolations;\n\n if (integrityViolations.length > 0) {\n report.passed = false;\n }\n\n // 2. Count rebase and resolution commits\n const stateBranch = await this.getStateBranchName();\n const branchExists = await this.git.branchExists(stateBranch);\n\n if (branchExists) {\n try {\n const commits = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1000,\n });\n\n report.totalCommits = commits.length;\n report.rebaseCommits = commits.filter((c) =>\n c.message.toLowerCase().includes(\"rebase\")\n ).length;\n report.resolutionCommits = commits.filter((c) =>\n c.message.toLowerCase().startsWith(\"resolution:\")\n ).length;\n } catch {\n // If getCommitHistory fails, use defaults (0)\n report.totalCommits = 0;\n report.rebaseCommits = 0;\n report.resolutionCommits = 0;\n }\n }\n\n // 3. Verify signatures and checksums using LintModule\n if (verifySignatures || verifyChecksums) {\n const lintReport = await this.lint.lint({\n validateChecksums: verifyChecksums,\n validateSignatures: verifySignatures,\n validateReferences: false,\n concurrent: true,\n });\n\n // Store complete LintReport for consumers to access detailed validation results\n report.lintReport = lintReport;\n\n // Update audit passed status based on lint errors\n if (lintReport.summary.errors > 0) {\n report.passed = false;\n }\n }\n\n // Note: Signature/checksum/file validation is delegated to LintModule\n\n // Generate summary\n const lintErrorCount = report.lintReport?.summary.errors || 0;\n const violationCount = report.integrityViolations.length + lintErrorCount;\n\n report.summary = report.passed\n ? `Audit passed. No violations found (scope: ${scope}).`\n : `Audit failed. Found ${violationCount} violation(s): ${report.integrityViolations.length} integrity + ${lintErrorCount} structural (scope: ${scope}).`;\n\n return report;\n } catch (error) {\n throw new SyncStateError(\n `Failed to audit state: ${(error as Error).message}`\n );\n }\n }\n\n /**\n * Publishes local state changes to gitgov-state.\n * Implements 3 phases: verification, reconciliation, publication.\n *\n * [EARS-B1 through EARS-B7]\n */\n async pushState(options: SyncStatePushOptions): Promise<SyncStatePushResult> {\n const { actorId, dryRun = false } = options;\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n let sourceBranch = options.sourceBranch;\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[pushState] ${msg}`);\n\n // Initialize result\n const result: SyncStatePushResult = {\n success: false,\n filesSynced: 0,\n sourceBranch: \"\",\n commitHash: null,\n commitMessage: null,\n conflictDetected: false,\n };\n\n // [EARS-B10] Declare stash tracking variables in outer scope for error handling\n let stashHash: string | null = null;\n let savedBranch: string = sourceBranch || \"\";\n\n try {\n log('=== STARTING pushState ===');\n\n // PRE-CHECK: Get current branch if not specified\n if (!sourceBranch) {\n sourceBranch = await this.git.getCurrentBranch();\n log(`Got current branch: ${sourceBranch}`);\n }\n result.sourceBranch = sourceBranch;\n\n // PRE-CHECK: Verify we're not on gitgov-state (EARS-B3)\n // This check must be FIRST, before audit\n if (sourceBranch === stateBranch) {\n log(`ERROR: Attempting to push from state branch ${stateBranch}`);\n throw new PushFromStateBranchError(stateBranch);\n }\n log(`Pre-check passed: pushing from ${sourceBranch} to ${stateBranch}`);\n\n // PRE-CHECK: Verify actorId matches authenticated identity\n // Prevents impersonation — you can only push as the actor whose key you hold\n const currentActor = await this.identity.getCurrentActor();\n if (currentActor.id !== actorId) {\n log(`ERROR: Actor identity mismatch: requested '${actorId}' but authenticated as '${currentActor.id}'`);\n throw new ActorIdentityMismatchError(actorId, currentActor.id);\n }\n log(`Pre-check passed: actorId '${actorId}' matches authenticated identity`);\n\n // [EARS-B11] PRE-CHECK 1: Verify remote is configured for push (FIRST!)\n // This must be checked first because without remote, sync makes no sense\n const remoteName = \"origin\";\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n if (!hasRemote) {\n log(`ERROR: No remote '${remoteName}' configured`);\n throw new SyncStateError(\n `No remote repository configured. ` +\n `State sync requires a remote for multi-machine collaboration.\\n` +\n `Add a remote with: git remote add origin <url>\\n` +\n `Then push your changes: git push -u origin ${sourceBranch}`\n );\n }\n log(`Pre-check passed: remote '${remoteName}' configured`);\n\n // [EARS-B11] PRE-CHECK 2: Verify current branch has commits\n // This is required for creating gitgov-state orphan branch and returning to original branch\n const hasCommits = await this.git.branchExists(sourceBranch);\n if (!hasCommits) {\n log(`ERROR: Branch '${sourceBranch}' has no commits`);\n throw new SyncStateError(\n `Cannot sync: branch '${sourceBranch}' has no commits. ` +\n `Please create an initial commit first (e.g., 'git commit --allow-empty -m \"Initial commit\"').`\n );\n }\n log(`Pre-check passed: branch '${sourceBranch}' has commits`);\n\n // PHASE 0: Integrity Verification and Audit (EARS-B1, EARS-B2)\n log('Phase 0: Starting audit...');\n const auditReport = await this.auditState({ scope: \"current\" });\n log(`Audit result: ${auditReport.passed ? 'PASSED' : 'FAILED'}`);\n\n if (!auditReport.passed) {\n log(`Audit violations: ${auditReport.summary}`);\n\n // Extract affected files from lint errors and integrity violations\n const affectedFiles: string[] = [];\n const detailedErrors: string[] = [];\n\n // Add files from lintReport errors\n if (auditReport.lintReport?.results) {\n for (const r of auditReport.lintReport.results) {\n if (r.level === 'error') {\n if (!affectedFiles.includes(r.filePath)) {\n affectedFiles.push(r.filePath);\n }\n detailedErrors.push(` • ${r.filePath}: [${r.validator}] ${r.message}`);\n }\n }\n }\n\n // Add info from integrity violations (commit-level)\n for (const v of auditReport.integrityViolations) {\n detailedErrors.push(` • Commit ${v.rebaseCommitHash.slice(0, 8)}: ${v.commitMessage} (by ${v.author})`);\n }\n\n // Build detailed message\n const detailSection = detailedErrors.length > 0\n ? `\\n\\nDetails:\\n${detailedErrors.join('\\n')}`\n : '';\n\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"integrity_violation\",\n affectedFiles,\n message: auditReport.summary + detailSection,\n resolutionSteps: [\n \"Run 'gitgov lint --fix' to auto-fix signature/checksum issues\",\n \"If issues persist, manually review the affected files\",\n \"Then retry: gitgov sync push\",\n ],\n };\n result.error = \"Integrity violations detected. Cannot push.\";\n return result;\n }\n\n // Ensure state branch exists\n log('Ensuring state branch exists...');\n await this.ensureStateBranch();\n log('State branch confirmed');\n\n // PHASE 1: Automatic Reconciliation (EARS-B4, EARS-B5)\n log('=== Phase 1: Reconciliation ===');\n savedBranch = sourceBranch;\n log(`Saved branch: ${savedBranch}`);\n\n // [EARS-B10] Check if current branch has untracked .gitgov/ files BEFORE stashing\n const isCurrentBranch = sourceBranch === (await this.git.getCurrentBranch());\n let hasUntrackedGitgovFiles = false;\n let tempDir: string | null = null;\n\n if (isCurrentBranch) {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovPath = path.join(repoRoot, '.gitgov');\n\n // Check if .gitgov/ EXISTS ON FILESYSTEM (not git status)\n // This is critical because .gitgov/ may be in .gitignore and git status won't show it\n hasUntrackedGitgovFiles = existsSync(gitgovPath);\n log(`[EARS-B10] .gitgov/ exists on filesystem: ${hasUntrackedGitgovFiles}`);\n\n // If untracked files exist, copy ENTIRE .gitgov/ to temp directory BEFORE stashing\n // This preserves ALL local files (not just SYNC_WHITELIST) for restoration after branch switch\n if (hasUntrackedGitgovFiles) {\n log('[EARS-B10] Copying ENTIRE .gitgov/ to temp directory for preservation...');\n\n tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gitgov-sync-'));\n log(`[EARS-B10] Created temp directory: ${tempDir}`);\n\n // Copy entire .gitgov/ directory to preserve ALL files (including local-only files)\n await fs.cp(gitgovPath, tempDir, { recursive: true });\n log('[EARS-B10] Entire .gitgov/ copied to temp');\n }\n }\n\n // [EARS-B10] Stash uncommitted changes before checkout to allow sync from dirty working tree\n // This is safe because:\n // 1. Stash preserves all local changes including .gitgov/\n // 2. We restore the stash when returning to original branch\n // 3. Enables seamless workflow: dev can work + sync without committing\n log('[EARS-B10] Checking for uncommitted changes before checkout...');\n const hasUncommittedBeforeCheckout = await this.git.hasUncommittedChanges();\n\n if (hasUncommittedBeforeCheckout) {\n log('[EARS-B10] Uncommitted changes detected, stashing before checkout...');\n stashHash = await this.git.stash('gitgov-sync-temp-stash');\n log(`[EARS-B10] Changes stashed: ${stashHash || 'none'}`);\n }\n\n // Helper function to restore stash AND tempDir when returning early\n const restoreStashAndReturn = async (returnResult: SyncStatePushResult): Promise<SyncStatePushResult> => {\n await this.git.checkoutBranch(savedBranch);\n\n // [EARS-B14] CRITICAL: Always restore tempDir FIRST to preserve local files (keys, etc.)\n if (tempDir) {\n try {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n // [EARS-B21] If implicit pull occurred, preserve new files from gitgov-state\n if (returnResult.implicitPull?.hasChanges) {\n log('[EARS-B21] Implicit pull detected in early return - preserving new files from gitgov-state...');\n // First checkout synced files from gitgov-state\n try {\n await this.git.checkoutFilesFromBranch(stateBranch, ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('[EARS-B21] Synced files copied from gitgov-state (unstaged)');\n } catch (checkoutError) {\n log(`[EARS-B21] Warning: Failed to checkout from gitgov-state: ${checkoutError}`);\n }\n // Then restore LOCAL_ONLY_FILES and EXCLUDED files from tempDir\n // [EARS-B22] This includes .key files which are excluded from sync but must be preserved\n for (const fileName of LOCAL_ONLY_FILES) {\n const tempFilePath = path.join(tempDir, fileName);\n const destFilePath = path.join(gitgovDir, fileName);\n try {\n await fs.access(tempFilePath);\n await fs.cp(tempFilePath, destFilePath, { force: true });\n log(`[EARS-B21] Restored LOCAL_ONLY_FILE: ${fileName}`);\n } catch {\n // File doesn't exist in temp, that's ok\n }\n }\n\n // [EARS-B22] Restore files matching SYNC_EXCLUDED_PATTERNS (e.g., .key files)\n const restoreExcludedFilesEarly = async (dir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(dir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcludedFilesEarly(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`[EARS-B22] Restored excluded file (early return): ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcludedFilesEarly(tempDir, gitgovDir);\n } else {\n // No implicit pull - restore everything from temp (original behavior)\n log('[EARS-B14] Restoring .gitgov/ from temp directory (early return)...');\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B14] .gitgov/ restored from temp (early return)');\n }\n\n // Cleanup temp\n await fs.rm(tempDir, { recursive: true, force: true });\n log('[EARS-B14] Temp directory cleaned up (early return)');\n } catch (tempRestoreError) {\n log(`[EARS-B14] WARNING: Failed to restore tempDir: ${tempRestoreError}`);\n returnResult.error = returnResult.error\n ? `${returnResult.error}. Failed to restore .gitgov/ from temp.`\n : `Failed to restore .gitgov/ from temp. Check /tmp for gitgov-sync-* directory.`;\n }\n }\n\n if (stashHash) {\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored');\n } catch (stashError) {\n log(`[EARS-B10] Failed to restore stash: ${stashError}`);\n returnResult.error = returnResult.error\n ? `${returnResult.error}. Failed to restore stashed changes.`\n : 'Failed to restore stashed changes. Run \\'git stash pop\\' manually.';\n }\n }\n\n // [EARS-B21] Regenerate index if implicit pull brought changes (even on early return)\n if (returnResult.implicitPull?.hasChanges) {\n log('[EARS-B21] Regenerating index after implicit pull (early return)...');\n try {\n await this.indexer.generateIndex();\n returnResult.implicitPull.reindexed = true;\n log('[EARS-B21] Index regenerated successfully');\n } catch (indexError) {\n log(`[EARS-B21] Warning: Failed to regenerate index: ${indexError}`);\n returnResult.implicitPull.reindexed = false;\n }\n }\n\n return returnResult;\n };\n\n // Checkout to gitgov-state\n log(`Checking out to ${stateBranch}...`);\n await this.git.checkoutBranch(stateBranch);\n log(`Now on branch: ${await this.git.getCurrentBranch()}`);\n\n // Note: We don't check for uncommitted changes here because:\n // 1. Untracked files from working tree (like .gitgov/) are expected and harmless\n // 2. If there are actual staged changes, git commit will detect them\n // 3. This allows seamless workflow without false positives from untracked files\n\n // [EARS-B19] Capture files in gitgov-state BEFORE any changes to distinguish user deletions vs new remote files\n let filesBeforeChanges: Set<string> = new Set();\n try {\n const repoRoot = await this.git.getRepoRoot();\n const { stdout: filesOutput } = await execAsync(\n `git ls-files \".gitgov\" 2>/dev/null || true`,\n { cwd: repoRoot }\n );\n filesBeforeChanges = new Set(filesOutput.trim().split('\\n').filter(f => f && shouldSyncFile(f)));\n log(`[EARS-B19] Files in gitgov-state before changes: ${filesBeforeChanges.size}`);\n } catch {\n // Ignore - might be first commit\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // GIT-NATIVE SYNC FLOW\n // Order: Copy files → Commit locally → Pull --rebase → Push\n // This allows Git to detect conflicts naturally (modify/modify, delete/modify)\n // ═══════════════════════════════════════════════════════════════════════════\n\n // PHASE 2: Stage Local Changes (EARS-B6, EARS-B7, EARS-B8, EARS-B9)\n log('=== Phase 2: Publication ===');\n\n // [EARS-B8] Detect first push: check if .gitgov/ exists in gitgov-state\n log('Checking if .gitgov/ exists in gitgov-state...');\n let isFirstPush = false;\n try {\n const repoRoot = await this.git.getRepoRoot();\n\n // Check if .gitgov/ directory exists in gitgov-state branch\n const { stdout } = await execAsync(\n `git ls-tree -d ${stateBranch} .gitgov`,\n { cwd: repoRoot }\n );\n\n isFirstPush = !stdout.trim(); // If empty, .gitgov/ doesn't exist\n log(`First push detected: ${isFirstPush}`);\n } catch (error) {\n // If command fails, assume first push\n log('Error checking .gitgov/ existence, assuming first push');\n isFirstPush = true;\n }\n\n // Calculate change delta (skip for first push, will copy everything from whitelist)\n let delta: StateDeltaFile[] = [];\n if (!isFirstPush) {\n log('Calculating state delta...');\n delta = await this.calculateStateDelta(sourceBranch);\n log(`Delta: ${delta.length} file(s) changed`);\n\n // If no changes, return without commit (EARS-B6)\n if (delta.length === 0) {\n log('No changes detected, returning without commit');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n } else {\n log('First push: will copy all whitelisted files');\n }\n\n // [EARS-B9] & [EARS-B10] Copy ONLY syncable files (*.json, no keys, no backups)\n log(`Copying syncable .gitgov/ files from ${sourceBranch}...`);\n log(`Sync directories: ${SYNC_DIRECTORIES.join(', ')}`);\n log(`Sync root files: ${SYNC_ROOT_FILES.join(', ')}`);\n\n const repoRoot = await this.git.getRepoRoot();\n\n // Note: untracked file detection was moved earlier, before stashing\n\n // If we have temp directory with untracked files, copy from there\n // Otherwise, use git checkout from source branch\n if (tempDir) {\n log('[EARS-B10] Copying ONLY syncable files from temp directory...');\n\n // Create .gitgov/ directory if it doesn't exist (first push to orphan branch)\n const gitgovDir = path.join(repoRoot, '.gitgov');\n await fs.mkdir(gitgovDir, { recursive: true });\n log(`[EARS-B10] Ensured .gitgov/ directory exists: ${gitgovDir}`);\n\n // Copy only syncable files (*.json, no keys, no backups)\n // Git-native flow: we copy ALL local files, then commit, then pull --rebase\n // Git will detect conflicts during rebase if same file was modified remotely\n const copiedCount = await copySyncableFiles(tempDir, gitgovDir, log);\n log(`[EARS-B10] Syncable files copy complete: ${copiedCount} files copied`);\n } else {\n // Use git checkout for tracked files\n log('Copying syncable files from git...');\n\n // Build list of paths that exist in source branch AND are syncable\n const existingPaths: string[] = [];\n\n // Check sync directories\n for (const dirName of SYNC_DIRECTORIES) {\n const fullPath = `.gitgov/${dirName}`;\n try {\n const { stdout } = await execAsync(\n `git ls-tree -r ${sourceBranch} -- ${fullPath}`,\n { cwd: repoRoot }\n );\n // Filter to only include syncable files (*.json, no keys, no backups)\n const lines = stdout.trim().split('\\n').filter(l => l);\n for (const line of lines) {\n const parts = line.split('\\t');\n const filePath = parts[1];\n if (filePath && shouldSyncFile(filePath)) {\n existingPaths.push(filePath);\n } else if (filePath) {\n log(`Skipped (not syncable): ${filePath}`);\n }\n }\n } catch {\n log(`Directory ${dirName} does not exist in ${sourceBranch}, skipping`);\n }\n }\n\n // Check root sync files\n for (const fileName of SYNC_ROOT_FILES) {\n const fullPath = `.gitgov/${fileName}`;\n try {\n const { stdout } = await execAsync(\n `git ls-tree ${sourceBranch} -- ${fullPath}`,\n { cwd: repoRoot }\n );\n if (stdout.trim()) {\n existingPaths.push(fullPath);\n }\n } catch {\n log(`File ${fileName} does not exist in ${sourceBranch}, skipping`);\n }\n }\n\n log(`Syncable paths found: ${existingPaths.length}`);\n\n if (existingPaths.length === 0) {\n log('No syncable files to sync, aborting');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Copy only syncable files\n await this.git.checkoutFilesFromBranch(sourceBranch, existingPaths);\n log('Syncable files checked out successfully');\n }\n\n // Create structured commit message\n const timestamp = new Date().toISOString();\n\n // For first push, we need to recalculate delta now that files are staged\n if (isFirstPush) {\n // Stage the copied files first\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n\n // Get list of staged files for commit message\n const repoRoot = await this.git.getRepoRoot();\n\n try {\n const { stdout } = await execAsync(\n 'git diff --cached --name-status',\n { cwd: repoRoot }\n );\n\n const lines = stdout.trim().split('\\n').filter(l => l);\n delta = lines\n .map(line => {\n const [status, file] = line.split('\\t');\n if (!file) return null; // Skip invalid lines\n return {\n status: status as 'A' | 'M' | 'D',\n file\n };\n })\n .filter((item): item is StateDeltaFile => item !== null);\n log(`First push delta calculated: ${delta.length} file(s)`);\n } catch (error) {\n log('Error calculating first push delta, using empty delta');\n delta = [];\n }\n }\n\n const commitMessage =\n `sync: ${isFirstPush ? 'Initial state' : 'Publish state'} from ${sourceBranch}\\n\\n` +\n `Actor: ${actorId}\\n` +\n `Timestamp: ${timestamp}\\n` +\n `Files: ${delta.length} file(s) ${isFirstPush ? 'synced (initial)' : 'changed'}\\n\\n` +\n delta.map((d) => `${d.status} ${d.file}`).join(\"\\n\");\n\n result.commitMessage = commitMessage;\n\n if (!dryRun) {\n // IMPORTANT: Stage ALL files FIRST, then cleanup non-syncable files\n // This ensures EARS-B14 can detect and remove untracked files from worktree\n // that shouldn't be synced (like .session.json, gitgov binary)\n if (!isFirstPush) {\n log('Staging all .gitgov/ files before cleanup...');\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n log('All files staged, proceeding to cleanup');\n }\n\n // [EARS-B14] Remove ALL non-syncable files from gitgov-state\n // This ensures only files that pass shouldSyncFile() remain in shared state\n // MUST run AFTER git add so we can detect and remove untracked files\n log('[EARS-B14] Scanning for non-syncable files in gitgov-state...');\n\n // Get ALL files currently in staging area for .gitgov/\n try {\n const { stdout: trackedFiles } = await execAsync(\n `git ls-files \".gitgov\" 2>/dev/null || true`,\n { cwd: repoRoot }\n );\n const allTrackedFiles = trackedFiles.trim().split('\\n').filter(f => f);\n log(`[EARS-B14] Found ${allTrackedFiles.length} staged/tracked files in .gitgov/`);\n\n // Remove any file that should NOT be synced (using the same shouldSyncFile() logic)\n for (const trackedFile of allTrackedFiles) {\n if (!shouldSyncFile(trackedFile)) {\n try {\n await execAsync(`git rm -f \"${trackedFile}\"`, { cwd: repoRoot });\n log(`[EARS-B14] Removed non-syncable file: ${trackedFile}`);\n } catch {\n // File might not exist or not be tracked anymore\n }\n }\n }\n } catch {\n // No tracked files, that's fine (first push)\n }\n\n log('[EARS-B14] Non-syncable files cleanup complete');\n\n // [EARS-B19] Sync deleted files: remove files from gitgov-state that no longer exist in source\n // This handles the case where a user deletes a record locally and pushes\n // In Git-native flow, deleted files will be detected during rebase if there's a conflict\n log('[EARS-B19] Checking for deleted files to sync...');\n\n try {\n // Get all syncable files in source (tempDir = user's local state)\n const sourceFiles = new Set<string>();\n\n // Recursively find all files in source\n const findSourceFiles = async (dir: string, prefix: string = '.gitgov') => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = `${prefix}/${entry.name}`;\n if (entry.isDirectory()) {\n await findSourceFiles(fullPath, relativePath);\n } else if (shouldSyncFile(relativePath)) {\n sourceFiles.add(relativePath);\n }\n }\n } catch {\n // Directory doesn't exist, that's ok\n }\n };\n\n // Use tempDir if available (untracked files case), otherwise working tree\n const sourceDir = tempDir || path.join(repoRoot, '.gitgov');\n await findSourceFiles(sourceDir);\n log(`[EARS-B19] Found ${sourceFiles.size} syncable files in source (user's local state)`);\n log(`[EARS-B19] Files that existed before changes: ${filesBeforeChanges.size}`);\n\n // Delete files that:\n // 1. Existed in gitgov-state BEFORE our changes (filesBeforeChanges)\n // 2. Are NOT in user's local state (sourceFiles/tempDir)\n // This ensures we only delete files the user intentionally removed\n let deletedCount = 0;\n for (const fileBeforeChange of filesBeforeChanges) {\n if (!sourceFiles.has(fileBeforeChange)) {\n try {\n await execAsync(`git rm -f \"${fileBeforeChange}\"`, { cwd: repoRoot });\n log(`[EARS-B19] Deleted (user removed): ${fileBeforeChange}`);\n deletedCount++;\n } catch {\n // File might already be removed or not tracked\n }\n }\n }\n log(`[EARS-B19] Deleted ${deletedCount} files that user removed locally`);\n } catch (err) {\n log(`[EARS-B19] Warning: Failed to sync deleted files: ${err}`);\n }\n\n // Verify there are staged changes\n const hasStaged = await this.git.hasUncommittedChanges();\n log(`Has staged changes: ${hasStaged}`);\n\n if (!hasStaged) {\n log('No staged changes detected, returning without commit');\n // No changes to commit - return early\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Create commit\n log('Creating local commit...');\n try {\n const commitHash = await this.git.commit(commitMessage);\n log(`Local commit created: ${commitHash}`);\n result.commitHash = commitHash;\n } catch (commitError) {\n // Check if this is a \"nothing to commit\" error (common on second push with identical files)\n const errorMsg = commitError instanceof Error ? commitError.message : String(commitError);\n const stdout = (commitError as any).stdout || '';\n const stderr = (commitError as any).stderr || '';\n\n log(`Commit attempt output - stdout: ${stdout}, stderr: ${stderr}`);\n\n // Git returns exit code 1 with \"nothing to commit\" in stdout when there are no changes\n const isNothingToCommit =\n stdout.includes('nothing to commit') ||\n stderr.includes('nothing to commit') ||\n stdout.includes('nothing added to commit') ||\n stderr.includes('nothing added to commit');\n\n if (isNothingToCommit) {\n log('Nothing to commit - files are identical to gitgov-state HEAD');\n result.success = true;\n result.filesSynced = 0;\n return await restoreStashAndReturn(result);\n }\n\n // Otherwise, it's a real error\n log(`ERROR: Commit failed: ${errorMsg}`);\n log(`ERROR: Git stderr: ${stderr}`);\n throw new Error(`Failed to create commit: ${errorMsg} | stderr: ${stderr}`);\n }\n\n // ═══════════════════════════════════════════════════════════════════════════\n // GIT-NATIVE CONFLICT DETECTION: Pull --rebase AFTER local commit\n // This is the key change: Git can now detect conflicts naturally because\n // we have a local commit to rebase onto the remote changes\n // ═══════════════════════════════════════════════════════════════════════════\n log('=== Phase 3: Reconcile with Remote (Git-Native) ===');\n\n // Capture hash before pull to detect if remote had changes\n let hashBeforePull: string | null = null;\n try {\n const { stdout: beforeHash } = await execAsync(`git rev-parse HEAD`, { cwd: repoRoot });\n hashBeforePull = beforeHash.trim();\n log(`Hash before pull: ${hashBeforePull}`);\n } catch {\n // Ignore\n }\n\n // Attempt pull --rebase to reconcile with remote\n log('Attempting git pull --rebase origin gitgov-state...');\n try {\n await this.git.pullRebase(\"origin\", stateBranch);\n log('Pull rebase successful - no conflicts');\n\n // [EARS-B16] Check if remote had changes (implicit pull)\n if (hashBeforePull) {\n try {\n const { stdout: afterHash } = await execAsync(`git rev-parse HEAD`, { cwd: repoRoot });\n const hashAfterPull = afterHash.trim();\n\n if (hashAfterPull !== hashBeforePull) {\n // Our commit was rebased on top of remote changes\n const pulledChangedFiles = await this.git.getChangedFiles(hashBeforePull, hashAfterPull, \".gitgov/\");\n result.implicitPull = {\n hasChanges: true,\n filesUpdated: pulledChangedFiles.length,\n reindexed: false // Will be set to true after actual reindex\n };\n log(`[EARS-B16] Implicit pull: ${pulledChangedFiles.length} files from remote were rebased`);\n }\n } catch (e) {\n log(`[EARS-B16] Could not capture implicit pull details: ${e}`);\n }\n }\n } catch (pullError) {\n const errorMsg = pullError instanceof Error ? pullError.message : String(pullError);\n log(`Pull rebase result: ${errorMsg}`);\n\n const isAlreadyUpToDate = errorMsg.includes(\"up to date\") || errorMsg.includes(\"up-to-date\");\n const isNoRemote = errorMsg.includes(\"does not appear to be\") || errorMsg.includes(\"Could not read from remote\");\n const isNoUpstream = errorMsg.includes(\"no tracking information\") || errorMsg.includes(\"There is no tracking information\");\n\n if (isAlreadyUpToDate || isNoRemote || isNoUpstream) {\n log('Pull not needed or no remote - continuing to push');\n // Continue - we'll just push our local commit\n } else {\n // Check if it's a conflict - THIS IS THE GIT-NATIVE CONFLICT DETECTION\n const isRebaseInProgress = await this.isRebaseInProgress();\n const conflictedFiles = await this.git.getConflictedFiles();\n\n if (isRebaseInProgress || conflictedFiles.length > 0) {\n log(`[GIT-NATIVE] Conflict detected! Files: ${conflictedFiles.join(', ')}`);\n\n // DO NOT abort - leave rebase in progress for user to resolve with git tools\n result.conflictDetected = true;\n // Build dynamic resolution steps based on number of conflicted files\n const fileWord = conflictedFiles.length === 1 ? \"file\" : \"files\";\n const stageCommand = conflictedFiles.length === 1\n ? `git add ${conflictedFiles[0]}`\n : \"git add .gitgov/\";\n\n result.conflictInfo = {\n type: \"rebase_conflict\",\n affectedFiles: conflictedFiles,\n message: \"Conflict detected during sync - Git has paused the rebase for manual resolution\",\n resolutionSteps: [\n `1. Edit the conflicted ${fileWord} to resolve conflicts (remove <<<<<<, ======, >>>>>> markers)`,\n `2. Stage resolved ${fileWord}: ${stageCommand}`,\n \"3. Complete sync: gitgov sync resolve --reason 'your reason'\",\n \"(This will continue the rebase, re-sign the record, and return you to your original branch)\"\n ]\n };\n result.error = `Conflict detected: ${conflictedFiles.length} file(s) need manual resolution. Use 'git status' to see details.`;\n\n // DO NOT restore to original branch - user must resolve in gitgov-state\n // But restore stash to original branch if there was one\n if (stashHash) {\n try {\n await this.git.checkoutBranch(sourceBranch);\n await execAsync('git stash pop', { cwd: repoRoot });\n await this.git.checkoutBranch(stateBranch);\n log('Restored stash to original branch during conflict');\n } catch (stashErr) {\n log(`Warning: Could not restore stash: ${stashErr}`);\n }\n }\n\n // CRITICAL: Restore LOCAL_ONLY_FILES and EXCLUDED files (.key) to gitgov-state\n // These are needed for signing during conflict resolution\n if (tempDir) {\n log('Restoring local files (.key, .session.json, etc.) for conflict resolution...');\n const gitgovInState = path.join(repoRoot, '.gitgov');\n\n // Restore LOCAL_ONLY_FILES\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(tempDir, fileName);\n const destPath = path.join(gitgovInState, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Restored LOCAL_ONLY_FILE for conflict resolution: ${fileName}`);\n } catch {\n // File doesn't exist in temp, ok\n }\n }\n\n // Restore EXCLUDED files (like .key) recursively\n const restoreExcluded = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcluded(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Restored EXCLUDED file for conflict resolution: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcluded(tempDir, gitgovInState);\n log('Local files restored for conflict resolution');\n }\n\n return result;\n }\n\n // Not a conflict, propagate the error\n throw pullError;\n }\n }\n\n // Push\n log('=== Phase 4: Push to Remote ===');\n log('Pushing to remote...');\n try {\n await this.git.push(\"origin\", stateBranch);\n log('Push successful');\n } catch (pushError) {\n // If push fails, check if it's a \"no remote\" error\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n log(`Push failed: ${pushErrorMsg}`);\n\n const isNoRemote = pushErrorMsg.includes(\"does not appear to be\") || pushErrorMsg.includes(\"Could not read from remote\");\n\n if (!isNoRemote) {\n log('ERROR: Push failed with non-remote error');\n // If it's not a \"no remote\" error, propagate it\n throw pushError;\n }\n log('Push failed due to no remote, continuing (local commit succeeded)');\n // Otherwise, continue - commit succeeded locally even if push failed\n }\n }\n\n // Return to original branch\n log(`Returning to ${savedBranch}...`);\n await this.git.checkoutBranch(savedBranch);\n log(`Back on ${await this.git.getCurrentBranch()}`);\n\n // [EARS-B10] Restore stashed changes\n if (stashHash) {\n log('[EARS-B10] Restoring stashed changes...');\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored successfully');\n } catch (stashError) {\n log(`[EARS-B10] Warning: Failed to restore stashed changes: ${stashError}`);\n // Don't fail the push if stash pop fails, but warn the user\n result.error = `Push succeeded but failed to restore stashed changes. Run 'git stash pop' manually. Error: ${stashError}`;\n }\n }\n\n // [EARS-B10] Restore files from temp directory back to working tree\n // [EARS-B18] If implicit pull occurred, we must keep the NEW synced files from gitgov-state,\n // only restoring LOCAL_ONLY_FILES from tempDir\n if (tempDir) {\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n if (result.implicitPull?.hasChanges) {\n // [EARS-B18] Implicit pull occurred - we need to preserve the new files from remote\n log('[EARS-B18] Implicit pull detected - copying synced files from gitgov-state first...');\n\n // First, checkout the synced directories/files from gitgov-state to work branch\n // This brings the newly pulled files to the work tree\n try {\n await this.git.checkoutFilesFromBranch(stateBranch, ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('[EARS-B18] Synced files copied from gitgov-state to work branch (unstaged)');\n } catch (checkoutError) {\n log(`[EARS-B18] Warning: Failed to checkout from gitgov-state: ${checkoutError}`);\n // Fall back to restoring everything from temp\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B18] Fallback: Entire .gitgov/ restored from temp');\n }\n\n // Then, restore LOCAL_ONLY_FILES and EXCLUDED files from tempDir (they're not in gitgov-state)\n // [EARS-B22] This includes .key files which are excluded from sync but must be preserved\n log('[EARS-B18] Restoring local-only files from temp directory...');\n\n // Restore LOCAL_ONLY_FILES (root level: .session.json, index.json, gitgov)\n for (const fileName of LOCAL_ONLY_FILES) {\n const tempFilePath = path.join(tempDir, fileName);\n const destFilePath = path.join(gitgovDir, fileName);\n try {\n await fs.access(tempFilePath);\n await fs.cp(tempFilePath, destFilePath, { force: true });\n log(`[EARS-B18] Restored LOCAL_ONLY_FILE: ${fileName}`);\n } catch {\n // File doesn't exist in temp, that's ok\n }\n }\n\n // [EARS-B22] Restore files matching SYNC_EXCLUDED_PATTERNS (e.g., .key files in actors/)\n // These are local-only files that exist in subdirectories\n const restoreExcludedFiles = async (dir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(dir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n\n if (entry.isDirectory()) {\n await restoreExcludedFiles(srcPath, dstPath);\n } else {\n // Check if this file matches any excluded pattern\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`[EARS-B22] Restored excluded file: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist, that's ok\n }\n };\n\n await restoreExcludedFiles(tempDir, gitgovDir);\n log('[EARS-B22] Local-only and excluded files restored from temp');\n } else {\n // No implicit pull - restore everything from temp (original behavior)\n log('[EARS-B10] Restoring ENTIRE .gitgov/ from temp directory to working tree...');\n await fs.cp(tempDir, gitgovDir, { recursive: true, force: true });\n log('[EARS-B10] Entire .gitgov/ restored from temp');\n }\n\n // Cleanup temp directory\n log('[EARS-B10] Cleaning up temp directory...');\n try {\n await fs.rm(tempDir, { recursive: true, force: true });\n log('[EARS-B10] Temp directory cleaned up');\n } catch (cleanupError) {\n log(`[EARS-B10] Warning: Failed to cleanup temp directory: ${cleanupError}`);\n }\n }\n\n // [EARS-B17] If implicit pull occurred, regenerate index NOW (after returning to work branch)\n // Previously, reindexed: true was just a flag but indexer was never called - BUG!\n if (result.implicitPull?.hasChanges) {\n log('[EARS-B16] Regenerating index after implicit pull...');\n try {\n await this.indexer.generateIndex();\n result.implicitPull.reindexed = true;\n log('[EARS-B16] Index regenerated successfully after implicit pull');\n } catch (indexError) {\n log(`[EARS-B16] Warning: Failed to regenerate index after implicit pull: ${indexError}`);\n result.implicitPull.reindexed = false;\n }\n }\n\n result.success = true;\n result.filesSynced = delta.length;\n log(`=== pushState COMPLETED SUCCESSFULLY: ${delta.length} files synced ===`);\n return result;\n } catch (error) {\n log(`=== pushState FAILED: ${(error as Error).message} ===`);\n\n // [EARS-B10] Try to restore original branch even on error (ALWAYS, not just with stash)\n try {\n const currentBranch = await this.git.getCurrentBranch();\n if (currentBranch !== savedBranch && savedBranch) {\n log(`[EARS-B10] Restoring original branch: ${savedBranch}...`);\n await this.git.checkoutBranch(savedBranch);\n log(`[EARS-B10] Restored to ${savedBranch}`);\n }\n } catch (branchError) {\n log(`[EARS-B10] Failed to restore original branch: ${branchError}`);\n }\n\n // [EARS-B10] Try to restore stashed changes if any\n if (stashHash) {\n log('[EARS-B10] Attempting to restore stashed changes after error...');\n try {\n await this.git.stashPop();\n log('[EARS-B10] Stashed changes restored after error');\n } catch (stashError) {\n log(`[EARS-B10] Failed to restore stashed changes after error: ${stashError}`);\n // Add to error message\n const originalError = (error as Error).message;\n (error as Error).message = `${originalError}. Additionally, failed to restore stashed changes. Run 'git stash pop' manually.`;\n }\n }\n\n // Re-throw critical errors that should fail fast\n if (\n error instanceof PushFromStateBranchError ||\n error instanceof UncommittedChangesError\n ) {\n throw error;\n }\n\n // For other errors, return result with error message\n result.error = (error as Error).message;\n return result;\n }\n }\n\n /**\n * Pulls remote changes from gitgov-state to the local environment.\n * Includes automatic re-indexing if there are new changes.\n *\n * [EARS-C1 through EARS-C4]\n * [EARS-C5] Requires remote to be configured (pull without remote makes no sense)\n */\n async pullState(\n options: SyncStatePullOptions = {}\n ): Promise<SyncStatePullResult> {\n const { forceReindex = false, force = false } = options;\n const stateBranch = await this.getStateBranchName();\n if (!stateBranch) {\n throw new SyncStateError(\"Failed to get state branch name\");\n }\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[pullState] ${msg}`);\n\n // Initialize result\n const result: SyncStatePullResult = {\n success: false,\n hasChanges: false,\n filesUpdated: 0,\n reindexed: false,\n conflictDetected: false,\n };\n\n try {\n log('=== STARTING pullState ===');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 0: Pre-flight Checks (EARS-C5)\n // ═══════════════════════════════════════════════════════════\n log('Phase 0: Pre-flight checks...');\n\n // [EARS-C5] PRE-CHECK: Verify remote is configured (pull without remote is meaningless)\n const remoteName = \"origin\";\n const hasRemote = await this.git.isRemoteConfigured(remoteName);\n\n if (!hasRemote) {\n throw new SyncStateError(\n `No remote '${remoteName}' configured. Pull requires a remote repository. ` +\n `Add a remote with: git remote add origin <url>`\n );\n }\n\n // [EARS-C5] PRE-CHECK: Verify gitgov-state exists remotely\n // Fetch first to get latest remote refs\n await this.git.fetch(remoteName);\n const remoteBranches = await this.git.listRemoteBranches(remoteName);\n const existsRemote = remoteBranches.includes(stateBranch);\n\n if (!existsRemote) {\n // Check if local branch exists (maybe not pushed yet)\n const existsLocal = await this.git.branchExists(stateBranch);\n\n if (!existsLocal) {\n // Check if .gitgov/ exists - if so, user already ran init and just needs to push\n const repoRoot = await this.git.getRepoRoot();\n const gitgovPath = path.join(repoRoot, \".gitgov\");\n const gitgovExists = existsSync(gitgovPath);\n\n if (gitgovExists) {\n // User has .gitgov/ but hasn't pushed yet - suggest sync push\n throw new SyncStateError(\n `State branch '${stateBranch}' does not exist remotely yet. ` +\n `Run 'gitgov sync push' to publish your local state to the remote.`\n );\n } else {\n // User hasn't initialized at all\n throw new SyncStateError(\n `State branch '${stateBranch}' does not exist locally or remotely. ` +\n `Run 'gitgov init' first to initialize GitGovernance, then 'gitgov sync push' to publish.`\n );\n }\n }\n\n // Local exists but remote doesn't - nothing to pull\n result.success = true;\n result.hasChanges = false;\n result.filesUpdated = 0;\n logger.info(`[pullState] State branch exists locally but not remotely. Nothing to pull.`);\n return result;\n }\n\n log('Pre-flight checks complete');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 1: Branch Setup and Verification\n // ═══════════════════════════════════════════════════════════\n log('Phase 1: Setting up branches...');\n\n // Get repoRoot early for use throughout this function\n const pullRepoRoot = await this.git.getRepoRoot();\n\n // 1. Pre-checks - ensure local branch tracks remote\n await this.ensureStateBranch();\n\n const savedBranch = await this.git.getCurrentBranch();\n\n // [EARS-C8] Save LOCAL_ONLY_FILES before checkout\n // When .gitgov/ is untracked on work branch but tracked on gitgov-state,\n // git checkout will fail or overwrite files. We save local-only files first.\n const savedLocalFiles: Map<string, string> = new Map();\n try {\n for (const fileName of LOCAL_ONLY_FILES) {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n try {\n const content = await fs.readFile(filePath, \"utf-8\");\n savedLocalFiles.set(fileName, content);\n log(`[EARS-C8] Saved local-only file: ${fileName}`);\n } catch {\n // File doesn't exist, that's fine\n }\n }\n } catch (error) {\n log(`[EARS-C8] Warning: Could not save local files: ${(error as Error).message}`);\n }\n\n // [EARS-C10] Save ALL syncable files BEFORE checkout for conflict detection\n // We need to compare local changes vs remote changes BEFORE checkout overwrites them\n const savedSyncableFiles: Map<string, string> = new Map();\n try {\n const gitgovPath = path.join(pullRepoRoot, \".gitgov\");\n const gitgovExists = await fs.access(gitgovPath).then(() => true).catch(() => false);\n\n if (gitgovExists) {\n // Recursively read all syncable files\n const readSyncableFilesRecursive = async (dir: string, baseDir: string) => {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relativePath = path.relative(baseDir, fullPath);\n const gitgovRelativePath = `.gitgov/${relativePath}`;\n\n if (entry.isDirectory()) {\n await readSyncableFilesRecursive(fullPath, baseDir);\n } else if (shouldSyncFile(gitgovRelativePath)) {\n try {\n const content = await fs.readFile(fullPath, 'utf-8');\n savedSyncableFiles.set(gitgovRelativePath, content);\n } catch {\n // Ignore read errors\n }\n }\n }\n } catch {\n // Ignore directory read errors\n }\n };\n\n await readSyncableFilesRecursive(gitgovPath, gitgovPath);\n log(`[EARS-C10] Saved ${savedSyncableFiles.size} syncable files before checkout for conflict detection`);\n }\n } catch (error) {\n log(`[EARS-C10] Warning: Could not save syncable files: ${(error as Error).message}`);\n }\n\n // Checkout to gitgov-state\n // Use force to handle case where .gitgov/ is untracked on work branch\n // but tracked on gitgov-state (would otherwise fail with \"would be overwritten\")\n try {\n await this.git.checkoutBranch(stateBranch);\n } catch (checkoutError) {\n // If normal checkout fails, try with force\n log(`[EARS-C8] Normal checkout failed, trying with force: ${(checkoutError as Error).message}`);\n try {\n await execAsync(`git checkout -f ${stateBranch}`, { cwd: pullRepoRoot });\n log(`[EARS-C8] Force checkout successful`);\n } catch (forceError) {\n // Still failed - rethrow original error\n throw checkoutError;\n }\n }\n\n // Verify no staged or modified changes (ignore untracked files)\n // Untracked files from work branch are expected and harmless in gitgov-state\n try {\n // Check only for staged (A, M, D) or modified (M) files, NOT untracked (??)\n const { stdout } = await execAsync('git status --porcelain', { cwd: pullRepoRoot });\n const lines = stdout.trim().split('\\n').filter(l => l);\n const hasStagedOrModified = lines.some(line => {\n const status = line.substring(0, 2);\n // Ignore untracked files (??), only check for staged/modified\n return status !== '??' && status.trim().length > 0;\n });\n\n if (hasStagedOrModified) {\n await this.git.checkoutBranch(savedBranch);\n throw new UncommittedChangesError(stateBranch);\n }\n } catch (error) {\n if (error instanceof UncommittedChangesError) {\n throw error;\n }\n // If git status fails, continue (branch might be clean)\n }\n\n log('Branch setup complete');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 2: Pull Remote Changes (EARS-C1, EARS-C2)\n // ═══════════════════════════════════════════════════════════\n log('Phase 2: Pulling remote changes...');\n\n // 2. Save current commit to compare later\n const commitBefore = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1,\n });\n const hashBefore = commitBefore[0]?.hash;\n\n // 3. Fetch to get remote refs\n await this.git.fetch(\"origin\");\n\n // ═══════════════════════════════════════════════════════════\n // [EARS-C10] CONFLICT DETECTION: Detect if local changes would be overwritten\n // Compare: savedSyncableFiles (captured BEFORE checkout) vs gitgov-state vs origin/gitgov-state\n // If same file modified locally AND remotely → abort like git pull does\n // ═══════════════════════════════════════════════════════════\n log('[EARS-C10] Checking for local changes that would be overwritten...');\n\n // Step 1: Get files that changed in remote (origin/gitgov-state vs local gitgov-state)\n let remoteChangedFiles: string[] = [];\n try {\n const { stdout: remoteChanges } = await execAsync(\n `git diff --name-only ${stateBranch} origin/${stateBranch} -- .gitgov/ 2>/dev/null || true`,\n { cwd: pullRepoRoot }\n );\n remoteChangedFiles = remoteChanges.trim().split('\\n').filter(f => f && shouldSyncFile(f));\n log(`[EARS-C10] Remote changed files: ${remoteChangedFiles.length} - ${remoteChangedFiles.join(', ')}`);\n } catch {\n log('[EARS-C10] Could not determine remote changes, continuing...');\n }\n\n // Step 2: Check if local files (saved BEFORE checkout) differ from gitgov-state HEAD\n // This detects: user edited file locally that was also edited remotely\n let localModifiedFiles: string[] = [];\n if (remoteChangedFiles.length > 0 && savedSyncableFiles.size > 0) {\n try {\n for (const remoteFile of remoteChangedFiles) {\n // Check if we have a saved version of this file (from before checkout)\n const savedContent = savedSyncableFiles.get(remoteFile);\n\n if (savedContent !== undefined) {\n // Get content from gitgov-state HEAD (what was synced last time)\n try {\n const { stdout: gitStateContent } = await execAsync(\n `git show HEAD:${remoteFile} 2>/dev/null`,\n { cwd: pullRepoRoot }\n );\n\n // Compare saved local content vs last synced content\n // If different, user modified this file locally since last sync\n if (savedContent !== gitStateContent) {\n localModifiedFiles.push(remoteFile);\n log(`[EARS-C10] Local file was modified since last sync: ${remoteFile}`);\n }\n } catch {\n // File doesn't exist in gitgov-state HEAD (new file locally)\n // This is also a local modification\n localModifiedFiles.push(remoteFile);\n log(`[EARS-C10] Local file is new (not in gitgov-state): ${remoteFile}`);\n }\n }\n }\n log(`[EARS-C10] Local modified files that overlap with remote: ${localModifiedFiles.length}`);\n } catch (error) {\n log(`[EARS-C10] Warning: Could not check local modifications: ${(error as Error).message}`);\n }\n }\n\n // Step 3: If there's overlap (same file modified locally AND remotely)\n if (localModifiedFiles.length > 0) {\n // [EARS-C11] If force flag is set, continue and overwrite local changes\n if (force) {\n log(`[EARS-C11] Force flag set - will overwrite ${localModifiedFiles.length} local file(s)`);\n logger.warn(`[pullState] Force pull: overwriting local changes to ${localModifiedFiles.length} file(s)`);\n result.forcedOverwrites = localModifiedFiles;\n } else {\n // [EARS-C10] Abort and restore local changes\n log(`[EARS-C10] CONFLICT: Local changes would be overwritten by pull`);\n\n // Return to original branch before aborting\n await this.git.checkoutBranch(savedBranch);\n\n // Restore ALL saved syncable files (user's local changes that would be overwritten)\n for (const [filePath, content] of savedSyncableFiles) {\n const fullPath = path.join(pullRepoRoot, filePath);\n try {\n await fs.mkdir(path.dirname(fullPath), { recursive: true });\n await fs.writeFile(fullPath, content, \"utf-8\");\n log(`[EARS-C10] Restored syncable file: ${filePath}`);\n } catch {\n // Ignore restore errors\n }\n }\n\n // Also restore LOCAL_ONLY_FILES\n for (const [fileName, content] of savedLocalFiles) {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n try {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, content, \"utf-8\");\n log(`[EARS-C10] Restored local-only file: ${fileName}`);\n } catch {\n // Ignore restore errors\n }\n }\n\n result.success = false;\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"local_changes_conflict\",\n affectedFiles: localModifiedFiles,\n message: `Your local changes to the following files would be overwritten by pull.\\nYou have modified these files locally, and they were also modified remotely.\\nTo avoid losing your changes, push first or use --force to overwrite.`,\n resolutionSteps: [\n \"1. Run 'gitgov sync push' to push your local changes first\",\n \" → This will trigger a rebase and let you resolve conflicts properly\",\n \"2. Or run 'gitgov sync pull --force' to discard your local changes\",\n ],\n };\n result.error = \"Aborting pull: local changes would be overwritten by remote changes\";\n\n logger.warn(`[pullState] Aborting: local changes to ${localModifiedFiles.length} file(s) would be overwritten by pull`);\n return result;\n }\n }\n\n log('[EARS-C10] No conflicting local changes (or force enabled), proceeding with pull...');\n\n // 4. Pull --rebase (EARS-C1, EARS-C2)\n try {\n await this.git.pullRebase(\"origin\", stateBranch);\n } catch (error) {\n // Detect conflict\n const conflictedFiles = await this.git.getConflictedFiles();\n if (conflictedFiles.length > 0) {\n // Pause rebase (DO NOT abort) and return conflict\n await this.git.checkoutBranch(savedBranch);\n\n result.conflictDetected = true;\n result.conflictInfo = {\n type: \"rebase_conflict\",\n affectedFiles: conflictedFiles,\n message: \"Conflict detected during pull\",\n resolutionSteps: [\n \"Review conflicted files\",\n \"Manually resolve conflicts\",\n \"Run 'gitgov sync resolve' to complete\",\n ],\n };\n result.error = \"Conflict detected during pull\";\n return result;\n }\n\n // If not a conflict, propagate error\n throw error;\n }\n\n log('Pull rebase successful');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 3: Re-indexing and File Updates (EARS-C3, EARS-C4)\n // ═══════════════════════════════════════════════════════════\n log('Phase 3: Checking for changes and re-indexing...');\n\n // 4. Check if there are new changes (EARS-C3)\n const commitAfter = await this.git.getCommitHistory(stateBranch, {\n maxCount: 1,\n });\n const hashAfter = commitAfter[0]?.hash;\n\n const hasNewChanges = hashBefore !== hashAfter;\n result.hasChanges = hasNewChanges;\n\n // 5. Calculate if reindex is needed (EARS-C3, EARS-C4, EARS-C9)\n // NOTE: Actual reindex happens AFTER file restoration in Phase 4\n // [EARS-C9] Also reindex if index.json doesn't exist (bootstrap scenario)\n const indexPath = path.join(pullRepoRoot, '.gitgov', 'index.json');\n const indexExists = await fs.access(indexPath).then(() => true).catch(() => false);\n const shouldReindex = hasNewChanges || forceReindex || !indexExists;\n if (shouldReindex) {\n result.reindexed = true;\n\n // Calculate number of changed files\n if (hasNewChanges && hashBefore && hashAfter) {\n const changedFiles = await this.git.getChangedFiles(\n hashBefore,\n hashAfter,\n \".gitgov/\"\n );\n result.filesUpdated = changedFiles.length;\n }\n }\n\n // 6. Copy .gitgov/ to filesystem in work branch (EARS-B10 complement)\n // When .gitgov/ is ignored in work branch, we need to manually copy files\n // from gitgov-state to the filesystem so they're available for CLI commands\n const gitgovPath = path.join(pullRepoRoot, \".gitgov\");\n\n // Check if .gitgov/ exists in gitgov-state\n const gitgovExists = await fs.access(gitgovPath).then(() => true).catch(() => false);\n\n if (gitgovExists && hasNewChanges) {\n logger.debug(\"[pullState] Copying .gitgov/ to filesystem for work branch access\");\n // Files will be copied when we return to savedBranch\n // Git will preserve .gitgov/ in the filesystem even though it's ignored\n }\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 4: Restore Working Branch and Cleanup\n // ═══════════════════════════════════════════════════════════\n log('Phase 4: Restoring working branch...');\n\n // 7. Return to original branch\n await this.git.checkoutBranch(savedBranch);\n\n // After returning to work branch, ALWAYS restore .gitgov/ from gitgov-state\n // This is necessary because switching branches may have modified/deleted files\n // even if there are no \"new changes\" from the remote.\n // IMPORTANT: Only checkout SYNC_DIRECTORIES and SYNC_ROOT_FILES, preserving LOCAL_ONLY_FILES\n if (gitgovExists) {\n try {\n logger.debug(\"[pullState] Restoring .gitgov/ to filesystem from gitgov-state (preserving local-only files)\");\n\n // Build list of paths to checkout (SYNC_DIRECTORIES + SYNC_ROOT_FILES)\n // This preserves LOCAL_ONLY_FILES like .session.json, index.json, gitgov binary\n const pathsToCheckout: string[] = [];\n\n // Add sync directories\n for (const dirName of SYNC_DIRECTORIES) {\n pathsToCheckout.push(`.gitgov/${dirName}`);\n }\n\n // Add root-level sync files\n for (const fileName of SYNC_ROOT_FILES) {\n pathsToCheckout.push(`.gitgov/${fileName}`);\n }\n\n // Checkout only syncable paths, one at a time (some may not exist)\n for (const checkoutPath of pathsToCheckout) {\n try {\n await execAsync(`git checkout ${stateBranch} -- \"${checkoutPath}\"`, { cwd: pullRepoRoot });\n logger.debug(`[pullState] Checked out: ${checkoutPath}`);\n } catch {\n // Path might not exist in gitgov-state, that's fine\n logger.debug(`[pullState] Skipped (not in gitgov-state): ${checkoutPath}`);\n }\n }\n\n // Unstage the files (keep them untracked if .gitgov/ is ignored)\n try {\n await execAsync('git reset HEAD .gitgov/', { cwd: pullRepoRoot });\n } catch {\n // Nothing staged, that's fine\n }\n\n // [EARS-C8] Restore saved LOCAL_ONLY_FILES (they may have been lost during checkout)\n for (const [fileName, content] of savedLocalFiles) {\n try {\n const filePath = path.join(pullRepoRoot, \".gitgov\", fileName);\n await fs.writeFile(filePath, content, \"utf-8\");\n logger.debug(`[EARS-C8] Restored local-only file: ${fileName}`);\n } catch (writeError) {\n logger.warn(`[EARS-C8] Failed to restore ${fileName}: ${(writeError as Error).message}`);\n }\n }\n\n logger.debug(\"[pullState] .gitgov/ restored to filesystem successfully (local-only files preserved)\");\n } catch (error) {\n logger.warn(`[pullState] Failed to restore .gitgov/ to filesystem: ${(error as Error).message}`);\n // Non-critical: user can manually restore with 'git checkout gitgov-state -- .gitgov/'\n }\n }\n\n // [EARS-C3, EARS-C4, EARS-C9] Invoke indexer AFTER file restoration is complete\n // This ensures the index reflects the latest pulled files, not the old saved index.json\n if (shouldReindex) {\n logger.info(\"Invoking IndexerAdapter.generateIndex() after pull...\");\n try {\n await this.indexer.generateIndex();\n logger.info(\"Index regenerated successfully\");\n } catch (error) {\n logger.warn(`Failed to regenerate index: ${(error as Error).message}`);\n // Non-critical: index regeneration failure doesn't fail the pull\n }\n }\n\n result.success = true;\n log(`=== pullState COMPLETED: ${hasNewChanges ? 'new changes pulled' : 'no changes'}, reindexed: ${result.reindexed} ===`);\n return result;\n } catch (error) {\n log(`=== pullState FAILED: ${(error as Error).message} ===`);\n // Re-throw critical errors that should fail fast\n if (error instanceof UncommittedChangesError) {\n throw error;\n }\n\n // For other errors, return result with error message\n result.error = (error as Error).message;\n return result;\n }\n }\n\n /**\n * Resolves state conflicts in a governed manner (Git-Native).\n *\n * Git-Native Flow:\n * 1. User resolves conflicts using standard Git tools (edit files, remove markers)\n * 2. User stages resolved files: git add .gitgov/\n * 3. User runs: gitgov sync resolve --reason \"reason\"\n *\n * This method:\n * - Verifies that a rebase is in progress\n * - Checks that no conflict markers remain in staged files\n * - Updates resolved Records with new checksums and signatures\n * - Continues the git rebase (git rebase --continue)\n * - Creates a signed resolution commit\n * - Regenerates the index\n *\n * [EARS-D1 through EARS-D7]\n */\n async resolveConflict(\n options: SyncStateResolveOptions\n ): Promise<SyncStateResolveResult> {\n const { reason, actorId } = options;\n\n // Debug logging helper\n const log = (msg: string) => logger.debug(`[resolveConflict] ${msg}`);\n log('=== STARTING resolveConflict (Git-Native) ===');\n\n // ═══════════════════════════════════════════════════════════\n // PHASE 0: Pre-flight Checks (EARS-D1, EARS-D2)\n // Git-Native: Only rebase conflicts exist now\n // ═══════════════════════════════════════════════════════════\n log('Phase 0: Verifying rebase in progress...');\n\n // 1. Check if rebase is in progress (EARS-D1)\n const rebaseInProgress = await this.isRebaseInProgress();\n\n if (!rebaseInProgress) {\n throw new NoRebaseInProgressError();\n }\n\n // PRE-CHECK: Verify actorId matches authenticated identity\n // Prevents impersonation — you can only resolve as the actor whose key you hold\n const authenticatedActor = await this.identity.getCurrentActor();\n if (authenticatedActor.id !== actorId) {\n log(`ERROR: Actor identity mismatch: requested '${actorId}' but authenticated as '${authenticatedActor.id}'`);\n throw new ActorIdentityMismatchError(actorId, authenticatedActor.id);\n }\n log(`Pre-check passed: actorId '${actorId}' matches authenticated identity`);\n\n log('Conflict mode: rebase_conflict (Git-Native)');\n\n // 2. Get STAGED files (user already resolved and added them)\n console.log(\"[resolveConflict] Getting staged files...\");\n const allStagedFiles = await this.git.getStagedFiles();\n console.log(\"[resolveConflict] All staged files:\", allStagedFiles);\n\n // Filter to only .gitgov/*.json files (Records)\n let resolvedRecords = allStagedFiles.filter(f =>\n f.startsWith('.gitgov/') && f.endsWith('.json')\n );\n console.log(\"[resolveConflict] Resolved Records (staged .gitgov/*.json):\", resolvedRecords);\n\n // 3. Verify conflict markers (EARS-D2)\n console.log(\"[resolveConflict] Checking for conflict markers...\");\n const filesWithMarkers = await this.checkConflictMarkers(resolvedRecords);\n console.log(\"[resolveConflict] Files with markers:\", filesWithMarkers);\n if (filesWithMarkers.length > 0) {\n throw new ConflictMarkersPresentError(filesWithMarkers);\n }\n\n let rebaseCommitHash = \"\";\n\n // 4. Continue git rebase FIRST (EARS-D4) - Git-Native flow\n // This completes the rebase with user's resolved files\n console.log(\"[resolveConflict] Step 4: Calling git.rebaseContinue()...\");\n await this.git.rebaseContinue();\n console.log(\"[resolveConflict] rebaseContinue completed successfully\");\n\n // Get rebase commit hash\n const currentBranch = await this.git.getCurrentBranch();\n const rebaseCommit = await this.git.getCommitHistory(currentBranch, {\n maxCount: 1,\n });\n rebaseCommitHash = rebaseCommit[0]?.hash ?? \"\";\n\n // 4b. Get resolved files from the rebase commit (since getStagedFiles doesn't work during rebase)\n // The files that were modified in the rebase commit are the ones that had conflicts\n if (resolvedRecords.length === 0 && rebaseCommitHash) {\n console.log(\"[resolveConflict] No staged files detected, getting files from rebase commit...\");\n const repoRoot = await this.git.getRepoRoot();\n try {\n // Get files changed in the rebase commit\n const { stdout } = await execAsync(\n `git diff-tree --no-commit-id --name-only -r ${rebaseCommitHash}`,\n { cwd: repoRoot }\n );\n const commitFiles = stdout.trim().split('\\n').filter(f => f);\n // Filter to .gitgov/*.json files\n resolvedRecords = commitFiles.filter(f =>\n f.startsWith('.gitgov/') && f.endsWith('.json')\n );\n console.log(\"[resolveConflict] Files from rebase commit:\", resolvedRecords);\n } catch (e) {\n console.log(\"[resolveConflict] Could not get files from rebase commit:\", e);\n }\n }\n\n // 5. NOW update resolved Records with new checksums and signatures (EARS-D3)\n // This happens AFTER rebase so we can create a separate signed resolution commit\n console.log(\"[resolveConflict] Updating resolved Records with signatures...\");\n if (resolvedRecords.length > 0) {\n // Get current actor for signing\n const currentActor = await this.identity.getCurrentActor();\n console.log(\"[resolveConflict] Current actor:\", currentActor);\n\n // Process each resolved Record\n console.log(\"[resolveConflict] Processing\", resolvedRecords.length, \"resolved Records\");\n for (const filePath of resolvedRecords) {\n console.log(\"[resolveConflict] Processing Record:\", filePath);\n\n try {\n const repoRoot = await this.git.getRepoRoot();\n const fullPath = join(repoRoot, filePath);\n\n // Read the resolved Record\n const content = readFileSync(fullPath, 'utf-8');\n const record = JSON.parse(content) as EmbeddedMetadataRecord<GitGovRecordPayload>;\n\n // Skip if not a valid EmbeddedMetadataRecord structure\n if (!record.header || !record.payload) {\n continue;\n }\n\n // Re-sign the record (this recalculates checksum AND adds new signature)\n // Pass the reason as notes for the signature\n const signedRecord = await this.identity.signRecord(\n record,\n currentActor.id,\n 'resolver',\n `Conflict resolved: ${reason}`\n );\n\n // Write back the updated Record\n writeFileSync(fullPath, JSON.stringify(signedRecord, null, 2) + '\\n', 'utf-8');\n\n logger.info(`Updated Record: ${filePath} (new checksum + resolver signature)`);\n console.log(\"[resolveConflict] Successfully updated Record:\", filePath);\n } catch (error) {\n // Log but don't fail - some files might not be Records\n logger.debug(`Skipping file ${filePath}: ${(error as Error).message}`);\n console.log(\"[resolveConflict] Error updating Record:\", filePath, error);\n }\n }\n\n console.log(\"[resolveConflict] All Records updated, staging...\");\n }\n\n // 6. Stage updated files with new checksums/signatures\n console.log(\"[resolveConflict] Staging .gitgov/ with updated metadata...\");\n // Use force: true because .gitgov/ may be in .gitignore (by design)\n await this.git.add([\".gitgov\"], { force: true });\n\n // 7. Create signed resolution commit (EARS-D5)\n const timestamp = new Date().toISOString();\n const resolutionMessage =\n `resolution: conflict resolved by ${actorId}\\n\\n` +\n `Actor: ${actorId}\\n` +\n `Timestamp: ${timestamp}\\n` +\n `Reason: ${reason}\\n` +\n `Files: ${resolvedRecords.length} file(s) resolved\\n\\n` +\n `Signed-off-by: ${actorId}`;\n\n // Create resolution commit (may have signature updates or be empty if no records to sign)\n let resolutionCommitHash = \"\";\n try {\n resolutionCommitHash = await this.git.commit(resolutionMessage);\n } catch (commitError) {\n // If nothing to commit (no records needed re-signing), that's OK\n const stdout = (commitError as any).stdout || '';\n const stderr = (commitError as any).stderr || '';\n\n const isNothingToCommit =\n stdout.includes('nothing to commit') ||\n stderr.includes('nothing to commit') ||\n stdout.includes('nothing added to commit') ||\n stderr.includes('nothing added to commit');\n\n if (isNothingToCommit) {\n log('No additional changes to commit (no records needed re-signing)');\n // Use the rebase commit hash as the resolution hash\n resolutionCommitHash = rebaseCommitHash;\n } else {\n throw commitError;\n }\n }\n\n // 8. Push to remote (best effort - don't fail if no remote)\n log('Pushing resolved state to remote...');\n try {\n await this.git.push(\"origin\", \"gitgov-state\");\n log('Push successful');\n } catch (pushError) {\n // Don't fail resolution just because push failed - local commit is enough\n // This handles: no remote, no network, permission denied, etc.\n const pushErrorMsg = pushError instanceof Error ? pushError.message : String(pushError);\n log(`Push failed (non-fatal): ${pushErrorMsg}`);\n }\n\n // 9. Return to original branch and restore .gitgov/ files\n // This is complex because:\n // - In main branch, .gitgov/ is in .gitignore (untracked)\n // - When we checkout from gitgov-state to main, Git doesn't preserve untracked files\n // - We need to: save local-only files, checkout, restore from gitgov-state, restore local-only\n log('Returning to original branch and restoring .gitgov/ files...');\n const repoRoot = await this.git.getRepoRoot();\n const gitgovDir = path.join(repoRoot, '.gitgov');\n\n // 9a. Save LOCAL_ONLY_FILES and EXCLUDED files to temp BEFORE checkout\n const tempDir = path.join(os.tmpdir(), `gitgov-resolve-${Date.now()}`);\n await fs.mkdir(tempDir, { recursive: true });\n log(`Created temp directory for local files: ${tempDir}`);\n\n // Save LOCAL_ONLY_FILES\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(gitgovDir, fileName);\n const destPath = path.join(tempDir, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Saved LOCAL_ONLY_FILE to temp: ${fileName}`);\n } catch {\n // File doesn't exist, ok\n }\n }\n\n // Save EXCLUDED files (like .key files) recursively\n const saveExcludedFiles = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await fs.mkdir(dstPath, { recursive: true });\n await saveExcludedFiles(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Saved EXCLUDED file to temp: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await saveExcludedFiles(gitgovDir, tempDir);\n\n // 9b. Checkout to original branch\n try {\n await execAsync('git checkout -', { cwd: repoRoot });\n log('Returned to original branch');\n } catch (checkoutError) {\n log(`Warning: Could not return to original branch: ${checkoutError}`);\n }\n\n // 9c. Restore .gitgov/ from gitgov-state branch\n log('Restoring .gitgov/ from gitgov-state...');\n try {\n await this.git.checkoutFilesFromBranch('gitgov-state', ['.gitgov/']);\n // [EARS-B24] Unstage files - git checkout adds them to staging area\n await execAsync('git reset HEAD .gitgov/ 2>/dev/null || true', { cwd: repoRoot });\n log('Restored .gitgov/ from gitgov-state (unstaged)');\n } catch (checkoutFilesError) {\n log(`Warning: Could not restore .gitgov/ from gitgov-state: ${checkoutFilesError}`);\n }\n\n // 9d. Restore LOCAL_ONLY_FILES from temp\n for (const fileName of LOCAL_ONLY_FILES) {\n const srcPath = path.join(tempDir, fileName);\n const destPath = path.join(gitgovDir, fileName);\n try {\n await fs.access(srcPath);\n await fs.cp(srcPath, destPath, { force: true });\n log(`Restored LOCAL_ONLY_FILE from temp: ${fileName}`);\n } catch {\n // File wasn't saved, ok\n }\n }\n\n // 9e. Restore EXCLUDED files from temp\n const restoreExcludedFiles = async (srcDir: string, destDir: string) => {\n try {\n const entries = await fs.readdir(srcDir, { withFileTypes: true });\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const dstPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n await restoreExcludedFiles(srcPath, dstPath);\n } else {\n const isExcluded = SYNC_EXCLUDED_PATTERNS.some(pattern => pattern.test(entry.name));\n if (isExcluded) {\n await fs.mkdir(path.dirname(dstPath), { recursive: true });\n await fs.copyFile(srcPath, dstPath);\n log(`Restored EXCLUDED file from temp: ${entry.name}`);\n }\n }\n }\n } catch {\n // Directory doesn't exist\n }\n };\n await restoreExcludedFiles(tempDir, gitgovDir);\n\n // 9f. Cleanup temp\n try {\n await fs.rm(tempDir, { recursive: true, force: true });\n log('Temp directory cleaned up');\n } catch {\n // Cleanup failure is not critical\n }\n\n // 10. Re-index after conflict resolution (EARS-D4)\n logger.info(\"Invoking IndexerAdapter.generateIndex() after conflict resolution...\");\n try {\n await this.indexer.generateIndex();\n logger.info(\"Index regenerated successfully after conflict resolution\");\n } catch (error) {\n logger.warn(`Failed to regenerate index after resolution: ${(error as Error).message}`);\n // Non-critical: index regeneration failure doesn't fail the resolution\n }\n\n log(`=== resolveConflict COMPLETED: ${resolvedRecords.length} conflicts resolved ===`);\n\n return {\n success: true,\n rebaseCommitHash,\n resolutionCommitHash,\n conflictsResolved: resolvedRecords.length,\n resolvedBy: actorId,\n reason,\n };\n }\n}\n","export class WatcherStateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"WatcherStateError\";\n Object.setPrototypeOf(this, WatcherStateError.prototype);\n }\n}\n\nexport class ProjectNotInitializedError extends WatcherStateError {\n constructor(gitgovPath: string) {\n super(`Directory ${gitgovPath} not found. Run 'gitgov init' first.`);\n this.name = \"ProjectNotInitializedError\";\n Object.setPrototypeOf(this, ProjectNotInitializedError.prototype);\n }\n}\n\nexport class WatcherSetupError extends WatcherStateError {\n constructor(directory: string, cause: Error) {\n super(`Failed to create watcher for ${directory}: ${cause.message}`);\n this.name = \"WatcherSetupError\";\n this.cause = cause;\n Object.setPrototypeOf(this, WatcherSetupError.prototype);\n }\n}\n\nexport class ChecksumMismatchError extends WatcherStateError {\n public expected: string;\n public actual: string;\n\n constructor(filePath: string, expected: string, actual: string) {\n super(\n `Checksum mismatch in ${filePath}: expected ${expected}, got ${actual}`\n );\n this.name = \"ChecksumMismatchError\";\n this.expected = expected;\n this.actual = actual;\n Object.setPrototypeOf(this, ChecksumMismatchError.prototype);\n }\n}\n\n// Type guards\nexport function isWatcherStateError(\n error: unknown\n): error is WatcherStateError {\n return error instanceof WatcherStateError;\n}\n\nexport function isProjectNotInitializedError(\n error: unknown\n): error is ProjectNotInitializedError {\n return error instanceof ProjectNotInitializedError;\n}\n\nexport function isWatcherSetupError(\n error: unknown\n): error is WatcherSetupError {\n return error instanceof WatcherSetupError;\n}\n\nexport function isChecksumMismatchError(\n error: unknown\n): error is ChecksumMismatchError {\n return error instanceof ChecksumMismatchError;\n}\n","/**\n * FsWatcherStateModule — Filesystem watcher for .gitgov/ changes\n *\n * Watches .gitgov/ subdirectories using chokidar and emits events\n * to the EventBus after debounce + checksum validation.\n */\n\nimport chokidar from \"chokidar\";\nimport { readFile } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { basename, dirname, join, relative } from \"path\";\nimport { SYNC_DIRECTORIES } from \"../../sync_state/sync_state.types\";\nimport { calculatePayloadChecksum } from \"../../crypto/checksum\";\nimport { createLogger } from \"../../logger/logger\";\nimport type { IWatcherStateModule } from \"../watcher_state\";\nimport type {\n WatcherStateModuleDependencies,\n WatcherStateStatus,\n} from \"../watcher_state.types\";\nimport type { IEventStream } from \"../../event_bus\";\nimport {\n ProjectNotInitializedError,\n ChecksumMismatchError,\n} from \"../watcher_state.errors\";\n\n// --- Constants ---\n\nconst DEFAULT_DEBOUNCE_MS = 300;\n\nconst EVENT_TYPE_MAP = {\n add: \"watcher.record.added\",\n change: \"watcher.record.changed\",\n unlink: \"watcher.record.deleted\",\n} as const;\n\n// --- Implementation ---\n\nexport class FsWatcherStateModule implements IWatcherStateModule {\n private eventBus: IEventStream;\n private gitgovPath: string;\n private debounceMs: number;\n private logger = createLogger(\"[FsWatcherStateModule] \");\n private watchers: chokidar.FSWatcher[] = [];\n private watchedDirectories: string[] = [];\n private running = false;\n private debounceTimers = new Map<string, NodeJS.Timeout>();\n private checksums = new Map<string, string>();\n private eventsEmitted = 0;\n private lastError?: Error;\n\n constructor(deps: WatcherStateModuleDependencies) {\n this.eventBus = deps.eventBus;\n this.gitgovPath = deps.options.gitgovPath;\n this.debounceMs = deps.options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n }\n\n /**\n * EARS-1: Creates watchers for existing directories in .gitgov/\n * EARS-2: Throws ProjectNotInitializedError if .gitgov/ doesn't exist\n */\n async start(): Promise<void> {\n if (!existsSync(this.gitgovPath)) {\n throw new ProjectNotInitializedError(this.gitgovPath);\n }\n\n for (const dir of SYNC_DIRECTORIES) {\n const dirPath = join(this.gitgovPath, dir);\n if (!existsSync(dirPath)) continue;\n\n const watcher = chokidar.watch(dirPath, {\n ignoreInitial: true,\n depth: 0,\n });\n\n watcher.on(\"add\", (fp) => this.onFileChange(fp, \"add\"));\n watcher.on(\"change\", (fp) => this.onFileChange(fp, \"change\"));\n watcher.on(\"unlink\", (fp) => this.onFileChange(fp, \"unlink\"));\n\n this.watchers.push(watcher);\n this.watchedDirectories.push(dir);\n }\n\n this.running = true;\n }\n\n /** EARS-5: Closes watchers + cancels timers */\n async stop(): Promise<void> {\n for (const timer of this.debounceTimers.values()) {\n clearTimeout(timer);\n }\n this.debounceTimers.clear();\n\n await Promise.all(this.watchers.map((w) => w.close()));\n this.watchers = [];\n this.watchedDirectories = [];\n\n this.running = false;\n }\n\n isRunning(): boolean {\n return this.running;\n }\n\n getStatus(): WatcherStateStatus {\n return {\n isRunning: this.running,\n watchedDirectories: [...this.watchedDirectories],\n eventsEmitted: this.eventsEmitted,\n lastError: this.lastError,\n };\n }\n\n /**\n * EARS-3: Emits event after debounce\n * EARS-6: Debounce — N rapid changes → 1 event\n */\n private onFileChange(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): void {\n const existing = this.debounceTimers.get(filePath);\n if (existing) clearTimeout(existing);\n\n const timer = setTimeout(() => {\n this.debounceTimers.delete(filePath);\n void this.processFileChange(filePath, changeType);\n }, this.debounceMs);\n\n this.debounceTimers.set(filePath, timer);\n }\n\n /**\n * EARS-3: Emit event to EventBus\n * EARS-4: Skip event on checksum mismatch\n * EARS-7: Handle errors gracefully\n */\n private async processFileChange(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): Promise<void> {\n try {\n if (changeType === \"unlink\") {\n this.checksums.delete(filePath);\n this.emitEvent(filePath, changeType);\n return;\n }\n\n const content = await readFile(filePath, \"utf-8\");\n const record = JSON.parse(content);\n\n if (record?.header?.payloadChecksum && record?.payload) {\n const calculated = calculatePayloadChecksum(record.payload);\n if (calculated !== record.header.payloadChecksum) {\n this.lastError = new ChecksumMismatchError(\n filePath,\n record.header.payloadChecksum,\n calculated\n );\n this.logger.error(this.lastError.message);\n return;\n }\n }\n\n const newChecksum = record?.header?.payloadChecksum as\n | string\n | undefined;\n if (newChecksum && newChecksum === this.checksums.get(filePath)) {\n return;\n }\n if (newChecksum) this.checksums.set(filePath, newChecksum);\n\n this.emitEvent(filePath, changeType);\n } catch (error) {\n this.lastError =\n error instanceof Error ? error : new Error(String(error));\n this.logger.error(\n `Error processing ${filePath}: ${this.lastError.message}`\n );\n }\n }\n\n private emitEvent(\n filePath: string,\n changeType: \"add\" | \"change\" | \"unlink\"\n ): void {\n const recordType = this.extractRecordType(filePath);\n const recordId = this.extractRecordId(filePath);\n const relPath = relative(join(this.gitgovPath, \"..\"), filePath);\n\n this.eventBus.publish({\n type: EVENT_TYPE_MAP[changeType],\n timestamp: Date.now(),\n source: \"watcher\",\n payload: { recordType, recordId, filePath: relPath },\n });\n this.eventsEmitted++;\n }\n\n private extractRecordType(filePath: string): string {\n return basename(dirname(filePath));\n }\n\n private extractRecordId(filePath: string): string {\n return basename(filePath, \".json\");\n }\n}\n","/**\n * Custom Error Classes for AgentRunnerModule\n *\n * These errors provide typed exceptions for better error handling\n * and diagnostics in the agent runner operations.\n */\n\n/**\n * Base error class for all Runner-related errors\n */\nexport class RunnerError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RunnerError\";\n Object.setPrototypeOf(this, RunnerError.prototype);\n }\n}\n\n/**\n * Error thrown when an agent file is not found in .gitgov/agents/\n */\nexport class AgentNotFoundError extends RunnerError {\n public readonly agentId: string;\n\n constructor(agentId: string) {\n super(`AgentNotFound: ${agentId}`);\n this.name = \"AgentNotFoundError\";\n this.agentId = agentId;\n Object.setPrototypeOf(this, AgentNotFoundError.prototype);\n }\n}\n\n/**\n * Error thrown when the specified function is not exported from entrypoint\n */\nexport class FunctionNotExportedError extends RunnerError {\n public readonly functionName: string;\n public readonly entrypoint: string;\n\n constructor(functionName: string, entrypoint: string) {\n super(`FunctionNotExported: ${functionName} not found in ${entrypoint}`);\n this.name = \"FunctionNotExportedError\";\n this.functionName = functionName;\n this.entrypoint = entrypoint;\n Object.setPrototypeOf(this, FunctionNotExportedError.prototype);\n }\n}\n\n/**\n * Error thrown when local engine has neither entrypoint nor runtime\n */\nexport class LocalEngineConfigError extends RunnerError {\n constructor() {\n super(\"LocalEngineConfigError: entrypoint or runtime required for execution\");\n this.name = \"LocalEngineConfigError\";\n Object.setPrototypeOf(this, LocalEngineConfigError.prototype);\n }\n}\n\n/**\n * Error thrown when engine.type is not supported\n */\nexport class UnsupportedEngineTypeError extends RunnerError {\n public readonly engineType: string;\n\n constructor(engineType: string) {\n super(`UnsupportedEngineType: ${engineType}`);\n this.name = \"UnsupportedEngineTypeError\";\n this.engineType = engineType;\n Object.setPrototypeOf(this, UnsupportedEngineTypeError.prototype);\n }\n}\n\n/**\n * Error thrown when engine configuration is invalid\n */\nexport class EngineConfigError extends RunnerError {\n public readonly engineType: string;\n public readonly missingField: string;\n\n constructor(engineType: string, missingField: string) {\n super(`EngineConfigError: ${missingField} required for ${engineType}`);\n this.name = \"EngineConfigError\";\n this.engineType = engineType;\n this.missingField = missingField;\n Object.setPrototypeOf(this, EngineConfigError.prototype);\n }\n}\n\n/**\n * Error thrown when a required dependency is missing\n */\nexport class MissingDependencyError extends RunnerError {\n public readonly dependency: string;\n public readonly reason: string;\n\n constructor(dependency: string, reason: string) {\n super(`MissingDependency: ${dependency} ${reason}`);\n this.name = \"MissingDependencyError\";\n this.dependency = dependency;\n this.reason = reason;\n Object.setPrototypeOf(this, MissingDependencyError.prototype);\n }\n}\n\n/**\n * Error thrown when runtime handler is not found in registry\n */\nexport class RuntimeNotFoundError extends RunnerError {\n public readonly runtime: string;\n\n constructor(runtime: string) {\n super(`RuntimeNotFound: ${runtime}`);\n this.name = \"RuntimeNotFoundError\";\n this.runtime = runtime;\n Object.setPrototypeOf(this, RuntimeNotFoundError.prototype);\n }\n}\n","import path from \"node:path\";\nimport {\n LocalEngineConfigError,\n FunctionNotExportedError,\n RuntimeNotFoundError,\n} from \"../agent_runner.errors\";\nimport type { RuntimeHandlerRegistry } from \"../agent_runner\";\nimport type {\n LocalEngine,\n AgentExecutionContext,\n AgentOutput,\n} from \"../agent_runner.types\";\n\n/**\n * Backend for executing local agents (engine.type: \"local\").\n * Supports entrypoint (dynamic import) and runtime (registered handler).\n * RETURNS AgentOutput captured from the agent function.\n *\n * Note: This is called \"LocalBackend\" because it handles engine.type: \"local\",\n * not because of filesystem usage. The FsAgentRunner loads AgentRecords from\n * filesystem, but this backend executes code locally via dynamic import.\n */\nexport class LocalBackend {\n constructor(\n private projectRoot: string,\n private runtimeRegistry?: RuntimeHandlerRegistry\n ) {}\n\n /**\n * Executes a local agent and captures its output.\n */\n async execute(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-B3] Validate that at least entrypoint or runtime is defined\n if (!engine.entrypoint && !engine.runtime) {\n throw new LocalEngineConfigError();\n }\n\n // [EARS-B2] If runtime defined, use runtime handler\n if (engine.runtime) {\n return this.executeRuntime(engine, ctx);\n }\n\n // [EARS-B1, B4, B5, B6, B7] If entrypoint defined, use dynamic import\n return this.executeEntrypoint(engine, ctx);\n }\n\n /**\n * Executes via entrypoint (dynamic import) and captures output.\n */\n private async executeEntrypoint(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-B1] Resolve absolute path\n const absolutePath = path.join(this.projectRoot, engine.entrypoint!);\n\n // [EARS-B4] Dynamic import\n const mod = await import(absolutePath);\n\n // [EARS-B5] Get function (default: \"runAgent\")\n const fnName = engine.function || \"runAgent\";\n const fn = mod[fnName];\n\n // [EARS-B6] Error if function not exported\n if (typeof fn !== \"function\") {\n throw new FunctionNotExportedError(fnName, engine.entrypoint!);\n }\n\n // [EARS-B7] Invoke with context and capture output\n const result = await fn(ctx);\n\n return this.normalizeOutput(result);\n }\n\n /**\n * Executes via runtime handler.\n */\n private async executeRuntime(\n engine: LocalEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n if (!this.runtimeRegistry) {\n throw new RuntimeNotFoundError(engine.runtime!);\n }\n\n const handler = this.runtimeRegistry.get(engine.runtime!);\n if (!handler) {\n throw new RuntimeNotFoundError(engine.runtime!);\n }\n\n return handler(engine, ctx);\n }\n\n /**\n * Normalizes any result to AgentOutput.\n * If agent returns void/undefined, uses empty object.\n * If returns object with known fields, extracts them.\n */\n private normalizeOutput(result: unknown): AgentOutput {\n if (result === undefined || result === null) {\n return {};\n }\n\n if (typeof result === \"object\") {\n const obj = result as Record<string, unknown>;\n const output: AgentOutput = {};\n\n // Only include data if explicitly returned\n if (obj[\"data\"] !== undefined) {\n output.data = obj[\"data\"];\n }\n\n const message = obj[\"message\"];\n if (typeof message === \"string\") {\n output.message = message;\n }\n\n const artifacts = obj[\"artifacts\"];\n if (Array.isArray(artifacts)) {\n output.artifacts = artifacts;\n }\n\n const metadata = obj[\"metadata\"];\n if (typeof metadata === \"object\" && metadata !== null) {\n output.metadata = metadata as Record<string, unknown>;\n }\n\n return output;\n }\n\n // For primitives, wrap in data\n return { data: result };\n }\n}\n","/**\n * Backend for executing agents via HTTP API (engine.type: \"api\").\n *\n * EARS Coverage:\n * - [EARS-D1] Prepare HTTP request for API engine\n * - [EARS-D2] Read auth token from environment\n * - [EARS-D3] Sign request for actor-signature auth\n * - [EARS-D4] Capture response body as AgentOutput\n * - [EARS-D5] Throw ApiBackendError on non-2xx response\n *\n * Reference: agent_protocol.md §5.1.2\n */\n\nimport type {\n ApiEngine,\n AgentExecutionContext,\n AgentOutput,\n AuthConfig,\n} from \"../agent_runner.types\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\n\n/**\n * Error thrown when API backend request fails.\n * [EARS-D5]\n */\nexport class ApiBackendError extends Error {\n public readonly statusCode: number | undefined;\n public readonly statusText: string | undefined;\n\n constructor(message: string, statusCode?: number, statusText?: string) {\n super(`ApiBackendError: ${message}`);\n this.name = \"ApiBackendError\";\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n}\n\n/**\n * Backend for executing agents via HTTP API.\n *\n * Supports multiple authentication types:\n * - bearer: Bearer token from environment variable\n * - api-key: API key from environment variable\n * - actor-signature: Cryptographic signature using ActorRecord\n *\n * Reference: agent_protocol.md §5.1.2, §5.5, §5.6\n */\nexport class ApiBackend {\n constructor(private identityAdapter?: IIdentityAdapter) {}\n\n /**\n * Executes an agent via API and captures the response.\n *\n * @param engine - API engine configuration\n * @param ctx - Execution context\n * @returns AgentOutput with parsed response body\n *\n * @throws ApiBackendError - When request fails or non-2xx response [EARS-D5]\n */\n async execute(\n engine: ApiEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-D1] Prepare HTTP request\n const method = engine.method ?? \"POST\";\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // [EARS-D2, D3] Apply authentication\n if (engine.auth) {\n await this.applyAuth(headers, engine.auth, ctx);\n }\n\n // Prepare request body with context\n const body = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n input: ctx.input,\n });\n\n try {\n // Execute HTTP request\n const response = await fetch(engine.url, {\n method,\n headers,\n ...(method !== \"GET\" ? { body } : {}),\n });\n\n // [EARS-D5] Error on non-2xx response\n if (!response.ok) {\n throw new ApiBackendError(\n response.statusText || `HTTP ${response.status}`,\n response.status,\n response.statusText\n );\n }\n\n // [EARS-D4] Parse response body as JSON and return as AgentOutput\n const responseBody = await response.json();\n\n return this.normalizeOutput(responseBody);\n } catch (error) {\n // Re-throw ApiBackendError as-is\n if (error instanceof ApiBackendError) {\n throw error;\n }\n\n // Wrap other errors\n throw new ApiBackendError(\n error instanceof Error ? error.message : \"Unknown error\"\n );\n }\n }\n\n /**\n * Apply authentication headers based on auth config.\n * [EARS-D2] Read token from environment\n * [EARS-D3] Sign request for actor-signature\n */\n private async applyAuth(\n headers: Record<string, string>,\n auth: AuthConfig,\n ctx: AgentExecutionContext\n ): Promise<void> {\n switch (auth.type) {\n case \"bearer\": {\n // [EARS-D2] Read token from env var or use direct token\n const token = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n break;\n }\n\n case \"api-key\": {\n // [EARS-D2] Read API key from env var or use direct token\n const apiKey = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (apiKey) {\n headers[\"X-API-Key\"] = apiKey;\n }\n break;\n }\n\n case \"actor-signature\": {\n // [EARS-D3] Sign context using IdentityAdapter\n if (!this.identityAdapter) {\n throw new ApiBackendError(\n \"IdentityAdapter required for actor-signature auth\"\n );\n }\n\n // Create signature payload\n const payload = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n timestamp: Date.now(),\n });\n\n // Sign using actor's private key\n const signature = await this.identityAdapter.signRecord(\n { header: { version: \"1.0\", type: \"request\", payloadChecksum: \"\", signatures: [] }, payload } as any,\n ctx.actorId,\n \"executor\",\n \"API request signature\"\n );\n\n headers[\"X-GitGov-Signature\"] = JSON.stringify(signature);\n headers[\"X-GitGov-Actor\"] = ctx.actorId;\n break;\n }\n\n case \"oauth\":\n // OAuth would require more complex flow (token refresh, etc.)\n // For now, treat similar to bearer\n if (auth.token) {\n headers[\"Authorization\"] = `Bearer ${auth.token}`;\n }\n break;\n\n default:\n // No authentication\n break;\n }\n }\n\n /**\n * Normalize API response to AgentOutput format.\n * Handles various response structures.\n */\n private normalizeOutput(responseBody: unknown): AgentOutput {\n if (responseBody === null || responseBody === undefined) {\n return {};\n }\n\n if (typeof responseBody !== \"object\") {\n return { data: responseBody };\n }\n\n const body = responseBody as Record<string, unknown>;\n\n // If response already has AgentOutput structure, use it\n const output: AgentOutput = {};\n\n if (body[\"data\"] !== undefined) {\n output.data = body[\"data\"];\n } else {\n // If no data field, use entire body as data\n output.data = body;\n }\n\n if (typeof body[\"message\"] === \"string\") {\n output.message = body[\"message\"];\n }\n\n if (Array.isArray(body[\"artifacts\"])) {\n output.artifacts = body[\"artifacts\"];\n }\n\n if (typeof body[\"metadata\"] === \"object\" && body[\"metadata\"] !== null) {\n output.metadata = body[\"metadata\"] as Record<string, unknown>;\n }\n\n return output;\n }\n}\n","/**\n * Backend for executing agents via Model Context Protocol (engine.type: \"mcp\").\n *\n * EARS Coverage:\n * - [EARS-E1] Connect to MCP server at engine.url\n * - [EARS-E2] Invoke tool and capture result as AgentOutput\n * - [EARS-E3] Map tool result to AgentOutput.data\n * - [EARS-E4] Throw McpBackendError on connection/tool failure\n *\n * Reference: agent_protocol.md §5.1.3\n *\n * Note: This implementation uses HTTP transport for MCP. In production,\n * this would integrate with the actual MCP SDK for full protocol support.\n */\n\nimport type {\n McpEngine,\n AgentExecutionContext,\n AgentOutput,\n AuthConfig,\n} from \"../agent_runner.types\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\n\n/**\n * Error thrown when MCP backend operation fails.\n * [EARS-E4]\n */\nexport class McpBackendError extends Error {\n public readonly code: string | undefined;\n\n constructor(message: string, code?: string) {\n super(`McpBackendError: ${message}`);\n this.name = \"McpBackendError\";\n this.code = code;\n }\n}\n\n/**\n * MCP JSON-RPC request structure.\n */\ninterface McpRequest {\n jsonrpc: \"2.0\";\n id: string | number;\n method: string;\n params?: Record<string, unknown>;\n}\n\n/**\n * MCP JSON-RPC response structure.\n */\ninterface McpResponse {\n jsonrpc: \"2.0\";\n id: string | number;\n result?: unknown;\n error?: {\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\n/**\n * Backend for executing agents via Model Context Protocol.\n *\n * Connects to MCP servers and invokes tools.\n * CAPTURES the tool result and returns it as AgentOutput.\n *\n * Tool resolution priority (per agent_protocol.md §5.1.3):\n * 1. toolOverride (RunOptions.tool) - runtime selection\n * 2. engine.tool - AgentRecord configuration\n * 3. agentId without \"agent:\" prefix - fallback\n *\n * Reference: agent_protocol.md §5.1.3\n */\nexport class McpBackend {\n constructor(private identityAdapter?: IIdentityAdapter) {}\n\n /**\n * Executes an agent via MCP and captures the result.\n *\n * @param engine - MCP engine configuration\n * @param ctx - Execution context\n * @param toolOverride - Optional tool override from RunOptions.tool\n * @returns AgentOutput with tool result\n *\n * @throws McpBackendError - When connection or tool invocation fails [EARS-E4]\n */\n async execute(\n engine: McpEngine,\n ctx: AgentExecutionContext,\n toolOverride?: string\n ): Promise<AgentOutput> {\n // [EARS-E2] Determine tool to invoke (priority order)\n const tool = this.resolveToolName(engine, ctx, toolOverride);\n\n // [EARS-E1] Prepare MCP connection/request\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // Apply authentication if configured\n if (engine.auth) {\n await this.applyAuth(headers, engine.auth, ctx);\n }\n\n // Build MCP JSON-RPC request for tool invocation\n const mcpRequest: McpRequest = {\n jsonrpc: \"2.0\",\n id: ctx.runId,\n method: \"tools/call\",\n params: {\n name: tool,\n arguments: {\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n input: ctx.input,\n },\n },\n };\n\n try {\n // [EARS-E1] Connect to MCP server via HTTP\n const response = await fetch(engine.url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(mcpRequest),\n });\n\n if (!response.ok) {\n // [EARS-E4] Connection failure\n throw new McpBackendError(\n `HTTP ${response.status}: ${response.statusText}`,\n \"CONNECTION_FAILED\"\n );\n }\n\n const mcpResponse: McpResponse = await response.json();\n\n // [EARS-E4] Check for MCP error response\n if (mcpResponse.error) {\n throw new McpBackendError(\n mcpResponse.error.message,\n `MCP_ERROR_${mcpResponse.error.code}`\n );\n }\n\n // [EARS-E3] Map tool result to AgentOutput.data\n return this.mapResultToOutput(mcpResponse.result);\n } catch (error) {\n // Re-throw McpBackendError as-is\n if (error instanceof McpBackendError) {\n throw error;\n }\n\n // [EARS-E4] Wrap other errors\n throw new McpBackendError(\n error instanceof Error ? error.message : \"Unknown error\",\n \"EXECUTION_FAILED\"\n );\n }\n }\n\n /**\n * [EARS-E2] Resolve tool name following priority order:\n * 1. toolOverride (from RunOptions.tool)\n * 2. engine.tool (from AgentRecord)\n * 3. agentId without \"agent:\" prefix\n */\n private resolveToolName(\n engine: McpEngine,\n ctx: AgentExecutionContext,\n toolOverride?: string\n ): string {\n if (toolOverride) {\n return toolOverride;\n }\n\n if (engine.tool) {\n return engine.tool;\n }\n\n // Fallback: use agentId without \"agent:\" prefix\n return ctx.agentId.replace(/^agent:/, \"\");\n }\n\n /**\n * Apply authentication headers based on auth config.\n */\n private async applyAuth(\n headers: Record<string, string>,\n auth: AuthConfig,\n ctx: AgentExecutionContext\n ): Promise<void> {\n switch (auth.type) {\n case \"bearer\": {\n const token = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n break;\n }\n\n case \"api-key\": {\n const apiKey = auth.secret_key\n ? process.env[auth.secret_key]\n : auth.token;\n if (apiKey) {\n headers[\"X-API-Key\"] = apiKey;\n }\n break;\n }\n\n case \"actor-signature\": {\n if (!this.identityAdapter) {\n throw new McpBackendError(\n \"IdentityAdapter required for actor-signature auth\",\n \"AUTH_MISSING_ADAPTER\"\n );\n }\n\n const payload = JSON.stringify({\n agentId: ctx.agentId,\n actorId: ctx.actorId,\n taskId: ctx.taskId,\n runId: ctx.runId,\n timestamp: Date.now(),\n });\n\n const signature = await this.identityAdapter.signRecord(\n { header: { version: \"1.0\", type: \"request\", payloadChecksum: \"\", signatures: [] }, payload } as any,\n ctx.actorId,\n \"executor\",\n \"MCP request signature\"\n );\n\n headers[\"X-GitGov-Signature\"] = JSON.stringify(signature);\n headers[\"X-GitGov-Actor\"] = ctx.actorId;\n break;\n }\n\n default:\n break;\n }\n }\n\n /**\n * [EARS-E3] Map MCP tool result to AgentOutput.\n */\n private mapResultToOutput(result: unknown): AgentOutput {\n if (result === null || result === undefined) {\n return {};\n }\n\n // If result is already AgentOutput-like, extract fields\n if (typeof result === \"object\") {\n const obj = result as Record<string, unknown>;\n const output: AgentOutput = {\n data: obj[\"data\"] ?? result, // Use data field or entire result\n };\n\n if (typeof obj[\"message\"] === \"string\") {\n output.message = obj[\"message\"];\n }\n\n if (Array.isArray(obj[\"artifacts\"])) {\n output.artifacts = obj[\"artifacts\"];\n }\n\n if (typeof obj[\"metadata\"] === \"object\" && obj[\"metadata\"] !== null) {\n output.metadata = obj[\"metadata\"] as Record<string, unknown>;\n }\n\n // Handle MCP-specific content array format\n if (Array.isArray(obj[\"content\"])) {\n const textContent = obj[\"content\"].find(\n (c: any) => c.type === \"text\"\n );\n if (textContent && typeof textContent.text === \"string\") {\n output.message = textContent.text;\n }\n }\n\n return output;\n }\n\n // Primitive result\n return { data: result };\n }\n}\n","/**\n * Backend for executing agents via custom protocol handlers (engine.type: \"custom\").\n *\n * EARS Coverage:\n * - [EARS-F1] Lookup handler in ProtocolHandlerRegistry\n * - [EARS-F2] Throw CustomEngineConfigError when protocol missing\n * - [EARS-F3] Throw ProtocolHandlerNotFound when handler not registered\n * - [EARS-F4] Invoke handler with engine and context\n *\n * Reference: agent_protocol.md §5.1.4\n */\n\nimport type { ProtocolHandlerRegistry, ProtocolHandler } from \"../agent_runner\";\nimport type {\n CustomEngine,\n AgentExecutionContext,\n AgentOutput,\n} from \"../agent_runner.types\";\n\n/**\n * Error thrown when custom engine configuration is invalid.\n * [EARS-F2]\n */\nexport class CustomEngineConfigError extends Error {\n constructor(message: string) {\n super(`CustomEngineConfigError: ${message}`);\n this.name = \"CustomEngineConfigError\";\n }\n}\n\n/**\n * Error thrown when protocol handler is not found in registry.\n * [EARS-F3]\n */\nexport class ProtocolHandlerNotFoundError extends Error {\n public readonly protocol: string;\n\n constructor(protocol: string) {\n super(`ProtocolHandlerNotFound: ${protocol}`);\n this.name = \"ProtocolHandlerNotFoundError\";\n this.protocol = protocol;\n }\n}\n\n/**\n * Backend for executing agents via custom protocol handlers.\n *\n * Allows extensibility without modifying the runner core.\n * Protocol handlers MUST return AgentOutput.\n *\n * Reference: agent_protocol.md §5.1.4\n */\nexport class CustomBackend {\n constructor(private registry?: ProtocolHandlerRegistry) {}\n\n /**\n * Executes an agent via protocol handler.\n *\n * @param engine - Custom engine configuration\n * @param ctx - Execution context\n * @returns AgentOutput from handler\n *\n * @throws CustomEngineConfigError - When protocol is not defined [EARS-F2]\n * @throws ProtocolHandlerNotFoundError - When handler not registered [EARS-F3]\n */\n async execute(\n engine: CustomEngine,\n ctx: AgentExecutionContext\n ): Promise<AgentOutput> {\n // [EARS-F2] Validate protocol is defined\n if (!engine.protocol) {\n throw new CustomEngineConfigError(\"protocol required for execution\");\n }\n\n // [EARS-F1] Lookup handler in registry\n if (!this.registry) {\n throw new ProtocolHandlerNotFoundError(engine.protocol);\n }\n\n const handler = this.registry.get(engine.protocol);\n\n // [EARS-F3] Error if handler not registered\n if (!handler) {\n throw new ProtocolHandlerNotFoundError(engine.protocol);\n }\n\n // [EARS-F4] Invoke handler with engine and context, capture output\n const output = await handler(engine, ctx);\n\n return output;\n }\n}\n\n/**\n * Default implementation of ProtocolHandlerRegistry.\n * In-memory registry for protocol handlers.\n */\nexport class DefaultProtocolHandlerRegistry implements ProtocolHandlerRegistry {\n private handlers = new Map<string, ProtocolHandler>();\n\n register(protocol: string, handler: ProtocolHandler): void {\n this.handlers.set(protocol, handler);\n }\n\n get(protocol: string): ProtocolHandler | undefined {\n return this.handlers.get(protocol);\n }\n}\n","import path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport {\n LocalBackend,\n ApiBackend,\n McpBackend,\n CustomBackend,\n} from \"../backends\";\nimport {\n AgentNotFoundError,\n UnsupportedEngineTypeError,\n EngineConfigError,\n MissingDependencyError,\n} from \"../agent_runner.errors\";\nimport type { AgentRecord } from \"../../record_types\";\nimport type { IEventStream } from \"../../event_bus\";\nimport type { IExecutionAdapter } from \"../../adapters/execution_adapter\";\nimport type { IIdentityAdapter } from \"../../adapters/identity_adapter\";\nimport type {\n IAgentRunner,\n ProtocolHandlerRegistry,\n RuntimeHandlerRegistry,\n} from \"../agent_runner\";\nimport type {\n LocalEngine,\n ApiEngine,\n McpEngine,\n CustomEngine,\n AgentRunnerDependencies,\n AgentExecutionContext,\n AgentOutput,\n AgentResponse,\n AgentRunnerEvent,\n RunOptions,\n} from \"../agent_runner.types\";\n\nconst VALID_ENGINE_TYPES = [\"local\", \"api\", \"mcp\", \"custom\"] as const;\n\n/**\n * Filesystem-based Agent Runner - Executes agents based on their engine.type.\n *\n * Responsibilities:\n * - Load AgentRecords from .gitgov/agents/\n * - Execute via appropriate backend (local, api, mcp, custom)\n * - Capture responses and write ExecutionRecords\n * - Emit events via EventBus\n */\nexport class FsAgentRunner implements IAgentRunner {\n private gitgovPath: string;\n private projectRoot: string;\n private identityAdapter: IIdentityAdapter | undefined;\n private executionAdapter: IExecutionAdapter;\n private eventBus: IEventStream | undefined;\n /** Protocol handlers for CustomBackend */\n public readonly protocolHandlers: ProtocolHandlerRegistry | undefined;\n private runtimeHandlers: RuntimeHandlerRegistry | undefined;\n\n // Engine backends\n private localBackend: LocalBackend;\n private apiBackend: ApiBackend;\n private mcpBackend: McpBackend;\n private customBackend: CustomBackend;\n\n constructor(deps: AgentRunnerDependencies) {\n // [EARS-H4] Validate ExecutionAdapter is provided\n if (!deps.executionAdapter) {\n throw new MissingDependencyError(\"ExecutionAdapter\", \"required\");\n }\n\n this.projectRoot = deps.projectRoot;\n this.gitgovPath = deps.gitgovPath ?? path.join(this.projectRoot, \".gitgov\");\n this.identityAdapter = deps.identityAdapter ?? undefined;\n this.executionAdapter = deps.executionAdapter;\n this.eventBus = deps.eventBus ?? undefined;\n this.protocolHandlers = deps.protocolHandlers ?? undefined;\n this.runtimeHandlers = deps.runtimeHandlers ?? undefined;\n\n // Initialize all engine backends\n this.localBackend = new LocalBackend(this.projectRoot, this.runtimeHandlers);\n this.apiBackend = new ApiBackend(this.identityAdapter);\n this.mcpBackend = new McpBackend(this.identityAdapter);\n this.customBackend = new CustomBackend(this.protocolHandlers);\n }\n\n /**\n * Executes an agent once and returns the response.\n * TaskRecord must exist before calling this method.\n */\n async runOnce(opts: RunOptions): Promise<AgentResponse> {\n const startedAt = new Date().toISOString();\n const runId = randomUUID(); // [EARS-C3]\n let output: AgentOutput | undefined;\n let error: string | undefined;\n let status: \"success\" | \"error\" = \"success\";\n\n // [EARS-A1, A2, A3] Load AgentRecord\n const agent = await this.loadAgent(opts.agentId);\n\n // [EARS-A3] Extract engine from payload\n const engine = agent.engine;\n const engineType = engine.type as string;\n\n // [EARS-G1] Validate engine.type\n if (!VALID_ENGINE_TYPES.includes(engineType as typeof VALID_ENGINE_TYPES[number])) {\n throw new UnsupportedEngineTypeError(engineType);\n }\n\n // [EARS-G2] Validate url for api/mcp\n if ((engineType === \"api\" || engineType === \"mcp\") && !(\"url\" in engine)) {\n throw new EngineConfigError(engineType, \"url\");\n }\n\n // [EARS-G3] Validate IdentityAdapter for actor-signature auth\n if (engineType === \"api\" || engineType === \"mcp\") {\n const engineWithAuth = engine as { auth?: { type?: string } };\n if (\n engineWithAuth.auth?.type === \"actor-signature\" &&\n !this.identityAdapter\n ) {\n throw new MissingDependencyError(\n \"IdentityAdapter\",\n \"required for actor-signature auth\"\n );\n }\n }\n\n // [EARS-C1, C2] Build context\n const ctx: AgentExecutionContext = {\n agentId: opts.agentId,\n actorId: opts.actorId ?? opts.agentId, // [EARS-C2]\n taskId: opts.taskId,\n runId,\n input: opts.input,\n };\n\n // [EARS-I1] Emit agent:started event\n this.emitEvent({\n type: \"agent:started\",\n payload: { runId, agentId: opts.agentId, taskId: opts.taskId, startedAt },\n });\n\n try {\n // Execute via appropriate backend and CAPTURE output\n switch (engineType) {\n case \"local\":\n output = await this.localBackend.execute(engine as LocalEngine, ctx);\n break;\n case \"api\":\n output = await this.apiBackend.execute(engine as ApiEngine, ctx);\n break;\n case \"mcp\":\n output = await this.mcpBackend.execute(\n engine as McpEngine,\n ctx,\n opts.tool // Pass tool override from RunOptions\n );\n break;\n case \"custom\":\n output = await this.customBackend.execute(engine as CustomEngine, ctx);\n break;\n }\n } catch (err) {\n status = \"error\";\n error = (err as Error).message;\n }\n\n const completedAt = new Date().toISOString();\n const durationMs =\n new Date(completedAt).getTime() - new Date(startedAt).getTime();\n\n // [EARS-H1, H2] Write ExecutionRecord\n // Build result message (min 10 chars required by schema)\n const resultMessage = status === \"success\"\n ? output?.message || `Agent ${opts.agentId} completed successfully`\n : `Agent ${opts.agentId} failed: ${error || 'Unknown error'}`;\n\n const executionRecord = await this.executionAdapter.create(\n {\n taskId: opts.taskId,\n type: status === \"success\" ? \"completion\" : \"blocker\",\n title: `Agent execution: ${opts.agentId}`,\n result: resultMessage.length >= 10 ? resultMessage : resultMessage.padEnd(10, '.'),\n metadata: {\n agentId: opts.agentId,\n runId,\n status,\n output: status === \"success\" ? output : undefined,\n error: status === \"error\" ? error : undefined,\n startedAt,\n completedAt,\n durationMs,\n },\n },\n ctx.actorId\n );\n\n // [EARS-H3] executionRecordId in response\n const executionRecordId = executionRecord.id;\n\n // [EARS-I2, I3] Emit completion event\n if (status === \"success\") {\n this.emitEvent({\n type: \"agent:completed\",\n payload: {\n runId,\n agentId: opts.agentId,\n taskId: opts.taskId,\n status,\n durationMs,\n executionRecordId,\n },\n });\n } else {\n this.emitEvent({\n type: \"agent:error\",\n payload: {\n runId,\n agentId: opts.agentId,\n taskId: opts.taskId,\n status,\n error: error!,\n durationMs,\n executionRecordId,\n },\n });\n }\n\n // [EARS-J1, J2, J3] Return AgentResponse\n const response: AgentResponse = {\n runId,\n agentId: opts.agentId,\n status,\n executionRecordId,\n startedAt,\n completedAt,\n durationMs,\n };\n\n // [EARS-J2] Include output only on success\n if (status === \"success\" && output) {\n response.output = output;\n }\n\n // [EARS-J3] Include error only on failure\n if (status === \"error\" && error) {\n response.error = error;\n }\n\n return response;\n }\n\n /**\n * [EARS-A1, A2] Loads AgentRecord from .gitgov/agents/agent-{id}.json\n */\n private async loadAgent(agentId: string): Promise<AgentRecord> {\n // Remove \"agent:\" prefix if present\n const id = agentId.startsWith(\"agent:\") ? agentId.slice(6) : agentId;\n const agentPath = path.join(this.gitgovPath, \"agents\", `agent-${id}.json`);\n\n try {\n const content = await fs.readFile(agentPath, \"utf-8\");\n const record = JSON.parse(content);\n // Return payload if wrapped in GitGovRecord structure\n return record.payload ?? record;\n } catch {\n throw new AgentNotFoundError(agentId);\n }\n }\n\n /**\n * [EARS-I4] Emits event via EventBus if available.\n * Works silently without EventBus.\n */\n private emitEvent(event: AgentRunnerEvent): void {\n if (this.eventBus) {\n this.eventBus.publish({\n type: event.type,\n timestamp: Date.now(),\n source: \"agent_runner_module\",\n payload: event.payload,\n });\n }\n }\n}\n\n/**\n * [EARS-K1] Factory function for FsAgentRunner.\n *\n * Creates a filesystem-based agent runner with injected dependencies.\n * Recommended for dependency injection scenarios.\n */\nexport function createFsAgentRunner(deps: AgentRunnerDependencies): IAgentRunner {\n return new FsAgentRunner(deps);\n}\n","/**\n * Filesystem AgentRunner implementation\n *\n * This module provides the filesystem-based implementation of IAgentRunner:\n * - FsAgentRunner: Loads AgentRecords from .gitgov/agents/\n * - createAgentRunner(): Factory function for DI\n *\n * Note: LocalBackend is re-exported from backends/ for convenience.\n * Use @gitgov/core for direct backend imports.\n */\nexport { FsAgentRunner } from './fs_agent_runner';\nexport { LocalBackend } from '../backends';\nexport type { AgentRunnerDependencies as FsAgentRunnerDependencies } from '../agent_runner.types';\n\nimport type { IAgentRunner } from '../agent_runner';\nimport type { AgentRunnerDependencies } from '../agent_runner.types';\nimport { FsAgentRunner } from './fs_agent_runner';\n\n/**\n * Factory function to create a filesystem-based AgentRunner.\n */\nexport function createAgentRunner(deps: AgentRunnerDependencies): IAgentRunner {\n return new FsAgentRunner(deps);\n}\n"]}
|