@gitgov/core 1.13.0 → 2.0.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 CHANGED
@@ -6,309 +6,190 @@
6
6
 
7
7
  `@gitgov/core` is the **SDK** for the GitGovernance ecosystem. It provides a type-safe, local-first, and schema-driven API to manage identities, agents, tasks, and workflows in software projects.
8
8
 
9
- ## 🚀 Quick Start
9
+ ## Install
10
10
 
11
- This example shows how to create a new task using the `BacklogAdapter`. The SDK uses dependency injection - each adapter requires its dependencies to be explicitly provided.
11
+ ```bash
12
+ pnpm add @gitgov/core
13
+ ```
12
14
 
13
- _Note: This example assumes it is run inside an initialized GitGovernance project._
15
+ ## Quick Start
14
16
 
15
- ```typescript
16
- import { Adapters, Store, EventBus } from "@gitgov/core";
17
- import type {
18
- TaskRecord,
19
- CycleRecord,
20
- ActorRecord,
21
- AgentRecord,
22
- } from "@gitgov/core";
23
-
24
- // Extract classes from namespaces
25
- const { IdentityAdapter, BacklogAdapter, WorkflowMethodologyAdapter } =
26
- Adapters;
27
- const { RecordStore } = Store;
28
- const { EventBus: EventBusClass } = EventBus;
29
-
30
- // 1. Setup core infrastructure
31
- const eventBus = new EventBusClass();
32
- const actorStore = new RecordStore<ActorRecord>("actors");
33
- const agentStore = new RecordStore<AgentRecord>("agents");
34
- const taskStore = new RecordStore<TaskRecord>("tasks");
35
- const cycleStore = new RecordStore<CycleRecord>("cycles");
36
-
37
- // 2. Setup identity adapter
38
- const identity = new IdentityAdapter({
39
- actorStore,
40
- agentStore,
41
- });
17
+ The SDK uses dependency injection. Each adapter receives its dependencies via constructor.
42
18
 
43
- // 3. Setup workflow methodology
44
- const workflowMethodology = WorkflowMethodologyAdapter.createDefault();
45
-
46
- // 4. Setup BacklogAdapter with minimal dependencies for basic task creation
47
- const backlogAdapter = new BacklogAdapter({
48
- taskStore,
49
- cycleStore,
50
- identity,
51
- eventBus,
52
- workflowMethodologyAdapter: workflowMethodology,
53
- // Optional dependencies (can be undefined for basic usage)
54
- feedbackStore: undefined,
55
- executionStore: undefined,
56
- changelogStore: undefined,
57
- feedbackAdapter: undefined,
58
- executionAdapter: undefined,
59
- changelogAdapter: undefined,
60
- metricsAdapter: undefined,
19
+ ```typescript
20
+ import { Adapters, Store, EventBus } from '@gitgov/core';
21
+ import { FsRecordStore } from '@gitgov/core/fs';
22
+ import type { TaskRecord, CycleRecord, ActorRecord, AgentRecord } from '@gitgov/core';
23
+
24
+ // Infrastructure
25
+ const eventBus = new EventBus.EventBus();
26
+ const taskStore = new FsRecordStore<TaskRecord>({ recordType: 'tasks', projectRoot: '.' });
27
+ const cycleStore = new FsRecordStore<CycleRecord>({ recordType: 'cycles', projectRoot: '.' });
28
+ const actorStore = new FsRecordStore<ActorRecord>({ recordType: 'actors', projectRoot: '.' });
29
+ const agentStore = new FsRecordStore<AgentRecord>({ recordType: 'agents', projectRoot: '.' });
30
+
31
+ // Adapters compose modules
32
+ const identity = new Adapters.IdentityAdapter({ actorStore, agentStore });
33
+ const workflow = Adapters.WorkflowAdapter.createDefault();
34
+ const backlog = new Adapters.BacklogAdapter({
35
+ taskStore, cycleStore, identity, eventBus, workflowAdapter: workflow,
61
36
  });
62
37
 
