@fractary/codex 0.1.1 → 0.1.2

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.
Files changed (2) hide show
  1. package/README.md +266 -161
  2. package/package.json +9 -3
package/README.md CHANGED
@@ -1,23 +1,24 @@
1
1
  # @fractary/codex
2
2
 
3
- Core SDK for Fractary Codex - a centralized knowledge management and distribution platform for organizations.
3
+ Core SDK for Fractary Codex - knowledge infrastructure for AI agents.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/@fractary/codex.svg)](https://www.npmjs.com/package/@fractary/codex)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
8
  ## Overview
9
9
 
10
- The Codex SDK provides the foundational business logic for the Fractary Codex system, which enables organizations to maintain a single source of truth for documentation, AI tools, and organizational knowledge across all projects.
10
+ The Codex SDK provides foundational infrastructure for managing organizational knowledge across AI agents and projects. It implements a universal reference system (`codex://` URIs), multi-provider storage, intelligent caching, file synchronization, and MCP (Model Context Protocol) integration.
11
11
 
12
12
  ### Key Features
13
13
 
14
- - **Metadata Parsing**: Extract and validate YAML frontmatter from markdown files
15
- - **Pattern Matching**: Glob-based pattern matching for intelligent file routing
16
- - **Smart Routing**: Determine which files should sync to which repositories
17
- - **Configuration Management**: Multi-source configuration with sensible defaults
18
- - **Organization-Agnostic**: Works for any organization, not just Fractary
14
+ - **Universal References**: `codex://` URI scheme for cross-project knowledge references
15
+ - **Multi-Provider Storage**: Local filesystem, GitHub, and HTTP storage backends
16
+ - **Intelligent Caching**: Multi-tier caching (L1 memory, L2 disk, L3 network) with LRU eviction
17
+ - **File Synchronization**: Bidirectional sync with conflict detection
18
+ - **MCP Integration**: Model Context Protocol server for AI agent integration
19
+ - **Permission System**: Fine-grained access control (none/read/write/admin)
20
+ - **Migration Tools**: Upgrade from v2.x to v3.0 configuration format
19
21
  - **Type-Safe**: Full TypeScript support with strict typing
20
- - **Well-Tested**: Comprehensive unit test coverage
21
22
 
22
23
  ## Installation
23
24
 
@@ -29,193 +30,301 @@ npm install @fractary/codex
29
30
 
30
31
  ```typescript
31
32
  import {
32
- parseMetadata,
33
- shouldSyncToRepo,
34
- loadConfig
33
+ parseReference,
34
+ resolveReference,
35
+ CacheManager,
36
+ StorageManager,
37
+ createMcpServer
35
38
  } from '@fractary/codex'
36
39
 
37
- // 1. Load configuration
38
- const config = loadConfig({
39
- organizationSlug: 'fractary'
40
- })
40
+ // Parse a codex URI
41
+ const ref = parseReference('codex://myorg/docs/api-guide.md')
42
+ console.log(ref.org) // 'myorg'
43
+ console.log(ref.path) // 'docs/api-guide.md'
41
44
 
42
- // 2. Parse frontmatter from a markdown file
43
- const fileContent = await readFile('docs/api-guide.md', 'utf-8')
44
- const { metadata, content } = parseMetadata(fileContent)
45
-
46
- // 3. Determine if file should sync to a target repository
47
- const shouldSync = shouldSyncToRepo({
48
- filePath: 'docs/api-guide.md',
49
- fileMetadata: metadata,
50
- targetRepo: 'api-gateway',
51
- sourceRepo: 'codex.fractary.com',
52
- rules: config.rules
45
+ // Resolve to actual file location
46
+ const resolved = resolveReference(ref, {
47
+ cacheDir: '.codex-cache'
53
48
  })
54
49
 
55
- console.log(`Sync to api-gateway: ${shouldSync}`)
50
+ // Create storage and cache managers
51
+ const storage = StorageManager.create()
52
+ const cache = CacheManager.create({ cacheDir: '.codex-cache' })
53
+
54
+ // Fetch content with caching
55
+ const content = await cache.get('codex://myorg/docs/api-guide.md')
56
56
  ```
57
57
 
58
- ## Core Concepts
58
+ ## Core Modules
59
+
60
+ ### References
61
+
62
+ Universal `codex://` URI system for cross-project knowledge references:
59
63
 
60
- ### Metadata Parsing
64
+ ```typescript
65
+ import {
66
+ parseReference,
67
+ buildUri,
68
+ resolveReference,
69
+ validateUri
70
+ } from '@fractary/codex'
61
71
 
62
- The SDK parses YAML frontmatter from markdown files to extract sync rules and metadata:
72
+ // Parse URI
73
+ const ref = parseReference('codex://fractary/codex/docs/api.md')
74
+ // { org: 'fractary', project: 'codex', path: 'docs/api.md' }
63
75
 
64
- ```yaml
65
- ---
66
- org: fractary
67
- system: api-gateway
68
- codex_sync_include: ['api-*', 'core-*']
69
- codex_sync_exclude: ['*-test', '*-dev']
70
- visibility: internal
71
- tags: [api, rest]
72
- ---
76
+ // Build URI
77
+ const uri = buildUri('fractary', 'codex', 'docs/api.md')
78
+ // 'codex://fractary/codex/docs/api.md'
73
79
 
74
- # API Documentation
80
+ // Validate
81
+ const isValid = validateUri('codex://org/project/path.md')
75
82
  ```
76
83
 
84
+ ### Storage
85
+
86
+ Multi-provider storage abstraction with priority-based fallback:
87
+
77
88
  ```typescript
78
- import { parseMetadata } from '@fractary/codex'
89
+ import {
90
+ StorageManager,
91
+ LocalStorage,
92
+ GitHubStorage,
93
+ HttpStorage
94
+ } from '@fractary/codex'
79
95
 
80
- const result = parseMetadata(markdown)
81
- console.log(result.metadata.codex_sync_include) // ['api-*', 'core-*']
96
+ // Create storage manager with multiple providers
97
+ const storage = StorageManager.create({
98
+ providers: [
99
+ { type: 'local', basePath: './knowledge' },
100
+ { type: 'github', token: process.env.GITHUB_TOKEN },
101
+ { type: 'http', baseUrl: 'https://codex.example.com' }
102
+ ]
103
+ })
104
+
105
+ // Fetch content (tries providers in order)
106
+ const result = await storage.fetch('codex://org/project/file.md')
107
+ console.log(result.content)
108
+ console.log(result.provider) // Which provider served the content
82
109
  ```
83
110
 
84
- ### Pattern Matching
111
+ ### Cache
85
112
 
86
- Glob patterns determine which repositories receive which files:
113
+ Multi-tier caching with LRU eviction and stale-while-revalidate:
87
114
 
88
115
  ```typescript
89
- import { matchPattern, matchAnyPattern } from '@fractary/codex'
116
+ import { CacheManager, createCacheManager } from '@fractary/codex'
117
+
118
+ const cache = createCacheManager({
119
+ cacheDir: '.codex-cache',
120
+ maxMemorySize: 50 * 1024 * 1024, // 50MB L1 cache
121
+ maxDiskSize: 500 * 1024 * 1024, // 500MB L2 cache
122
+ defaultTtl: 3600 // 1 hour TTL
123
+ })
124
+
125
+ // Get with automatic caching
126
+ const entry = await cache.get('codex://org/project/file.md')
90
127
 
91
- // Single pattern
92
- matchPattern('api-*', 'api-gateway') // true
93
- matchPattern('api-*', 'web-app') // false
128
+ // Check cache status
129
+ const status = cache.getStatus('codex://org/project/file.md')
130
+ // 'fresh' | 'stale' | 'expired' | 'missing'
94
131
 
95
- // Multiple patterns
96
- matchAnyPattern(['api-*', 'core-*'], 'api-gateway') // true
97
- matchAnyPattern(['api-*', 'core-*'], 'web-app') // false
132
+ // Invalidate specific entry
133
+ await cache.invalidate('codex://org/project/file.md')
98
134
 
99
- // Special: match all
100
- matchAnyPattern(['*'], 'anything') // true
135
+ // Clear all cache
136
+ await cache.clear()
101
137
  ```
102
138
 
103
- ### Sync Routing
139
+ ### MCP Server
104
140
 
105
- Determine which repositories should receive a file based on frontmatter rules:
141
+ Model Context Protocol integration for AI agents:
106
142
 
107
143
  ```typescript
108
- import { shouldSyncToRepo } from '@fractary/codex'
109
-
110
- const shouldSync = shouldSyncToRepo({
111
- filePath: 'docs/api-guide.md',
112
- fileMetadata: {
113
- codex_sync_include: ['api-*', 'core-*'],
114
- codex_sync_exclude: ['*-test']
115
- },
116
- targetRepo: 'api-gateway',
117
- sourceRepo: 'codex.fractary.com'
144
+ import { createMcpServer } from '@fractary/codex'
145
+
146
+ const server = createMcpServer({
147
+ name: 'codex',
148
+ version: '1.0.0',
149
+ cacheDir: '.codex-cache'
118
150
  })
119
151
 
120
- // Returns: true (matches 'api-*' and not excluded)
152
+ // Available tools:
153
+ // - codex_fetch: Fetch document by URI
154
+ // - codex_search: Search across documents
155
+ // - codex_list: List available documents
156
+ // - codex_invalidate: Clear cache entries
157
+
158
+ await server.start()
121
159
  ```
122
160
 
123
- ### Configuration
161
+ ### Sync
124
162
 
125
- The SDK supports multi-source configuration:
163
+ Bidirectional file synchronization:
126
164
 
127
165
  ```typescript
128
- import { loadConfig, resolveOrganization } from '@fractary/codex'
166
+ import { SyncManager, createSyncPlan } from '@fractary/codex'
129
167
 
130
- // Auto-detect organization from repo name
131
- const org = resolveOrganization({
132
- repoName: 'codex.fractary.com'
133
- }) // Returns: 'fractary'
168
+ const sync = new SyncManager({
169
+ sourceDir: './local-docs',
170
+ targetDir: './codex-repo'
171
+ })
134
172
 
135
- // Load configuration
136
- const config = loadConfig({
137
- organizationSlug: 'fractary'
173
+ // Create sync plan (dry run)
174
+ const plan = await sync.plan({
175
+ direction: 'bidirectional',
176
+ include: ['**/*.md'],
177
+ exclude: ['**/node_modules/**']
138
178
  })
139
179
 
140
- console.log(config)
141
- /*
142
- {
143
- organizationSlug: 'fractary',
144
- directories: {
145
- source: '.fractary',
146
- target: '.fractary',
147
- systems: '.fractary/systems'
148
- },
149
- rules: {
150
- preventSelfSync: true,
151
- preventCodexSync: true,
152
- allowProjectOverrides: true,
153
- autoSyncPatterns: []
154
- }
155
- }
156
- */
180
+ console.log(plan.operations) // List of copy/update/delete operations
181
+
182
+ // Execute sync
183
+ const result = await sync.execute(plan)
157
184
  ```
158
185
 
159
- ## API Reference
186
+ ### Permissions
160
187
 
161
- ### Metadata Parsing
188
+ Fine-grained access control:
162
189
 
163
- - `parseMetadata(content, options?)` - Parse YAML frontmatter from markdown
164
- - `hasFrontmatter(content)` - Check if content has frontmatter
165
- - `validateMetadata(metadata)` - Validate metadata against schema
166
- - `extractRawFrontmatter(content)` - Extract raw frontmatter string
190
+ ```typescript
191
+ import {
192
+ PermissionManager,
193
+ createRule,
194
+ CommonRules
195
+ } from '@fractary/codex'
167
196
 
168
- ### Pattern Matching
197
+ const permissions = new PermissionManager({
198
+ config: { enforced: true }
199
+ })
169
200
 
170
- - `matchPattern(pattern, value)` - Match a single glob pattern
171
- - `matchAnyPattern(patterns, value)` - Match against multiple patterns
172
- - `filterByPatterns(patterns, values)` - Filter array by patterns
173
- - `evaluatePatterns({ value, include, exclude })` - Evaluate include/exclude rules
201
+ // Add rules
202
+ permissions.addRule(CommonRules.allowDocs()) // Allow read on docs/**
203
+ permissions.addRule(CommonRules.denyPrivate()) // Deny .private/**
204
+ permissions.addRule(createRule({
205
+ pattern: 'admin/**',
206
+ actions: ['fetch', 'sync'],
207
+ level: 'admin'
208
+ }))
209
+
210
+ // Check permissions
211
+ const allowed = permissions.isAllowed('docs/api.md', 'fetch')
212
+ const hasAccess = permissions.hasPermission('admin/config.md', 'sync', 'admin')
213
+
214
+ // Filter paths by permission
215
+ const accessible = permissions.filterAllowed(paths, 'fetch')
216
+ ```
174
217
 
175
- ### Configuration
218
+ ### Migration
176
219
 
177
- - `loadConfig(options)` - Load configuration from all sources
178
- - `resolveOrganization(options)` - Resolve organization slug
179
- - `extractOrgFromRepoName(repoName)` - Extract org from repo name pattern
180
- - `getDefaultConfig(orgSlug)` - Get default configuration
220
+ Upgrade from v2.x to v3.0 configuration:
181
221
 
182
- ### Routing
222
+ ```typescript
223
+ import {
224
+ migrateConfig,
225
+ detectVersion,
226
+ convertLegacyReferences
227
+ } from '@fractary/codex'
228
+
229
+ // Detect config version
230
+ const detection = detectVersion(oldConfig)
231
+ console.log(detection.version) // '2.x' | '3.0' | 'unknown'
232
+
233
+ // Migrate configuration
234
+ const result = migrateConfig(oldConfig)
235
+ if (result.success) {
236
+ console.log(result.config) // Modern v3.0 config
237
+ console.log(result.changes) // List of changes made
238
+ }
239
+
240
+ // Convert legacy references in content
241
+ const converted = convertLegacyReferences(content, {
242
+ defaultOrg: 'myorg',
243
+ defaultProject: 'myproject'
244
+ })
245
+ ```
246
+
247
+ ### Types
183
248
 
184
- - `shouldSyncToRepo(options)` - Determine if file should sync to repo
185
- - `getTargetRepos(options)` - Get all repos that should receive a file
249
+ Extensible artifact type system with TTL management:
250
+
251
+ ```typescript
252
+ import { TypeRegistry, BUILT_IN_TYPES } from '@fractary/codex'
253
+
254
+ const types = new TypeRegistry()
255
+
256
+ // Get TTL for a file
257
+ const ttl = types.getTtl('docs/api.md') // Uses 'docs' type TTL
258
+ const specTtl = types.getTtl('specs/v1.md') // Uses 'specs' type TTL
259
+
260
+ // Register custom type
261
+ types.register({
262
+ name: 'templates',
263
+ patterns: ['templates/**/*.md'],
264
+ ttl: 86400, // 24 hours
265
+ description: 'Document templates'
266
+ })
267
+ ```
268
+
269
+ ## API Reference
270
+
271
+ ### References Module
272
+ - `parseReference(uri)` - Parse codex:// URI
273
+ - `buildUri(org, project, path)` - Build codex:// URI
274
+ - `resolveReference(ref, options)` - Resolve to file path
275
+ - `validateUri(uri)` - Validate URI format
276
+
277
+ ### Storage Module
278
+ - `StorageManager` - Multi-provider storage coordinator
279
+ - `LocalStorage` - Local filesystem provider
280
+ - `GitHubStorage` - GitHub API/raw content provider
281
+ - `HttpStorage` - Generic HTTP provider
282
+
283
+ ### Cache Module
284
+ - `CacheManager` - Multi-tier cache coordinator
285
+ - `CachePersistence` - Disk persistence layer
286
+ - `createCacheEntry(uri, content, options)` - Create cache entry
287
+
288
+ ### MCP Module
289
+ - `McpServer` - MCP protocol server
290
+ - `CODEX_TOOLS` - Available tool definitions
291
+ - `handleToolCall(name, args, context)` - Handle tool invocation
292
+
293
+ ### Sync Module
294
+ - `SyncManager` - Sync orchestration
295
+ - `createSyncPlan(options)` - Create sync plan
296
+ - `evaluatePath(path, rules)` - Evaluate sync rules
297
+
298
+ ### Permissions Module
299
+ - `PermissionManager` - Permission orchestration
300
+ - `createRule(options)` - Create permission rule
301
+ - `CommonRules` - Pre-built common rules
302
+
303
+ ### Migration Module
304
+ - `migrateConfig(config)` - Migrate v2.x to v3.0
305
+ - `detectVersion(config)` - Detect config version
306
+ - `convertLegacyReferences(content)` - Convert old references
186
307
 
187
308
  ## Configuration
188
309
 
189
310
  ### Environment Variables
190
311
 
191
- - `ORGANIZATION_SLUG` - Organization identifier
192
- - `CODEX_ORG_SLUG` - Alternative organization identifier
193
- - `CODEX_SOURCE_DIR` - Source directory (default: `.{org}`)
194
- - `CODEX_TARGET_DIR` - Target directory (default: `.{org}`)
195
- - `CODEX_PREVENT_SELF_SYNC` - Prevent self-sync (default: `true`)
196
- - `CODEX_ALLOW_PROJECT_OVERRIDES` - Allow project overrides (default: `true`)
197
-
198
- ### Auto-Sync Patterns
312
+ ```bash
313
+ CODEX_CACHE_DIR=".codex-cache" # Cache directory
314
+ CODEX_DEFAULT_TTL="3600" # Default TTL in seconds
315
+ GITHUB_TOKEN="ghp_xxx" # GitHub API token (for GitHub storage)
316
+ ```
199
317
 
200
- Configure patterns that automatically sync to repositories:
318
+ ### Cache Configuration
201
319
 
202
320
  ```typescript
203
- const config = loadConfig({
204
- organizationSlug: 'fractary'
321
+ const cache = createCacheManager({
322
+ cacheDir: '.codex-cache',
323
+ maxMemorySize: 50 * 1024 * 1024, // 50MB
324
+ maxDiskSize: 500 * 1024 * 1024, // 500MB
325
+ defaultTtl: 3600, // 1 hour
326
+ staleWhileRevalidate: true
205
327
  })
206
-
207
- config.rules.autoSyncPatterns = [
208
- {
209
- pattern: '*/docs/schema/*.json',
210
- include: ['*'], // All repos
211
- exclude: []
212
- },
213
- {
214
- pattern: '*/security/**/*.md',
215
- include: ['*'],
216
- exclude: ['*-public']
217
- }
218
- ]
219
328
  ```
220
329
 
221
330
  ## Development
@@ -235,39 +344,35 @@ npm run test:coverage
235
344
 
236
345
  # Type check
237
346
  npm run typecheck
347
+
348
+ # Lint
349
+ npm run lint
238
350
  ```
239
351
 
240
352
  ## Project Structure
241
353
 
242
354
  ```
243
355
  src/
244
- ├── core/
245
- ├── metadata/ # Frontmatter parsing
246
- ├── patterns/ # Pattern matching
247
- ├── routing/ # Sync routing logic
248
- │ └── config/ # Configuration system
249
- ├── schemas/ # Zod schemas
250
- ├── errors/ # Error classes
251
- └── index.ts # Main exports
252
-
253
- tests/
254
- ├── unit/ # Unit tests
255
- └── fixtures/ # Test fixtures
356
+ ├── references/ # codex:// URI parsing and resolution
357
+ ├── types/ # Artifact type system
358
+ ├── storage/ # Multi-provider storage
359
+ ├── cache/ # Multi-tier caching
360
+ ├── mcp/ # MCP server integration
361
+ ├── sync/ # File synchronization
362
+ ├── permissions/ # Access control
363
+ ├── migration/ # v2.x to v3.0 migration
364
+ ├── core/ # Core utilities
365
+ │ ├── config/ # Configuration management
366
+ ├── metadata/ # Frontmatter parsing
367
+ │ ├── patterns/ # Glob pattern matching
368
+ │ └── routing/ # Sync routing
369
+ ├── schemas/ # Zod validation schemas
370
+ ├── errors/ # Error classes
371
+ └── index.ts # Public exports
256
372
  ```
257
373
 
258
- ## Specifications
259
-
260
- Detailed specifications are available in `/docs/specs/`:
261
-
262
- - [SPEC-00001: Core SDK Overview](./docs/specs/SPEC-00001-core-sdk-overview.md)
263
- - [SPEC-00002: Metadata Parsing](./docs/specs/SPEC-00002-metadata-parsing.md)
264
- - [SPEC-00003: Pattern Matching](./docs/specs/SPEC-00003-pattern-matching.md)
265
- - [SPEC-00004: Routing & Distribution](./docs/specs/SPEC-00004-routing-distribution.md)
266
- - [SPEC-00005: Configuration System](./docs/specs/SPEC-00005-configuration-system.md)
267
-
268
374
  ## Related Projects
269
375
 
270
- - **fractary-cli** - Unified CLI for all Fractary tools (coming soon)
271
376
  - **forge-bundle-codex-github-core** - GitHub Actions workflows for codex sync
272
377
  - **forge-bundle-codex-claude-agents** - Claude Code agents for codex management
273
378
 
@@ -277,4 +382,4 @@ MIT © Fractary Engineering
277
382
 
278
383
  ## Contributing
279
384
 
280
- This is part of the Fractary ecosystem. For issues or contributions, please refer to the [main repository](https://github.com/fractary/codex).
385
+ For issues or contributions, please visit the [GitHub repository](https://github.com/fractary/codex).
package/package.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "name": "@fractary/codex",
3
- "version": "0.1.1",
4
- "description": "Core SDK for Fractary Codex - centralized knowledge management and distribution platform",
3
+ "version": "0.1.2",
4
+ "description": "Knowledge infrastructure SDK for AI agents - universal references, multi-tier caching, storage abstraction, and MCP integration",
5
5
  "keywords": [
6
6
  "codex",
7
- "documentation",
8
7
  "knowledge-management",
8
+ "ai-agents",
9
+ "mcp",
10
+ "model-context-protocol",
11
+ "caching",
12
+ "storage",
9
13
  "sync",
14
+ "permissions",
15
+ "typescript",
10
16
  "fractary"
11
17
  ],
12
18
  "homepage": "https://github.com/fractary/codex#readme",