@defai.digital/context-domain 13.0.3

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/LICENSE ADDED
@@ -0,0 +1,214 @@
1
+ AutomatosX Open Source Edition - Apache License 2.0
2
+
3
+ This license applies ONLY to the AutomatosX Open Source Edition code
4
+ published on GitHub at https://github.com/defai-digital/automatosx
5
+
6
+ This license does NOT apply to:
7
+ - AutomatosX Pro Edition (proprietary software - separate EULA)
8
+ - AutomatosX Enterprise Edition (proprietary software - separate agreement)
9
+
10
+ For commercial editions, see COMMERCIAL-LICENSE.md
11
+
12
+ ===============================================================================
13
+
14
+ Apache License
15
+ Version 2.0, January 2004
16
+ http://www.apache.org/licenses/
17
+
18
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19
+
20
+ 1. Definitions.
21
+
22
+ "License" shall mean the terms and conditions for use, reproduction,
23
+ and distribution as defined by Sections 1 through 9 of this document.
24
+
25
+ "Licensor" shall mean the copyright owner or entity authorized by
26
+ the copyright owner that is granting the License.
27
+
28
+ "Legal Entity" shall mean the union of the acting entity and all
29
+ other entities that control, are controlled by, or are under common
30
+ control with that entity. For the purposes of this definition,
31
+ "control" means (i) the power, direct or indirect, to cause the
32
+ direction or management of such entity, whether by contract or
33
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34
+ outstanding shares, or (iii) beneficial ownership of such entity.
35
+
36
+ "You" (or "Your") shall mean an individual or Legal Entity
37
+ exercising permissions granted by this License.
38
+
39
+ "Source" form shall mean the preferred form for making modifications,
40
+ including but not limited to software source code, documentation
41
+ source, and configuration files.
42
+
43
+ "Object" form shall mean any form resulting from mechanical
44
+ transformation or translation of a Source form, including but
45
+ not limited to compiled object code, generated documentation,
46
+ and conversions to other media types.
47
+
48
+ "Work" shall mean the work of authorship, whether in Source or
49
+ Object form, made available under the License, as indicated by a
50
+ copyright notice that is included in or attached to the work
51
+ (an example is provided in the Appendix below).
52
+
53
+ "Derivative Works" shall mean any work, whether in Source or Object
54
+ form, that is based on (or derived from) the Work and for which the
55
+ editorial revisions, annotations, elaborations, or other modifications
56
+ represent, as a whole, an original work of authorship. For the purposes
57
+ of this License, Derivative Works shall not include works that remain
58
+ separable from, or merely link (or bind by name) to the interfaces of,
59
+ the Work and Derivative Works thereof.
60
+
61
+ "Contribution" shall mean any work of authorship, including
62
+ the original version of the Work and any modifications or additions
63
+ to that Work or Derivative Works thereof, that is intentionally
64
+ submitted to Licensor for inclusion in the Work by the copyright owner
65
+ or by an individual or Legal Entity authorized to submit on behalf of
66
+ the copyright owner. For the purposes of this definition, "submitted"
67
+ means any form of electronic, verbal, or written communication sent
68
+ to the Licensor or its representatives, including but not limited to
69
+ communication on electronic mailing lists, source code control systems,
70
+ and issue tracking systems that are managed by, or on behalf of, the
71
+ Licensor for the purpose of discussing and improving the Work, but
72
+ excluding communication that is conspicuously marked or otherwise
73
+ designated in writing by the copyright owner as "Not a Contribution."
74
+
75
+ "Contributor" shall mean Licensor and any individual or Legal Entity
76
+ on behalf of whom a Contribution has been received by Licensor and
77
+ subsequently incorporated within the Work.
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+ 3. Grant of Patent License. Subject to the terms and conditions of
87
+ this License, each Contributor hereby grants to You a perpetual,
88
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89
+ (except as stated in this section) patent license to make, have made,
90
+ use, offer to sell, sell, import, and otherwise transfer the Work,
91
+ where such license applies only to those patent claims licensable
92
+ by such Contributor that are necessarily infringed by their
93
+ Contribution(s) alone or by combination of their Contribution(s)
94
+ with the Work to which such Contribution(s) was submitted. If You
95
+ institute patent litigation against any entity (including a
96
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97
+ or a Contribution incorporated within the Work constitutes direct
98
+ or contributory patent infringement, then any patent licenses
99
+ granted to You under this License for that Work shall terminate
100
+ as of the date such litigation is filed.
101
+
102
+ 4. Redistribution. You may reproduce and distribute copies of the
103
+ Work or Derivative Works thereof in any medium, with or without
104
+ modifications, and in Source or Object form, provided that You
105
+ meet the following conditions:
106
+
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+
110
+ (b) You must cause any modified files to carry prominent notices
111
+ stating that You changed the files; and
112
+
113
+ (c) You must retain, in the Source form of any Derivative Works
114
+ that You distribute, all copyright, patent, trademark, and
115
+ attribution notices from the Source form of the Work,
116
+ excluding those notices that do not pertain to any part of
117
+ the Derivative Works; and
118
+
119
+ (d) If the Work includes a "NOTICE" text file as part of its
120
+ distribution, then any Derivative Works that You distribute must
121
+ include a readable copy of the attribution notices contained
122
+ within such NOTICE file, excluding those notices that do not
123
+ pertain to any part of the Derivative Works, in at least one
124
+ of the following places: within a NOTICE text file distributed
125
+ as part of the Derivative Works; within the Source form or
126
+ documentation, if provided along with the Derivative Works; or,
127
+ within a display generated by the Derivative Works, if and
128
+ wherever such third-party notices normally appear. The contents
129
+ of the NOTICE file are for informational purposes only and
130
+ do not modify the License. You may add Your own attribution
131
+ notices within Derivative Works that You distribute, alongside
132
+ or as an addendum to the NOTICE text from the Work, provided
133
+ that such additional attribution notices cannot be construed
134
+ as modifying the License.
135
+
136
+ You may add Your own copyright statement to Your modifications and
137
+ may provide additional or different license terms and conditions
138
+ for use, reproduction, or distribution of Your modifications, or
139
+ for any such Derivative Works as a whole, provided Your use,
140
+ reproduction, and distribution of the Work otherwise complies with
141
+ the conditions stated in this License.
142
+
143
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144
+ any Contribution intentionally submitted for inclusion in the Work
145
+ by You to the Licensor shall be under the terms and conditions of
146
+ this License, without any additional terms or conditions.
147
+ Notwithstanding the above, nothing herein shall supersede or modify
148
+ the terms of any separate license agreement you may have executed
149
+ with Licensor regarding such Contributions.
150
+
151
+ 6. Trademarks. This License does not grant permission to use the trade
152
+ names, trademarks, service marks, or product names of the Licensor,
153
+ except as required for reasonable and customary use in describing the
154
+ origin of the Work and reproducing the content of the NOTICE file.
155
+
156
+ 7. Disclaimer of Warranty. Unless required by applicable law or
157
+ agreed to in writing, Licensor provides the Work (and each
158
+ Contributor provides its Contributions) on an "AS IS" BASIS,
159
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160
+ implied, including, without limitation, any warranties or conditions
161
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162
+ PARTICULAR PURPOSE. You are solely responsible for determining the
163
+ appropriateness of using or redistributing the Work and assume any
164
+ risks associated with Your exercise of permissions under this License.
165
+
166
+ 8. Limitation of Liability. In no event and under no legal theory,
167
+ whether in tort (including negligence), contract, or otherwise,
168
+ unless required by applicable law (such as deliberate and grossly
169
+ negligent acts) or agreed to in writing, shall any Contributor be
170
+ liable to You for damages, including any direct, indirect, special,
171
+ incidental, or consequential damages of any character arising as a
172
+ result of this License or out of the use or inability to use the
173
+ Work (including but not limited to damages for loss of goodwill,
174
+ work stoppage, computer failure or malfunction, or any and all
175
+ other commercial damages or losses), even if such Contributor
176
+ has been advised of the possibility of such damages.
177
+
178
+ 9. Accepting Warranty or Additional Liability. While redistributing
179
+ the Work or Derivative Works thereof, You may choose to offer,
180
+ and charge a fee for, acceptance of support, warranty, indemnity,
181
+ or other liability obligations and/or rights consistent with this
182
+ License. However, in accepting such obligations, You may act only
183
+ on Your own behalf and on Your sole responsibility, not on behalf
184
+ of any other Contributor, and only if You agree to indemnify,
185
+ defend, and hold each Contributor harmless for any liability
186
+ incurred by, or claims asserted against, such Contributor by reason
187
+ of your accepting any such warranty or additional liability.
188
+
189
+ END OF TERMS AND CONDITIONS
190
+
191
+ APPENDIX: How to apply the Apache License to your work.
192
+
193
+ To apply the Apache License to your work, attach the following
194
+ boilerplate notice, with the fields enclosed by brackets "[]"
195
+ replaced with your own identifying information. (Don't include
196
+ the brackets!) The text should be enclosed in the appropriate
197
+ comment syntax for the file format. We also recommend that a
198
+ file or class name and description of purpose be included on the
199
+ same "printed page" as the copyright notice for easier
200
+ identification within third-party archives.
201
+
202
+ Copyright 2024-2025 DEFAI Private Limited
203
+
204
+ Licensed under the Apache License, Version 2.0 (the "License");
205
+ you may not use this file except in compliance with the License.
206
+ You may obtain a copy of the License at
207
+
208
+ http://www.apache.org/licenses/LICENSE-2.0
209
+
210
+ Unless required by applicable law or agreed to in writing, software
211
+ distributed under the License is distributed on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ See the License for the specific language governing permissions and
214
+ limitations under the License.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @defai.digital/context-domain
3
+ *
4
+ * Project context loading for AutomatosX.
5
+ * Loads project-specific conventions, architecture, and patterns
6
+ * from .automatosx/context/ for injection into agent prompts.
7
+ */
8
+ export type { ContextFile, ProjectContext, ContextLoaderConfig, ContextLoadResult, IContextLoader, FileInfo, } from './types.js';
9
+ export { ContextLoader, createContextLoader, hasProjectContext, loadProjectContext, } from './loader.js';
10
+ export { MAX_CONTEXT_FILE_SIZE, MAX_CONTEXT_TOTAL_SIZE, CONTEXT_DIRECTORY, ContextErrorCode, } from '@defai.digital/contracts';
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,YAAY,EACV,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,QAAQ,GACT,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAGrB,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,0BAA0B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @defai.digital/context-domain
3
+ *
4
+ * Project context loading for AutomatosX.
5
+ * Loads project-specific conventions, architecture, and patterns
6
+ * from .automatosx/context/ for injection into agent prompts.
7
+ */
8
+ // Loader
9
+ export { ContextLoader, createContextLoader, hasProjectContext, loadProjectContext, } from './loader.js';
10
+ // Re-export contract constants
11
+ export { MAX_CONTEXT_FILE_SIZE, MAX_CONTEXT_TOTAL_SIZE, CONTEXT_DIRECTORY, ContextErrorCode, } from '@defai.digital/contracts';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAYH,SAAS;AACT,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,iBAAiB,EACjB,kBAAkB,GACnB,MAAM,aAAa,CAAC;AAErB,+BAA+B;AAC/B,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,0BAA0B,CAAC"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Context Loader
3
+ *
4
+ * Loads project-specific context files from .automatosx/context/
5
+ * and prepares them for injection into agent system prompts.
6
+ *
7
+ * Invariants:
8
+ * - INV-CTX-001: Individual files must not exceed maxFileSize
9
+ * - INV-CTX-002: Total size must not exceed maxTotalSize
10
+ * - INV-CTX-003: Files must be valid UTF-8
11
+ */
12
+ import { type ContextLoaderConfig, type ContextLoadResult } from '@defai.digital/contracts';
13
+ import type { IContextLoader } from './types.js';
14
+ /**
15
+ * Loads project context from .automatosx/context/ directory
16
+ */
17
+ export declare class ContextLoader implements IContextLoader {
18
+ private config;
19
+ constructor(config?: Partial<ContextLoaderConfig>);
20
+ /**
21
+ * Get the context directory path for a project
22
+ */
23
+ getContextPath(projectPath: string): string;
24
+ /**
25
+ * Check if context directory exists
26
+ */
27
+ hasContext(projectPath: string): Promise<boolean>;
28
+ /**
29
+ * Load project context from a directory
30
+ */
31
+ load(projectPath: string): Promise<ContextLoadResult>;
32
+ /**
33
+ * List context files in directory
34
+ */
35
+ private listContextFiles;
36
+ /**
37
+ * Sort files based on configuration
38
+ */
39
+ private sortFiles;
40
+ /**
41
+ * Create combined content for system prompt injection
42
+ */
43
+ private createCombinedContent;
44
+ /**
45
+ * Create empty context when directory doesn't exist
46
+ */
47
+ private createEmptyContext;
48
+ }
49
+ /**
50
+ * Creates a context loader with optional configuration
51
+ */
52
+ export declare function createContextLoader(config?: Partial<ContextLoaderConfig>): IContextLoader;
53
+ /**
54
+ * Quick check if a project has context
55
+ */
56
+ export declare function hasProjectContext(projectPath: string): Promise<boolean>;
57
+ /**
58
+ * Load context with default settings
59
+ */
60
+ export declare function loadProjectContext(projectPath: string): Promise<ContextLoadResult>;
61
+ //# sourceMappingURL=loader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAOL,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,cAAc,EAAY,MAAM,YAAY,CAAC;AAmB3D;;GAEG;AACH,qBAAa,aAAc,YAAW,cAAc;IAClD,OAAO,CAAC,MAAM,CAAsB;gBAExB,MAAM,GAAE,OAAO,CAAC,mBAAmB,CAAM;IAIrD;;OAEG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM;IAI3C;;OAEG;IACG,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAUvD;;OAEG;IACG,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAiG3D;;OAEG;YACW,gBAAgB;IA8B9B;;OAEG;IACH,OAAO,CAAC,SAAS;IAcjB;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAW7B;;OAEG;IACH,OAAO,CAAC,kBAAkB;CAW3B;AAMD;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,GACpC,cAAc,CAEhB;AAMD;;GAEG;AACH,wBAAsB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAG7E;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CACtC,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,iBAAiB,CAAC,CAG5B"}
package/dist/loader.js ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Context Loader
3
+ *
4
+ * Loads project-specific context files from .automatosx/context/
5
+ * and prepares them for injection into agent system prompts.
6
+ *
7
+ * Invariants:
8
+ * - INV-CTX-001: Individual files must not exceed maxFileSize
9
+ * - INV-CTX-002: Total size must not exceed maxTotalSize
10
+ * - INV-CTX-003: Files must be valid UTF-8
11
+ */
12
+ import * as fs from 'node:fs/promises';
13
+ import * as path from 'node:path';
14
+ import { MAX_CONTEXT_FILE_SIZE, MAX_CONTEXT_TOTAL_SIZE, CONTEXT_DIRECTORY, DATA_DIR_NAME, } from '@defai.digital/contracts';
15
+ // ============================================================================
16
+ // Default Configuration
17
+ // ============================================================================
18
+ const DEFAULT_CONFIG = {
19
+ maxFileSize: MAX_CONTEXT_FILE_SIZE,
20
+ maxTotalSize: MAX_CONTEXT_TOTAL_SIZE,
21
+ fileExtensions: ['.md', '.txt'],
22
+ excludePatterns: [],
23
+ recursive: false,
24
+ sortBy: 'name',
25
+ };
26
+ // ============================================================================
27
+ // Context Loader Implementation
28
+ // ============================================================================
29
+ /**
30
+ * Loads project context from .automatosx/context/ directory
31
+ */
32
+ export class ContextLoader {
33
+ config;
34
+ constructor(config = {}) {
35
+ this.config = { ...DEFAULT_CONFIG, ...config };
36
+ }
37
+ /**
38
+ * Get the context directory path for a project
39
+ */
40
+ getContextPath(projectPath) {
41
+ return path.join(projectPath, DATA_DIR_NAME, CONTEXT_DIRECTORY);
42
+ }
43
+ /**
44
+ * Check if context directory exists
45
+ */
46
+ async hasContext(projectPath) {
47
+ const contextPath = this.getContextPath(projectPath);
48
+ try {
49
+ const stat = await fs.stat(contextPath);
50
+ return stat.isDirectory();
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Load project context from a directory
58
+ */
59
+ async load(projectPath) {
60
+ const contextPath = this.getContextPath(projectPath);
61
+ // Check if context directory exists
62
+ const exists = await this.hasContext(projectPath);
63
+ if (!exists) {
64
+ return {
65
+ success: true,
66
+ context: this.createEmptyContext(projectPath, contextPath),
67
+ filesLoaded: 0,
68
+ filesSkipped: 0,
69
+ };
70
+ }
71
+ try {
72
+ // List files in context directory
73
+ const fileInfos = await this.listContextFiles(contextPath);
74
+ // Load files with size limits
75
+ const loadedFiles = [];
76
+ const skippedReasons = [];
77
+ let totalSize = 0;
78
+ for (const fileInfo of fileInfos) {
79
+ // Check individual file size
80
+ if (fileInfo.size > this.config.maxFileSize) {
81
+ skippedReasons.push({
82
+ filename: fileInfo.name,
83
+ reason: `File exceeds max size (${fileInfo.size} > ${this.config.maxFileSize})`,
84
+ });
85
+ continue;
86
+ }
87
+ // Check total size limit
88
+ if (totalSize + fileInfo.size > this.config.maxTotalSize) {
89
+ skippedReasons.push({
90
+ filename: fileInfo.name,
91
+ reason: `Would exceed total size limit`,
92
+ });
93
+ continue;
94
+ }
95
+ // Load file content
96
+ try {
97
+ const content = await fs.readFile(fileInfo.path, 'utf-8');
98
+ const now = new Date().toISOString();
99
+ loadedFiles.push({
100
+ filename: fileInfo.name,
101
+ relativePath: path.relative(contextPath, fileInfo.path),
102
+ content,
103
+ size: fileInfo.size,
104
+ loadedAt: now,
105
+ });
106
+ totalSize += fileInfo.size;
107
+ }
108
+ catch (error) {
109
+ skippedReasons.push({
110
+ filename: fileInfo.name,
111
+ reason: `Read error: ${error instanceof Error ? error.message : 'Unknown'}`,
112
+ });
113
+ }
114
+ }
115
+ // Sort files
116
+ this.sortFiles(loadedFiles);
117
+ // Create combined content
118
+ const combinedContent = this.createCombinedContent(loadedFiles);
119
+ const context = {
120
+ projectPath,
121
+ contextPath,
122
+ files: loadedFiles,
123
+ totalSize,
124
+ fileCount: loadedFiles.length,
125
+ loadedAt: new Date().toISOString(),
126
+ combinedContent,
127
+ };
128
+ return {
129
+ success: true,
130
+ context,
131
+ filesLoaded: loadedFiles.length,
132
+ filesSkipped: skippedReasons.length,
133
+ skippedReasons: skippedReasons.length > 0 ? skippedReasons : undefined,
134
+ };
135
+ }
136
+ catch (error) {
137
+ return {
138
+ success: false,
139
+ error: `Failed to load context: ${error instanceof Error ? error.message : 'Unknown'}`,
140
+ filesLoaded: 0,
141
+ filesSkipped: 0,
142
+ };
143
+ }
144
+ }
145
+ /**
146
+ * List context files in directory
147
+ */
148
+ async listContextFiles(contextPath) {
149
+ const files = [];
150
+ const entries = await fs.readdir(contextPath, { withFileTypes: true });
151
+ for (const entry of entries) {
152
+ if (!entry.isFile())
153
+ continue;
154
+ // Check file extension
155
+ const ext = path.extname(entry.name).toLowerCase();
156
+ if (!this.config.fileExtensions.includes(ext))
157
+ continue;
158
+ // Check exclude patterns
159
+ const excluded = this.config.excludePatterns.some((pattern) => entry.name.includes(pattern));
160
+ if (excluded)
161
+ continue;
162
+ const filePath = path.join(contextPath, entry.name);
163
+ const stat = await fs.stat(filePath);
164
+ files.push({
165
+ path: filePath,
166
+ name: entry.name,
167
+ size: stat.size,
168
+ });
169
+ }
170
+ return files;
171
+ }
172
+ /**
173
+ * Sort files based on configuration
174
+ */
175
+ sortFiles(files) {
176
+ switch (this.config.sortBy) {
177
+ case 'name':
178
+ files.sort((a, b) => a.filename.localeCompare(b.filename));
179
+ break;
180
+ case 'size':
181
+ files.sort((a, b) => a.size - b.size);
182
+ break;
183
+ // 'modified' would require storing modification time
184
+ default:
185
+ files.sort((a, b) => a.filename.localeCompare(b.filename));
186
+ }
187
+ }
188
+ /**
189
+ * Create combined content for system prompt injection
190
+ */
191
+ createCombinedContent(files) {
192
+ if (files.length === 0)
193
+ return '';
194
+ const sections = files.map((file) => {
195
+ const header = `## ${file.filename}`;
196
+ return `${header}\n\n${file.content}`;
197
+ });
198
+ return `# Project Context\n\n${sections.join('\n\n---\n\n')}`;
199
+ }
200
+ /**
201
+ * Create empty context when directory doesn't exist
202
+ */
203
+ createEmptyContext(projectPath, contextPath) {
204
+ return {
205
+ projectPath,
206
+ contextPath,
207
+ files: [],
208
+ totalSize: 0,
209
+ fileCount: 0,
210
+ loadedAt: new Date().toISOString(),
211
+ combinedContent: '',
212
+ };
213
+ }
214
+ }
215
+ // ============================================================================
216
+ // Factory Function
217
+ // ============================================================================
218
+ /**
219
+ * Creates a context loader with optional configuration
220
+ */
221
+ export function createContextLoader(config) {
222
+ return new ContextLoader(config);
223
+ }
224
+ // ============================================================================
225
+ // Utility Functions
226
+ // ============================================================================
227
+ /**
228
+ * Quick check if a project has context
229
+ */
230
+ export async function hasProjectContext(projectPath) {
231
+ const loader = new ContextLoader();
232
+ return loader.hasContext(projectPath);
233
+ }
234
+ /**
235
+ * Load context with default settings
236
+ */
237
+ export async function loadProjectContext(projectPath) {
238
+ const loader = new ContextLoader();
239
+ return loader.load(projectPath);
240
+ }
241
+ //# sourceMappingURL=loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,aAAa,GAKd,MAAM,0BAA0B,CAAC;AAGlC,+EAA+E;AAC/E,wBAAwB;AACxB,+EAA+E;AAE/E,MAAM,cAAc,GAAwB;IAC1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mB,CACjC,MAAqC;IAErC,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC;AAED,+EAA+E;AAC/E,oBAAoB;AACpB,+EAA+E;AAE/E;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,WAAmB;IACzD,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IACnC,OAAO,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;AACxC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,WAAmB;IAEnB,MAAM,MAAM,GAAG,IAAI,aAAa,EAAE,CAAC;IACnC,OAAO,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAClC,CAAC"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Context Domain Internal Types
3
+ *
4
+ * Internal types for the context loader implementation.
5
+ */
6
+ import type { ContextFile, ProjectContext, ContextLoaderConfig, ContextLoadResult } from '@defai.digital/contracts';
7
+ export type { ContextFile, ProjectContext, ContextLoaderConfig, ContextLoadResult, };
8
+ /**
9
+ * Context loader interface
10
+ */
11
+ export interface IContextLoader {
12
+ /**
13
+ * Load project context from a directory
14
+ */
15
+ load(projectPath: string): Promise<ContextLoadResult>;
16
+ /**
17
+ * Get the context directory path for a project
18
+ */
19
+ getContextPath(projectPath: string): string;
20
+ /**
21
+ * Check if context directory exists
22
+ */
23
+ hasContext(projectPath: string): Promise<boolean>;
24
+ }
25
+ /**
26
+ * Context file reader options
27
+ */
28
+ export interface ContextFileReaderOptions {
29
+ maxFileSize: number;
30
+ encoding: BufferEncoding;
31
+ }
32
+ /**
33
+ * Internal file info
34
+ */
35
+ export interface FileInfo {
36
+ path: string;
37
+ name: string;
38
+ size: number;
39
+ }
40
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AAGlC,YAAY,EACV,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,iBAAiB,GAClB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,IAAI,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAEtD;;OAEG;IACH,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IAE5C;;OAEG;IACH,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACnD;AAED;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,cAAc,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd"}
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Context Domain Internal Types
3
+ *
4
+ * Internal types for the context loader implementation.
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@defai.digital/context-domain",
3
+ "version": "13.0.3",
4
+ "type": "module",
5
+ "description": "Project context loading for AutomatosX - inject project-specific conventions into agent prompts",
6
+ "license": "Apache-2.0",
7
+ "author": "DEFAI Private Limited",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/defai-digital/automatosx.git",
11
+ "directory": "packages/core/context-domain"
12
+ },
13
+ "homepage": "https://github.com/defai-digital/automatosx#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/defai-digital/automatosx/issues"
16
+ },
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20.0.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@defai.digital/contracts": "13.0.3"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.7.2"
40
+ },
41
+ "peerDependencies": {
42
+ "zod": "^3.23.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc --build",
46
+ "clean": "rm -rf dist"
47
+ }
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @defai.digital/context-domain
3
+ *
4
+ * Project context loading for AutomatosX.
5
+ * Loads project-specific conventions, architecture, and patterns
6
+ * from .automatosx/context/ for injection into agent prompts.
7
+ */
8
+
9
+ // Types
10
+ export type {
11
+ ContextFile,
12
+ ProjectContext,
13
+ ContextLoaderConfig,
14
+ ContextLoadResult,
15
+ IContextLoader,
16
+ FileInfo,
17
+ } from './types.js';
18
+
19
+ // Loader
20
+ export {
21
+ ContextLoader,
22
+ createContextLoader,
23
+ hasProjectContext,
24
+ loadProjectContext,
25
+ } from './loader.js';
26
+
27
+ // Re-export contract constants
28
+ export {
29
+ MAX_CONTEXT_FILE_SIZE,
30
+ MAX_CONTEXT_TOTAL_SIZE,
31
+ CONTEXT_DIRECTORY,
32
+ ContextErrorCode,
33
+ } from '@defai.digital/contracts';
package/src/loader.ts ADDED
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Context Loader
3
+ *
4
+ * Loads project-specific context files from .automatosx/context/
5
+ * and prepares them for injection into agent system prompts.
6
+ *
7
+ * Invariants:
8
+ * - INV-CTX-001: Individual files must not exceed maxFileSize
9
+ * - INV-CTX-002: Total size must not exceed maxTotalSize
10
+ * - INV-CTX-003: Files must be valid UTF-8
11
+ */
12
+
13
+ import * as fs from 'node:fs/promises';
14
+ import * as path from 'node:path';
15
+ import {
16
+ MAX_CONTEXT_FILE_SIZE,
17
+ MAX_CONTEXT_TOTAL_SIZE,
18
+ CONTEXT_DIRECTORY,
19
+ DATA_DIR_NAME,
20
+ type ContextFile,
21
+ type ProjectContext,
22
+ type ContextLoaderConfig,
23
+ type ContextLoadResult,
24
+ } from '@defai.digital/contracts';
25
+ import type { IContextLoader, FileInfo } from './types.js';
26
+
27
+ // ============================================================================
28
+ // Default Configuration
29
+ // ============================================================================
30
+
31
+ const DEFAULT_CONFIG: ContextLoaderConfig = {
32
+ maxFileSize: MAX_CONTEXT_FILE_SIZE,
33
+ maxTotalSize: MAX_CONTEXT_TOTAL_SIZE,
34
+ fileExtensions: ['.md', '.txt'],
35
+ excludePatterns: [],
36
+ recursive: false,
37
+ sortBy: 'name',
38
+ };
39
+
40
+ // ============================================================================
41
+ // Context Loader Implementation
42
+ // ============================================================================
43
+
44
+ /**
45
+ * Loads project context from .automatosx/context/ directory
46
+ */
47
+ export class ContextLoader implements IContextLoader {
48
+ private config: ContextLoaderConfig;
49
+
50
+ constructor(config: Partial<ContextLoaderConfig> = {}) {
51
+ this.config = { ...DEFAULT_CONFIG, ...config };
52
+ }
53
+
54
+ /**
55
+ * Get the context directory path for a project
56
+ */
57
+ getContextPath(projectPath: string): string {
58
+ return path.join(projectPath, DATA_DIR_NAME, CONTEXT_DIRECTORY);
59
+ }
60
+
61
+ /**
62
+ * Check if context directory exists
63
+ */
64
+ async hasContext(projectPath: string): Promise<boolean> {
65
+ const contextPath = this.getContextPath(projectPath);
66
+ try {
67
+ const stat = await fs.stat(contextPath);
68
+ return stat.isDirectory();
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Load project context from a directory
76
+ */
77
+ async load(projectPath: string): Promise<ContextLoadResult> {
78
+ const contextPath = this.getContextPath(projectPath);
79
+
80
+ // Check if context directory exists
81
+ const exists = await this.hasContext(projectPath);
82
+ if (!exists) {
83
+ return {
84
+ success: true,
85
+ context: this.createEmptyContext(projectPath, contextPath),
86
+ filesLoaded: 0,
87
+ filesSkipped: 0,
88
+ };
89
+ }
90
+
91
+ try {
92
+ // List files in context directory
93
+ const fileInfos = await this.listContextFiles(contextPath);
94
+
95
+ // Load files with size limits
96
+ const loadedFiles: ContextFile[] = [];
97
+ const skippedReasons: { filename: string; reason: string }[] = [];
98
+ let totalSize = 0;
99
+
100
+ for (const fileInfo of fileInfos) {
101
+ // Check individual file size
102
+ if (fileInfo.size > this.config.maxFileSize) {
103
+ skippedReasons.push({
104
+ filename: fileInfo.name,
105
+ reason: `File exceeds max size (${fileInfo.size} > ${this.config.maxFileSize})`,
106
+ });
107
+ continue;
108
+ }
109
+
110
+ // Check total size limit
111
+ if (totalSize + fileInfo.size > this.config.maxTotalSize) {
112
+ skippedReasons.push({
113
+ filename: fileInfo.name,
114
+ reason: `Would exceed total size limit`,
115
+ });
116
+ continue;
117
+ }
118
+
119
+ // Load file content
120
+ try {
121
+ const content = await fs.readFile(fileInfo.path, 'utf-8');
122
+ const now = new Date().toISOString();
123
+
124
+ loadedFiles.push({
125
+ filename: fileInfo.name,
126
+ relativePath: path.relative(contextPath, fileInfo.path),
127
+ content,
128
+ size: fileInfo.size,
129
+ loadedAt: now,
130
+ });
131
+
132
+ totalSize += fileInfo.size;
133
+ } catch (error) {
134
+ skippedReasons.push({
135
+ filename: fileInfo.name,
136
+ reason: `Read error: ${error instanceof Error ? error.message : 'Unknown'}`,
137
+ });
138
+ }
139
+ }
140
+
141
+ // Sort files
142
+ this.sortFiles(loadedFiles);
143
+
144
+ // Create combined content
145
+ const combinedContent = this.createCombinedContent(loadedFiles);
146
+
147
+ const context: ProjectContext = {
148
+ projectPath,
149
+ contextPath,
150
+ files: loadedFiles,
151
+ totalSize,
152
+ fileCount: loadedFiles.length,
153
+ loadedAt: new Date().toISOString(),
154
+ combinedContent,
155
+ };
156
+
157
+ return {
158
+ success: true,
159
+ context,
160
+ filesLoaded: loadedFiles.length,
161
+ filesSkipped: skippedReasons.length,
162
+ skippedReasons: skippedReasons.length > 0 ? skippedReasons : undefined,
163
+ };
164
+ } catch (error) {
165
+ return {
166
+ success: false,
167
+ error: `Failed to load context: ${error instanceof Error ? error.message : 'Unknown'}`,
168
+ filesLoaded: 0,
169
+ filesSkipped: 0,
170
+ };
171
+ }
172
+ }
173
+
174
+ /**
175
+ * List context files in directory
176
+ */
177
+ private async listContextFiles(contextPath: string): Promise<FileInfo[]> {
178
+ const files: FileInfo[] = [];
179
+ const entries = await fs.readdir(contextPath, { withFileTypes: true });
180
+
181
+ for (const entry of entries) {
182
+ if (!entry.isFile()) continue;
183
+
184
+ // Check file extension
185
+ const ext = path.extname(entry.name).toLowerCase();
186
+ if (!this.config.fileExtensions.includes(ext)) continue;
187
+
188
+ // Check exclude patterns
189
+ const excluded = this.config.excludePatterns.some((pattern) =>
190
+ entry.name.includes(pattern)
191
+ );
192
+ if (excluded) continue;
193
+
194
+ const filePath = path.join(contextPath, entry.name);
195
+ const stat = await fs.stat(filePath);
196
+
197
+ files.push({
198
+ path: filePath,
199
+ name: entry.name,
200
+ size: stat.size,
201
+ });
202
+ }
203
+
204
+ return files;
205
+ }
206
+
207
+ /**
208
+ * Sort files based on configuration
209
+ */
210
+ private sortFiles(files: ContextFile[]): void {
211
+ switch (this.config.sortBy) {
212
+ case 'name':
213
+ files.sort((a, b) => a.filename.localeCompare(b.filename));
214
+ break;
215
+ case 'size':
216
+ files.sort((a, b) => a.size - b.size);
217
+ break;
218
+ // 'modified' would require storing modification time
219
+ default:
220
+ files.sort((a, b) => a.filename.localeCompare(b.filename));
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Create combined content for system prompt injection
226
+ */
227
+ private createCombinedContent(files: ContextFile[]): string {
228
+ if (files.length === 0) return '';
229
+
230
+ const sections = files.map((file) => {
231
+ const header = `## ${file.filename}`;
232
+ return `${header}\n\n${file.content}`;
233
+ });
234
+
235
+ return `# Project Context\n\n${sections.join('\n\n---\n\n')}`;
236
+ }
237
+
238
+ /**
239
+ * Create empty context when directory doesn't exist
240
+ */
241
+ private createEmptyContext(projectPath: string, contextPath: string): ProjectContext {
242
+ return {
243
+ projectPath,
244
+ contextPath,
245
+ files: [],
246
+ totalSize: 0,
247
+ fileCount: 0,
248
+ loadedAt: new Date().toISOString(),
249
+ combinedContent: '',
250
+ };
251
+ }
252
+ }
253
+
254
+ // ============================================================================
255
+ // Factory Function
256
+ // ============================================================================
257
+
258
+ /**
259
+ * Creates a context loader with optional configuration
260
+ */
261
+ export function createContextLoader(
262
+ config?: Partial<ContextLoaderConfig>
263
+ ): IContextLoader {
264
+ return new ContextLoader(config);
265
+ }
266
+
267
+ // ============================================================================
268
+ // Utility Functions
269
+ // ============================================================================
270
+
271
+ /**
272
+ * Quick check if a project has context
273
+ */
274
+ export async function hasProjectContext(projectPath: string): Promise<boolean> {
275
+ const loader = new ContextLoader();
276
+ return loader.hasContext(projectPath);
277
+ }
278
+
279
+ /**
280
+ * Load context with default settings
281
+ */
282
+ export async function loadProjectContext(
283
+ projectPath: string
284
+ ): Promise<ContextLoadResult> {
285
+ const loader = new ContextLoader();
286
+ return loader.load(projectPath);
287
+ }
package/src/types.ts ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Context Domain Internal Types
3
+ *
4
+ * Internal types for the context loader implementation.
5
+ */
6
+
7
+ import type {
8
+ ContextFile,
9
+ ProjectContext,
10
+ ContextLoaderConfig,
11
+ ContextLoadResult,
12
+ } from '@defai.digital/contracts';
13
+
14
+ // Re-export contract types for convenience
15
+ export type {
16
+ ContextFile,
17
+ ProjectContext,
18
+ ContextLoaderConfig,
19
+ ContextLoadResult,
20
+ };
21
+
22
+ /**
23
+ * Context loader interface
24
+ */
25
+ export interface IContextLoader {
26
+ /**
27
+ * Load project context from a directory
28
+ */
29
+ load(projectPath: string): Promise<ContextLoadResult>;
30
+
31
+ /**
32
+ * Get the context directory path for a project
33
+ */
34
+ getContextPath(projectPath: string): string;
35
+
36
+ /**
37
+ * Check if context directory exists
38
+ */
39
+ hasContext(projectPath: string): Promise<boolean>;
40
+ }
41
+
42
+ /**
43
+ * Context file reader options
44
+ */
45
+ export interface ContextFileReaderOptions {
46
+ maxFileSize: number;
47
+ encoding: BufferEncoding;
48
+ }
49
+
50
+ /**
51
+ * Internal file info
52
+ */
53
+ export interface FileInfo {
54
+ path: string;
55
+ name: string;
56
+ size: number;
57
+ }