63
- // 5. Create a new task
64
- const newTaskPayload = {
65
- title: "Implement user authentication",
66
- priority: "high",
67
- description: "Add OAuth2 integration for Google and GitHub.",
68
- };
69
-
70
- const taskRecord = await backlogAdapter.createTask(
71
- newTaskPayload,
72
- "human:project-lead" // The actor performing the action
38
+ // Create a task
39
+ const task = await backlog.createTask(
40
+ { title: 'Implement auth', priority: 'high' },
41
+ 'human:project-lead',
73
42
  );
74
-
75
- console.log("✅ Task Created Successfully:");
76
- console.log({
77
- id: taskRecord.id,
78
- title: taskRecord.title,
79
- status: taskRecord.status, // The adapter sets the default status
80
- });
81
-
82
- // Expected output:
83
- // ✅ Task Created Successfully:
84
- // {
85
- // id: 'task:1727445600000-implement-user-authentication',
86
- // title: 'Implement user authentication',
87
- // status: 'draft'
88
- // }
89
43
  ```
90
44
 
91
- > **For production usage:** See the [complete setup example](../../blueprints/03_products/core/core_reference.md#quick-start) with all adapters and dependencies properly configured.
92
-
93
- ## ✅ What's Implemented (v1.0)
94
-
95
- ### Identity Management
96
-
97
- - **ActorRecord**: Cryptographic identities with Ed25519 keys
98
- - **AgentRecord**: AI agent operational manifests
99
- - **CRUD Operations**: Create, read, list, revoke operations
100
- - **Schema Validation**: JSON Schema-driven with detailed errors
101
- - **Performance**: Schema validation caching
102
-
103
- ### Adapter Ecosystem (9/9 Adapters)
104
-
105
- - **ProjectAdapter**: Project initialization engine with 3-adapter orchestration (18 tests)
106
- - **BacklogAdapter**: Task and cycle lifecycle management with workflow validation (71 tests)
107
- - **MetricsAdapter**: Pure calculation engine for system analytics (32 tests)
108
- - **ChangelogAdapter**: System historian for change documentation (31 tests)
109
- - **ExecutionAdapter**: Audit log for work execution (13 tests)
110
- - **FeedbackAdapter**: Structured communication and blocking management (21 tests)
111
- - **IdentityAdapter**: Cryptographic identity and agent management (25 tests)
112
- - **WorkflowMethodologyAdapter**: Configurable workflow validation engine (51 tests)
113
- - **IndexerAdapter**: Local cache optimization for performance (5 tests)
114
-
115
- ### Record System (8/8 Records)
116
-
117
- - **TaskRecord**: Factory and validation for task management
118
- - **CycleRecord**: Factory and validation for cycle organization
119
- - **ExecutionRecord**: Factory and validation for execution logging
120
- - **ChangelogRecord**: Factory and validation for changelog generation
121
- - **FeedbackRecord**: Factory and validation for feedback management
122
- - **ActorRecord**: Factory and validation for identity management
123
- - **AgentRecord**: Factory and validation for agent manifests
124
-
125
- ### Infrastructure Modules
126
-
127
- - **Generic Store**: CRUD operations for all record types
128
- - **Integration Testing**: Cross-module validation framework
129
- - **WorkflowMethodologyAdapter**: Configurable workflow validation engine
130
- - **EventBusModule**: Event-driven architecture foundation with 9 event types
131
- - **DiagramGenerator**: Automatic Mermaid diagram generation with deduplication and data quality warnings
132
- - **Schema Generation Pipeline**: Automatic YAML→JSON→TypeScript transformation with build-time validation
133
-
134
- ## 🏗️ Architecture
135
-
136
- The package is built with a domain-driven architecture to separate responsibilities. The public API is exposed through `Adapters`.
45
+ ## Architecture
137
46
 
138
47
  ```mermaid
139
- graph TD
140
- subgraph "@gitgov/core"
141
- PA[ProjectAdapter] --> IA[IdentityAdapter];
142
- PA --> BA[BacklogAdapter];
143
- PA --> WMA[WorkflowMethodologyAdapter];
144
- PA --> CM[ConfigManager];
145
- PA --> F((Factories));
146
- IA --> F;
147
- IA --> V((Validation));
148
- IA --> S((Store));
149
- IA --> CR((Crypto));
48
+ graph LR
49
+ subgraph "@gitgov/core — Pure Logic"
50
+ Adapters["Adapters (10)"]
51
+ Modules["Modules (24)"]
52
+ Records["Record System"]
53
+
54
+ Adapters --> Modules
55
+ Adapters --> Records
56
+ Modules --> Records
150
57
  end
151
58
 
152
- subgraph "Consumidores"
153
- CLI["@gitgov/cli"]
154
- SAAS["@gitgov/saas"]
59
+ subgraph "@gitgov/core/fs — I/O"
60
+ FsStore["FsRecordStore"]
61
+ FsGit["LocalGitModule"]
62
+ FsLint["FsLintModule"]
63
+ FsOther["FsKeyProvider, FsFileLister, ..."]
155
64
  end
156
65
 
157
- CLI --> PA;
158
- SAAS --> PA;
159
-
160
- style PA fill:#e8f5e8,stroke:#4caf50,stroke-width:2px
161
- style IA fill:#e8f5e8,stroke:#4caf50,stroke-width:2px
162
- style BA fill:#e8f5e8,stroke:#4caf50,stroke-width:2px
163
- ```
164
-
165
- ### Core Principles
166
-
167
- 1. **Protocol-Driven**: The canonical JSON Schemas that define the governance protocol are bundled with the package and are the single source of truth for all data validation.
168
- 2. **Build-Time Generation**: Schemas and types are automatically generated from YAML protocols using `npm run prebuild` (pipeline) or individual commands, ensuring 100% coherence.
169
- 3. **Type Safety**: Strict TypeScript with no `any` to prevent compile-time errors.
170
- 4. **Event Coherence Guarantee**: Event payloads are derived from canonical records using TypeScript Utility Types, ensuring 100% consistency between system state and system events.
171
- 5. **Rich Errors**: Detailed, field-level validation errors to make debugging easier.
172
- 6. **Performance**: A compiled schema cache (`SchemaValidationCache`) minimizes I/O and accelerates repetitive validations.
173
- 7. **Local-First**: Designed to operate directly on a Git repository as its database.
66
+ subgraph "@gitgov/core/memory — Testing"
67
+ MemStore["MemoryRecordStore"]
68
+ MemGit["MemoryGitModule"]
69
+ MemOther["MockKeyProvider, MemoryFileLister"]
70
+ end
174
71
 
175
- ## 🔧 Advanced Usage
72
+ Adapters -.->|DI| FsStore
73
+ Adapters -.->|DI| MemStore
176
74
 
177
- ### Schema Validation
75
+ CLI["@gitgov/cli"] --> Adapters
76
+ SaaS["@gitgov/saas-api"] --> Adapters
178
77
 
179
- ```typescript
180
- import {
181
- validateActorRecordDetailed,
182
- DetailedValidationError,
183
- } from "@gitgov/core";
184
-
185
- const result = validateActorRecordDetailed(userData);
186
- if (!result.isValid) {
187
- result.errors.forEach((error) => {
188
- console.log(`❌ ${error.field}: ${error.message}`);
189
- console.log(` Got: ${JSON.stringify(error.value)}`);
190
- });
191
- }
78
+ style Adapters fill:#e8f5e8,stroke:#4caf50,stroke-width:2px
79
+ style FsStore fill:#e3f2fd,stroke:#1976d2
80
+ style MemStore fill:#fff3e0,stroke:#f57c00
192
81
  ```
193
82
 
194
- ### Custom Error Handling
83
+ ### 3 Export Paths
84
+
85
+ | Import | Contents | I/O |
86
+ |--------|----------|-----|
87
+ | `@gitgov/core` | Interfaces, types, pure logic, factories, validators | No |
88
+ | `@gitgov/core/fs` | Filesystem implementations (FsRecordStore, LocalGitModule, FsLintModule, ...) | Yes |
89
+ | `@gitgov/core/memory` | In-memory implementations for testing (MemoryRecordStore, MemoryGitModule, ...) | No |
90
+
91
+ The root import (`@gitgov/core`) never imports `fs`, `path`, or `child_process`.
92
+
93
+ ### Record Symmetry
94
+
95
+ Every record type has 4 parallel artifacts:
96
+
97
+ | Artifact | Directory | Responsibility |
98
+ |----------|-----------|----------------|
99
+ | Types | `record_types/generated/` | Shape of the record (generated from schema) |
100
+ | Factory | `record_factories/` | Create record with defaults + validation |
101
+ | Validator | `record_validations/` | Business rules on the record |
102
+ | Schema | `record_schemas/generated/` | JSON Schema for AJV validation |
103
+
104
+ The 8 records: **Actor, Agent, Task, Cycle, Execution, Changelog, Feedback, Workflow**
105
+
106
+ ## Adapters
107
+
108
+ Adapters are orchestrators that compose modules. All receive dependencies via constructor injection.
109
+
110
+ | Adapter | Purpose |
111
+ |---------|---------|
112
+ | `ProjectAdapter` | Project initialization, environment validation |
113
+ | `IdentityAdapter` | Actor and agent identity management |
114
+ | `BacklogAdapter` | Task and cycle lifecycle, workflow validation |
115
+ | `ExecutionAdapter` | Execution audit log tracking |
116
+ | `FeedbackAdapter` | Structured feedback and blocking resolution |
117
+ | `ChangelogAdapter` | Automatic changelog entries |
118
+ | `MetricsAdapter` | System status and productivity metrics |
119
+ | `IndexerAdapter` | Local cache generation and integrity checks |
120
+ | `WorkflowAdapter` | State transitions with signatures and custom rules |
121
+ | `AgentAdapter` | Agent lifecycle management |
122
+
123
+ ## Modules
124
+
125
+ | Module | Responsibility |
126
+ |--------|----------------|
127
+ | `record_types/` | TypeScript types per record (generated from schemas) |
128
+ | `record_factories/` | Factories with defaults for creating records |
129
+ | `record_validations/` | Business validators (above schema) |
130
+ | `record_schemas/` | JSON Schemas + schema cache + errors |
131
+ | `record_store/` | `RecordStore<T>` interface (impl in fs/memory) |
132
+ | `config_store/` | Storage for project config.json |
133
+ | `config_manager/` | Typed access to config.json (versioned in git) |
134
+ | `session_store/` | Storage for .session.json |
135
+ | `session_manager/` | Typed access to .session.json (ephemeral, not versioned) |
136
+ | `sync_state/` | Push/pull/resolve synchronization state |
137
+ | `git/` | `IGitModule` interface + local/memory implementations |
138
+ | `crypto/` | Checksums, digital signatures, verification |
139
+ | `key_provider/` | Key storage abstraction (fs/memory) |
140
+ | `file_lister/` | File listing abstraction (fs/memory) |
141
+ | `lint/` | Structural + referential validation |
142
+ | `event_bus/` | Typed pub/sub with 9 event types |
143
+ | `agent_runner/` | Agent execution (interface + loader) |
144
+ | `watcher_state/` | File change tracking in .gitgov/ |
145
+ | `project_initializer/` | GitGovernance project setup |
146
+ | `finding_detector/` | Finding detection (regex, heuristic, LLM) |
147
+ | `source_auditor/` | Cross-system audit (code, Jira, gitgov) |
148
+ | `diagram_generator/` | Mermaid diagram generation |
149
+ | `logger/` | Centralized logging |
150
+ | `utils/` | ID generation/parsing, array utils, signature utils |
151
+
152
+ ## Development
195
153
 
196
- ```typescript
197
- import {
198
- DetailedValidationError,
199
- RecordNotFoundError,
200
- ProjectRootError,
201
- } from "@gitgov/core";
202
-
203
- function handleCoreErrors(error: unknown) {
204
- if (error instanceof DetailedValidationError) {
205
- return { type: "validation", fields: error.errors };
206
- } else if (error instanceof RecordNotFoundError) {
207
- return { type: "not_found", code: error.code };
208
- } else if (error instanceof ProjectRootError) {
209
- return { type: "setup", message: "Initialize Git repository first" };
210
- }
211
- return { type: "unknown", error };
212
- }
213
- ```
154
+ ```bash
155
+ # Type check
156
+ pnpm tsc --noEmit
214
157
 
215
- ### Performance Monitoring
158
+ # Build (full pipeline: schemas + types + tsup)
159
+ pnpm build
216
160
 
217
- ```typescript
218
- import { SchemaValidationCache } from "@gitgov/core";
161
+ # Tests
162
+ pnpm test
163
+ pnpm test:coverage
164
+ ```
219
165
 
220
- // Monitor cache efficiency
221
- const stats = SchemaValidationCache.getCacheStats();
222
- console.log(`Cache hit ratio: ${stats.cachedSchemas} schemas loaded`);
166
+ ### Build Pipeline
223
167
 
224
- // Clear cache when schemas are updated
225
- SchemaValidationCache.clearCache();
168
+ ```
169
+ YAML schemas -> JSON schemas (AJV) -> TypeScript types (generated/)
226
170
  ```
227
171
 
228
- ### Diagram Generation
172
+ Individual steps:
229
173
 
230
- ```typescript
231
- import { DiagramGenerator } from "@gitgov/core";
232
-
233
- const generator = new DiagramGenerator();
174
+ ```bash
175
+ pnpm sync # Sync from blueprints (schemas, configs, prompts)
176
+ pnpm compile:types # JSON -> TypeScript
177
+ pnpm generate:indexes # Generate barrel exports
178
+ pnpm validate:schemas # Validate all schemas
179
+ pnpm prebuild # compile:types + generate:indexes
180
+ ```
234
181
 
235
- // Generate Mermaid diagrams from GitGovernance records
236
- const result = await generator.generateFromRecords(cycles, tasks, {
237
- cycleId: "1704067200-cycle-identity-adapter",
238
- layout: "TD",
239
- showWarnings: true,
240
- });
182
+ Never edit files in `generated/`. Modify the source schema and regenerate.
241
183
 
242
- console.log(result.mermaidCode);
243
- // Automatic deduplication and data quality warnings included
244
- ```
184
+ ## License
245
185
 
246
- ## 🧪 Testing & Development
186
+ This package is licensed under the [Mozilla Public License 2.0 (MPL-2.0)](https://opensource.org/licenses/MPL-2.0).
247
187
 
248
- ```bash
249
- # Run all tests (737 tests total)
250
- npm test
251
- npm run test:coverage # Run tests with coverage report
252
-
253
- # Build-time schema and type generation
254
- npm run sync:prompts # Sync agent prompts for npm packaging
255
- npm run sync:schemas # Generate JSON schemas from YAML protocols
256
- npm run sync:workflow-configs # Sync workflow methodology configurations
257
- npm run compile:types # Generate TypeScript types from JSON schemas
258
- npm run generate:indexes # Generate organized export indexes
259
- npm run validate:schemas # Validate all generated schemas
260
-
261
- # Development workflow
262
- npm run prebuild # Pipeline: sync:prompts → compile:types → generate:indexes
263
- npm run build # Clean build with TypeScript compilation
264
- npm run clean # Remove dist directory
265
- npm run clean:generated # Remove all generated schemas and types
266
-
267
- # Type checking
268
- npx tsc --noEmit
269
-
270
- # Watch mode for development
271
- npm test -- --watch
272
- ```
188
+ ## Links
273
189
 
274
- ### Test Coverage
275
-
276
- - **737 tests total** with EARS methodology
277
- - **ProjectAdapter**: 18 tests (project initialization + template processing + error recovery)
278
- - **BacklogAdapter**: 71 tests (workflow lifecycle + event handlers + E2E simulation + deduplication)
279
- - **MetricsAdapter**: 32 tests (Tier 1+2 calculations + performance validation)
280
- - **ChangelogAdapter**: 31 tests (multi-entity changelog + conditional validation)
281
- - **EventBusModule**: 32 tests (20 unit + 12 integration tests with cross-adapter scenarios)
282
- - **FeedbackAdapter**: 21 tests (EARS coverage with dual event emission + duplicate assignment prevention)
283
- - **ExecutionAdapter**: 13 tests (EARS coverage with performance validation)
284
- - **WorkflowMethodologyAdapter**: 51 tests (29 unit + 22 integration tests)
285
- - **Identity Domain**: 66 tests (Adapter + ActorRecord/AgentRecord factories & validators)
286
- - **Validation**: 62 tests (for Task, Cycle, Exec, CL, Feedback records + schema caching)
287
- - **Factories**: 40 tests (for Task, Cycle, Exec, CL, Feedback records)
288
- - **Store**: 26 tests (generic CRUD for all record types)
289
- - **Crypto**: 23 tests (signatures + checksums for all 7 record types)
290
- - **ConfigManager**: 20 tests (configuration + session state + project utilities)
291
- - **IndexerAdapter**: 5 tests (cache generation, validation, and retrieval)
292
- - **Utils**: 10 tests (ID generation utilities)
293
- - **Integration**: 74 tests (cross-module validation)
294
-
295
- ## 📋 Roadmap
296
-
297
- ### Next Steps
298
-
299
- - **Git Adapter**: Development of a low-level adapter for direct Git operations.
300
- - **Platform Adapters**: Integration with platform-specific features (e.g., GitHub Adapter).
301
- - **Advanced Validation**: Creation of `lint` and `audit` modules for structural and protocol validation.
302
-
303
- ### Recently Completed
304
-
305
- - **Adapter Ecosystem**: All 9 core adapters for the foundational domains have been implemented and tested.
306
- - **IndexerAdapter**: A dedicated module for local cache optimization to enhance performance is now available.
307
- - **EventBusModule**: The foundational event-driven architecture is in place, enabling decoupled communication between modules.
308
- - **ProjectAdapter**: The project initialization and orchestration logic is functional.
309
- - **DiagramGenerator Module**: Automatic Mermaid diagram generation with deduplication, data quality warnings, and advanced filtering.
310
- - **Schema Generation Pipeline**: YAML→JSON→TypeScript build-time transformation with automatic synchronization.
190
+ - **GitHub:** https://github.com/gitgovernance/monorepo/tree/main/packages/core
191
+ - **NPM:** https://www.npmjs.com/package/@gitgov/core
311
192
 
312
193
  ---
313
194
 
314
- **Built with ❤️ by the GitGovernance Team**
195
+ **Built with ❤️ by the GitGovernance team.**