@deimoscloud/coreai 0.1.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.
Files changed (216) hide show
  1. package/.prettierrc +9 -0
  2. package/AGENT_SPEC.md +347 -0
  3. package/ARCHITECTURE.md +547 -0
  4. package/DRAFT_PRD.md +1440 -0
  5. package/IMPLEMENTATION_PLAN.md +256 -0
  6. package/PRODUCT.md +473 -0
  7. package/README.md +303 -0
  8. package/WORKFLOWS.md +295 -0
  9. package/agents/_templates/ic-engineer.md +185 -0
  10. package/agents/_templates/reviewer.md +182 -0
  11. package/agents/backend-engineer.yaml +72 -0
  12. package/agents/devops-engineer.yaml +72 -0
  13. package/agents/engineering-manager.yaml +70 -0
  14. package/agents/examples/android-engineer.md +302 -0
  15. package/agents/examples/backend-engineer.md +320 -0
  16. package/agents/examples/devops-engineer.md +742 -0
  17. package/agents/examples/engineering-manager.md +469 -0
  18. package/agents/examples/frontend-engineer.md +58 -0
  19. package/agents/examples/product-manager.md +315 -0
  20. package/agents/examples/qa-engineer.md +371 -0
  21. package/agents/examples/security-engineer.md +525 -0
  22. package/agents/examples/solutions-architect.md +351 -0
  23. package/agents/examples/wearos-engineer.md +359 -0
  24. package/agents/frontend-engineer.yaml +72 -0
  25. package/commands/core/check-inbox.md +34 -0
  26. package/commands/core/delegate.md +30 -0
  27. package/commands/core/git-commit.md +144 -0
  28. package/commands/core/pr-create.md +193 -0
  29. package/commands/core/review.md +56 -0
  30. package/commands/core/sprint-status.md +65 -0
  31. package/commands/optional/docs-update.md +200 -0
  32. package/commands/optional/jira-create.md +200 -0
  33. package/commands/optional/jira-transition.md +184 -0
  34. package/commands/optional/worktree-cleanup.md +167 -0
  35. package/commands/optional/worktree-setup.md +110 -0
  36. package/dist/cli/index.js +4037 -0
  37. package/dist/cli/index.js.map +1 -0
  38. package/dist/index.d.ts +2978 -0
  39. package/dist/index.js +3867 -0
  40. package/dist/index.js.map +1 -0
  41. package/eslint.config.js +29 -0
  42. package/jest.config.js +22 -0
  43. package/knowledge-library/README.md +118 -0
  44. package/knowledge-library/android-engineer/context/current.txt +42 -0
  45. package/knowledge-library/android-engineer/control/decisions.txt +9 -0
  46. package/knowledge-library/android-engineer/control/dependencies.txt +19 -0
  47. package/knowledge-library/android-engineer/control/objectives.txt +26 -0
  48. package/knowledge-library/android-engineer/history/.gitkeep +0 -0
  49. package/knowledge-library/android-engineer/inbox/processed/.gitkeep +0 -0
  50. package/knowledge-library/android-engineer/outbox/.gitkeep +0 -0
  51. package/knowledge-library/android-engineer/tech/.gitkeep +0 -0
  52. package/knowledge-library/architecture.txt +61 -0
  53. package/knowledge-library/backend-engineer/context/current.txt +42 -0
  54. package/knowledge-library/backend-engineer/control/decisions.txt +9 -0
  55. package/knowledge-library/backend-engineer/control/dependencies.txt +19 -0
  56. package/knowledge-library/backend-engineer/control/objectives.txt +26 -0
  57. package/knowledge-library/backend-engineer/history/.gitkeep +0 -0
  58. package/knowledge-library/backend-engineer/inbox/processed/.gitkeep +0 -0
  59. package/knowledge-library/backend-engineer/outbox/.gitkeep +0 -0
  60. package/knowledge-library/backend-engineer/tech/.gitkeep +0 -0
  61. package/knowledge-library/context.txt +52 -0
  62. package/knowledge-library/devops-engineer/context/current.txt +42 -0
  63. package/knowledge-library/devops-engineer/control/decisions.txt +9 -0
  64. package/knowledge-library/devops-engineer/control/dependencies.txt +19 -0
  65. package/knowledge-library/devops-engineer/control/objectives.txt +26 -0
  66. package/knowledge-library/devops-engineer/history/.gitkeep +0 -0
  67. package/knowledge-library/devops-engineer/inbox/processed/.gitkeep +0 -0
  68. package/knowledge-library/devops-engineer/outbox/.gitkeep +0 -0
  69. package/knowledge-library/devops-engineer/tech/.gitkeep +0 -0
  70. package/knowledge-library/engineering-manager/context/current.txt +40 -0
  71. package/knowledge-library/engineering-manager/control/decisions.txt +9 -0
  72. package/knowledge-library/engineering-manager/control/objectives.txt +27 -0
  73. package/knowledge-library/engineering-manager/history/.gitkeep +0 -0
  74. package/knowledge-library/engineering-manager/inbox/processed/.gitkeep +0 -0
  75. package/knowledge-library/engineering-manager/outbox/.gitkeep +0 -0
  76. package/knowledge-library/engineering-manager/tech/.gitkeep +0 -0
  77. package/knowledge-library/prd.txt +81 -0
  78. package/knowledge-library/product-manager/context/current.txt +42 -0
  79. package/knowledge-library/product-manager/control/decisions.txt +9 -0
  80. package/knowledge-library/product-manager/control/dependencies.txt +19 -0
  81. package/knowledge-library/product-manager/control/objectives.txt +26 -0
  82. package/knowledge-library/product-manager/history/.gitkeep +0 -0
  83. package/knowledge-library/product-manager/inbox/processed/.gitkeep +0 -0
  84. package/knowledge-library/product-manager/outbox/.gitkeep +0 -0
  85. package/knowledge-library/product-manager/tech/.gitkeep +0 -0
  86. package/knowledge-library/qa-engineer/context/current.txt +42 -0
  87. package/knowledge-library/qa-engineer/control/decisions.txt +9 -0
  88. package/knowledge-library/qa-engineer/control/dependencies.txt +19 -0
  89. package/knowledge-library/qa-engineer/control/objectives.txt +26 -0
  90. package/knowledge-library/qa-engineer/history/.gitkeep +0 -0
  91. package/knowledge-library/qa-engineer/inbox/processed/.gitkeep +0 -0
  92. package/knowledge-library/qa-engineer/outbox/.gitkeep +0 -0
  93. package/knowledge-library/qa-engineer/tech/.gitkeep +0 -0
  94. package/knowledge-library/security-engineer/context/current.txt +42 -0
  95. package/knowledge-library/security-engineer/control/decisions.txt +9 -0
  96. package/knowledge-library/security-engineer/control/dependencies.txt +19 -0
  97. package/knowledge-library/security-engineer/control/objectives.txt +26 -0
  98. package/knowledge-library/security-engineer/history/.gitkeep +0 -0
  99. package/knowledge-library/security-engineer/inbox/processed/.gitkeep +0 -0
  100. package/knowledge-library/security-engineer/outbox/.gitkeep +0 -0
  101. package/knowledge-library/security-engineer/tech/.gitkeep +0 -0
  102. package/knowledge-library/solutions-architect/context/current.txt +42 -0
  103. package/knowledge-library/solutions-architect/control/decisions.txt +9 -0
  104. package/knowledge-library/solutions-architect/control/dependencies.txt +19 -0
  105. package/knowledge-library/solutions-architect/control/objectives.txt +26 -0
  106. package/knowledge-library/solutions-architect/history/.gitkeep +0 -0
  107. package/knowledge-library/solutions-architect/inbox/processed/.gitkeep +0 -0
  108. package/knowledge-library/solutions-architect/outbox/.gitkeep +0 -0
  109. package/knowledge-library/solutions-architect/tech/.gitkeep +0 -0
  110. package/knowledge-library/wearos-engineer/context/current.txt +42 -0
  111. package/knowledge-library/wearos-engineer/control/decisions.txt +9 -0
  112. package/knowledge-library/wearos-engineer/control/dependencies.txt +19 -0
  113. package/knowledge-library/wearos-engineer/control/objectives.txt +26 -0
  114. package/knowledge-library/wearos-engineer/history/.gitkeep +0 -0
  115. package/knowledge-library/wearos-engineer/inbox/processed/.gitkeep +0 -0
  116. package/knowledge-library/wearos-engineer/outbox/.gitkeep +0 -0
  117. package/knowledge-library/wearos-engineer/tech/.gitkeep +0 -0
  118. package/package.json +66 -0
  119. package/schemas/agent.schema.json +171 -0
  120. package/schemas/coreai.config.schema.json +257 -0
  121. package/scripts/add-agent.sh +323 -0
  122. package/scripts/install.sh +354 -0
  123. package/src/adapters/factory.test.ts +386 -0
  124. package/src/adapters/factory.ts +305 -0
  125. package/src/adapters/index.ts +113 -0
  126. package/src/adapters/interfaces.ts +268 -0
  127. package/src/adapters/mcp/client.test.ts +130 -0
  128. package/src/adapters/mcp/client.ts +451 -0
  129. package/src/adapters/mcp/discovery.test.ts +315 -0
  130. package/src/adapters/mcp/discovery.ts +340 -0
  131. package/src/adapters/mcp/index.ts +66 -0
  132. package/src/adapters/mcp/mapper.test.ts +218 -0
  133. package/src/adapters/mcp/mapper.ts +536 -0
  134. package/src/adapters/mcp/registry.test.ts +433 -0
  135. package/src/adapters/mcp/registry.ts +550 -0
  136. package/src/adapters/mcp/types.ts +258 -0
  137. package/src/adapters/native/filesystem.test.ts +350 -0
  138. package/src/adapters/native/filesystem.ts +393 -0
  139. package/src/adapters/native/github.test.ts +173 -0
  140. package/src/adapters/native/github.ts +627 -0
  141. package/src/adapters/native/index.ts +22 -0
  142. package/src/adapters/native/selector.test.ts +224 -0
  143. package/src/adapters/native/selector.ts +150 -0
  144. package/src/adapters/types.ts +270 -0
  145. package/src/agents/compiler.test.ts +399 -0
  146. package/src/agents/compiler.ts +359 -0
  147. package/src/agents/index.ts +36 -0
  148. package/src/agents/loader.test.ts +319 -0
  149. package/src/agents/loader.ts +143 -0
  150. package/src/agents/resolver.test.ts +282 -0
  151. package/src/agents/resolver.ts +262 -0
  152. package/src/agents/types.ts +87 -0
  153. package/src/cache/index.ts +38 -0
  154. package/src/cache/interfaces.ts +283 -0
  155. package/src/cache/manager.test.ts +266 -0
  156. package/src/cache/manager.ts +388 -0
  157. package/src/cache/provider.test.ts +485 -0
  158. package/src/cache/provider.ts +745 -0
  159. package/src/cache/types.test.ts +192 -0
  160. package/src/cache/types.ts +313 -0
  161. package/src/cli/commands/build.test.ts +248 -0
  162. package/src/cli/commands/build.ts +244 -0
  163. package/src/cli/commands/cache.test.ts +221 -0
  164. package/src/cli/commands/cache.ts +229 -0
  165. package/src/cli/commands/index.ts +63 -0
  166. package/src/cli/commands/init.test.ts +173 -0
  167. package/src/cli/commands/init.ts +296 -0
  168. package/src/cli/commands/skills.test.ts +272 -0
  169. package/src/cli/commands/skills.ts +348 -0
  170. package/src/cli/commands/status.test.ts +392 -0
  171. package/src/cli/commands/status.ts +332 -0
  172. package/src/cli/commands/sync.test.ts +213 -0
  173. package/src/cli/commands/sync.ts +251 -0
  174. package/src/cli/commands/validate.test.ts +216 -0
  175. package/src/cli/commands/validate.ts +340 -0
  176. package/src/cli/index.test.ts +190 -0
  177. package/src/cli/index.ts +493 -0
  178. package/src/commands/context.test.ts +163 -0
  179. package/src/commands/context.ts +111 -0
  180. package/src/commands/index.ts +56 -0
  181. package/src/commands/loader.test.ts +273 -0
  182. package/src/commands/loader.ts +355 -0
  183. package/src/commands/registry.test.ts +384 -0
  184. package/src/commands/registry.ts +248 -0
  185. package/src/commands/runner.test.ts +297 -0
  186. package/src/commands/runner.ts +222 -0
  187. package/src/commands/types.ts +361 -0
  188. package/src/config/index.ts +19 -0
  189. package/src/config/loader.test.ts +262 -0
  190. package/src/config/loader.ts +188 -0
  191. package/src/config/types.ts +154 -0
  192. package/src/context/index.ts +14 -0
  193. package/src/context/loader.test.ts +334 -0
  194. package/src/context/loader.ts +357 -0
  195. package/src/index.test.ts +13 -0
  196. package/src/index.ts +244 -0
  197. package/src/knowledge-library/index.ts +44 -0
  198. package/src/knowledge-library/manager.test.ts +536 -0
  199. package/src/knowledge-library/manager.ts +804 -0
  200. package/src/knowledge-library/types.ts +432 -0
  201. package/src/skills/generator.test.ts +602 -0
  202. package/src/skills/generator.ts +491 -0
  203. package/src/skills/index.ts +27 -0
  204. package/src/skills/templates.ts +520 -0
  205. package/src/skills/types.ts +251 -0
  206. package/templates/completion-report.md +72 -0
  207. package/templates/feedback.md +56 -0
  208. package/templates/project-files/CLAUDE.md.template +109 -0
  209. package/templates/project-files/coreai.json.example +47 -0
  210. package/templates/project-files/mcp.json.template +20 -0
  211. package/templates/review-complete.md +64 -0
  212. package/templates/review-request.md +67 -0
  213. package/templates/task-assignment.md +51 -0
  214. package/tsconfig.build.json +4 -0
  215. package/tsconfig.json +26 -0
  216. package/tsup.config.ts +23 -0
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Agent Loader
3
+ *
4
+ * Handles loading and validating agent YAML definitions.
5
+ */
6
+
7
+ import { existsSync, readdirSync, readFileSync } from 'fs';
8
+ import { basename, extname, join } from 'path';
9
+ import { parse as parseYaml } from 'yaml';
10
+ import Ajv, { type ErrorObject } from 'ajv';
11
+ import type { AgentDefinition, AgentMetadata, AgentSource } from './types.js';
12
+
13
+ // Import schema as JSON
14
+ import { createRequire } from 'module';
15
+ const require = createRequire(import.meta.url);
16
+ const agentSchema = require('../../schemas/agent.schema.json') as object;
17
+
18
+ export class AgentError extends Error {
19
+ constructor(
20
+ message: string,
21
+ public readonly code: AgentErrorCode,
22
+ public readonly details?: unknown
23
+ ) {
24
+ super(message);
25
+ this.name = 'AgentError';
26
+ }
27
+ }
28
+
29
+ export type AgentErrorCode = 'NOT_FOUND' | 'PARSE_ERROR' | 'VALIDATION_ERROR' | 'READ_ERROR';
30
+
31
+ /**
32
+ * Parse YAML content into an agent definition
33
+ */
34
+ export function parseAgentYaml(content: string, filePath?: string): unknown {
35
+ try {
36
+ return parseYaml(content);
37
+ } catch (error) {
38
+ const message = error instanceof Error ? error.message : 'Unknown parse error';
39
+ throw new AgentError(
40
+ `Failed to parse agent YAML${filePath ? ` in ${filePath}` : ''}: ${message}`,
41
+ 'PARSE_ERROR',
42
+ error
43
+ );
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Validate parsed YAML against agent schema
49
+ */
50
+ export function validateAgentDefinition(agent: unknown): AgentDefinition {
51
+ const ajv = new Ajv.default({ allErrors: true, strict: false });
52
+ const validate = ajv.compile<AgentDefinition>(agentSchema);
53
+ const valid = validate(agent);
54
+
55
+ if (!valid) {
56
+ const errors: ErrorObject[] = validate.errors ?? [];
57
+ const errorMessages = errors.map((err: ErrorObject) => {
58
+ const path = err.instancePath || 'root';
59
+ return `${path}: ${err.message ?? 'unknown error'}`;
60
+ });
61
+
62
+ throw new AgentError(
63
+ `Agent validation failed:\n - ${errorMessages.join('\n - ')}`,
64
+ 'VALIDATION_ERROR',
65
+ errors
66
+ );
67
+ }
68
+
69
+ return agent as AgentDefinition;
70
+ }
71
+
72
+ /**
73
+ * Load and validate an agent definition from a file
74
+ */
75
+ export function loadAgentFromFile(filePath: string): AgentDefinition {
76
+ if (!existsSync(filePath)) {
77
+ throw new AgentError(`Agent file not found: ${filePath}`, 'NOT_FOUND');
78
+ }
79
+
80
+ let content: string;
81
+ try {
82
+ content = readFileSync(filePath, 'utf-8');
83
+ } catch (error) {
84
+ const message = error instanceof Error ? error.message : 'Unknown read error';
85
+ throw new AgentError(`Failed to read agent file ${filePath}: ${message}`, 'READ_ERROR', error);
86
+ }
87
+
88
+ const parsed = parseAgentYaml(content, filePath);
89
+ return validateAgentDefinition(parsed);
90
+ }
91
+
92
+ /**
93
+ * List all YAML files in a directory
94
+ */
95
+ function listYamlFiles(dir: string): string[] {
96
+ if (!existsSync(dir)) {
97
+ return [];
98
+ }
99
+
100
+ return readdirSync(dir)
101
+ .filter((file) => {
102
+ const ext = extname(file).toLowerCase();
103
+ return ext === '.yaml' || ext === '.yml';
104
+ })
105
+ .map((file) => join(dir, file));
106
+ }
107
+
108
+ /**
109
+ * Load all agents from a directory
110
+ */
111
+ export function loadAgentsFromDirectory(
112
+ dir: string,
113
+ source: AgentSource
114
+ ): Map<string, AgentMetadata> {
115
+ const agents = new Map<string, AgentMetadata>();
116
+ const files = listYamlFiles(dir);
117
+
118
+ for (const filePath of files) {
119
+ try {
120
+ const definition = loadAgentFromFile(filePath);
121
+ agents.set(definition.role, {
122
+ definition,
123
+ source,
124
+ filePath,
125
+ });
126
+ } catch (error) {
127
+ // Log warning but continue loading other agents
128
+ const fileName = basename(filePath);
129
+ console.warn(`Warning: Failed to load agent from ${fileName}: ${(error as Error).message}`);
130
+ }
131
+ }
132
+
133
+ return agents;
134
+ }
135
+
136
+ /**
137
+ * Get the agent role name from a filename
138
+ */
139
+ export function getRoleFromFilename(filePath: string): string {
140
+ const fileName = basename(filePath);
141
+ const ext = extname(fileName);
142
+ return fileName.slice(0, -ext.length);
143
+ }
@@ -0,0 +1,282 @@
1
+ import {
2
+ resolveString,
3
+ resolveObject,
4
+ resolveAgentDefinition,
5
+ hasVariables,
6
+ extractVariables,
7
+ ResolutionError,
8
+ } from './resolver.js';
9
+ import type { CoreAIConfig } from '../config/types.js';
10
+ import type { AgentDefinition } from './types.js';
11
+
12
+ describe('Variable Resolver', () => {
13
+ const mockConfig: CoreAIConfig = {
14
+ version: '1.0',
15
+ project: {
16
+ name: 'test-project',
17
+ type: 'software',
18
+ },
19
+ team: {
20
+ agents: ['backend-engineer', 'frontend-engineer'],
21
+ },
22
+ integrations: {
23
+ documentation: {
24
+ provider: 'confluence',
25
+ config: {
26
+ base_url: 'https://docs.example.com',
27
+ space_key: 'TEAM',
28
+ },
29
+ },
30
+ issue_tracker: {
31
+ provider: 'jira',
32
+ config: {
33
+ base_url: 'https://jira.example.com',
34
+ project_key: 'PROJ',
35
+ },
36
+ },
37
+ git: {
38
+ provider: 'github',
39
+ config: {
40
+ repo: 'org/repo',
41
+ default_branch: 'main',
42
+ },
43
+ },
44
+ },
45
+ tech_stack: {
46
+ primary_language: 'TypeScript',
47
+ frameworks: ['React', 'Node.js'],
48
+ cloud: 'AWS',
49
+ },
50
+ quality_gates: {
51
+ lint: { command: 'npm run lint', required: true },
52
+ test: { command: 'npm test', required: true },
53
+ },
54
+ };
55
+
56
+ const mockAgent: AgentDefinition = {
57
+ role: 'backend-engineer',
58
+ type: 'ic-engineer',
59
+ display_name: 'Backend Engineer',
60
+ description: 'A backend engineer',
61
+ };
62
+
63
+ describe('resolveString', () => {
64
+ it('should resolve config variables', () => {
65
+ const result = resolveString('Project: ${config.project.name}', { config: mockConfig });
66
+ expect(result).toBe('Project: test-project');
67
+ });
68
+
69
+ it('should resolve nested config variables', () => {
70
+ const result = resolveString('Language: ${config.tech_stack.primary_language}', {
71
+ config: mockConfig,
72
+ });
73
+ expect(result).toBe('Language: TypeScript');
74
+ });
75
+
76
+ it('should resolve agent variables', () => {
77
+ const result = resolveString('Role: ${agent.role}', { agent: mockAgent });
78
+ expect(result).toBe('Role: backend-engineer');
79
+ });
80
+
81
+ it('should resolve remote.documentation shortcut', () => {
82
+ const result = resolveString('Docs: ${remote.documentation}', { config: mockConfig });
83
+ expect(result).toBe('Docs: https://docs.example.com');
84
+ });
85
+
86
+ it('should resolve remote.issues shortcut', () => {
87
+ const result = resolveString('Issues: ${remote.issues}', { config: mockConfig });
88
+ expect(result).toBe('Issues: https://jira.example.com');
89
+ });
90
+
91
+ it('should resolve remote.git shortcut', () => {
92
+ const result = resolveString('Repo: ${remote.git}', { config: mockConfig });
93
+ expect(result).toBe('Repo: org/repo');
94
+ });
95
+
96
+ it('should resolve multiple variables in one string', () => {
97
+ const result = resolveString('${agent.role} on ${config.project.name}', {
98
+ config: mockConfig,
99
+ agent: mockAgent,
100
+ });
101
+ expect(result).toBe('backend-engineer on test-project');
102
+ });
103
+
104
+ it('should leave unresolved variables as-is in non-strict mode', () => {
105
+ const result = resolveString('Value: ${config.nonexistent}', { config: mockConfig });
106
+ expect(result).toBe('Value: ${config.nonexistent}');
107
+ });
108
+
109
+ it('should throw in strict mode for unresolved variables', () => {
110
+ expect(() => {
111
+ resolveString('Value: ${config.nonexistent}', { config: mockConfig }, { strict: true });
112
+ }).toThrow(ResolutionError);
113
+ });
114
+
115
+ it('should throw in strict mode for missing context', () => {
116
+ expect(() => {
117
+ resolveString('Value: ${config.project.name}', {}, { strict: true });
118
+ }).toThrow(ResolutionError);
119
+ });
120
+
121
+ it('should resolve arrays as JSON', () => {
122
+ const result = resolveString('Frameworks: ${config.tech_stack.frameworks}', {
123
+ config: mockConfig,
124
+ });
125
+ expect(result).toBe('Frameworks: ["React","Node.js"]');
126
+ });
127
+
128
+ it('should resolve objects as JSON', () => {
129
+ const result = resolveString('Gate: ${config.quality_gates.lint}', { config: mockConfig });
130
+ expect(result).toBe('Gate: {"command":"npm run lint","required":true}');
131
+ });
132
+
133
+ it('should handle strings without variables', () => {
134
+ const result = resolveString('No variables here', { config: mockConfig });
135
+ expect(result).toBe('No variables here');
136
+ });
137
+ });
138
+
139
+ describe('hasVariables', () => {
140
+ it('should return true for strings with variables', () => {
141
+ expect(hasVariables('${config.project.name}')).toBe(true);
142
+ expect(hasVariables('Hello ${agent.role}')).toBe(true);
143
+ });
144
+
145
+ it('should return false for strings without variables', () => {
146
+ expect(hasVariables('No variables')).toBe(false);
147
+ expect(hasVariables('Just $ signs')).toBe(false);
148
+ });
149
+ });
150
+
151
+ describe('extractVariables', () => {
152
+ it('should extract single variable', () => {
153
+ const vars = extractVariables('${config.project.name}');
154
+ expect(vars).toEqual(['config.project.name']);
155
+ });
156
+
157
+ it('should extract multiple variables', () => {
158
+ const vars = extractVariables('${agent.role} on ${config.project.name}');
159
+ expect(vars).toEqual(['agent.role', 'config.project.name']);
160
+ });
161
+
162
+ it('should return empty array for no variables', () => {
163
+ const vars = extractVariables('No variables');
164
+ expect(vars).toEqual([]);
165
+ });
166
+ });
167
+
168
+ describe('resolveObject', () => {
169
+ it('should resolve variables in nested objects', () => {
170
+ const input = {
171
+ name: '${config.project.name}',
172
+ agent: {
173
+ role: '${agent.role}',
174
+ display: '${agent.display_name}',
175
+ },
176
+ };
177
+
178
+ const result = resolveObject(input, { config: mockConfig, agent: mockAgent });
179
+
180
+ expect(result).toEqual({
181
+ name: 'test-project',
182
+ agent: {
183
+ role: 'backend-engineer',
184
+ display: 'Backend Engineer',
185
+ },
186
+ });
187
+ });
188
+
189
+ it('should resolve variables in arrays', () => {
190
+ const input = {
191
+ sources: ['${remote.documentation}/architecture', '${remote.documentation}/api'],
192
+ };
193
+
194
+ const result = resolveObject(input, { config: mockConfig });
195
+
196
+ expect(result).toEqual({
197
+ sources: ['https://docs.example.com/architecture', 'https://docs.example.com/api'],
198
+ });
199
+ });
200
+
201
+ it('should handle null and undefined values', () => {
202
+ const input = {
203
+ value: null,
204
+ other: undefined,
205
+ name: '${config.project.name}',
206
+ };
207
+
208
+ const result = resolveObject(input, { config: mockConfig });
209
+
210
+ expect(result).toEqual({
211
+ value: null,
212
+ other: undefined,
213
+ name: 'test-project',
214
+ });
215
+ });
216
+
217
+ it('should preserve non-string primitives', () => {
218
+ const input = {
219
+ count: 42,
220
+ enabled: true,
221
+ name: '${config.project.name}',
222
+ };
223
+
224
+ const result = resolveObject(input, { config: mockConfig });
225
+
226
+ expect(result).toEqual({
227
+ count: 42,
228
+ enabled: true,
229
+ name: 'test-project',
230
+ });
231
+ });
232
+ });
233
+
234
+ describe('resolveAgentDefinition', () => {
235
+ it('should resolve all variables in an agent definition', () => {
236
+ const agent: AgentDefinition = {
237
+ role: 'backend-engineer',
238
+ type: 'ic-engineer',
239
+ display_name: 'Backend Engineer',
240
+ description: 'Backend engineer for ${config.project.name}',
241
+ expertise: {
242
+ primary: ['API design'],
243
+ tech_stack: '${config.tech_stack}',
244
+ },
245
+ behaviors: {
246
+ workflow: 'ticket-implementation',
247
+ quality_gates: '${config.quality_gates}',
248
+ },
249
+ context_sources: {
250
+ shared: ['${remote.documentation}/architecture'],
251
+ personal: ['KnowledgeLibrary/${agent.role}/context'],
252
+ },
253
+ communication: {
254
+ inbox: 'KnowledgeLibrary/${agent.role}/inbox',
255
+ outbox: 'KnowledgeLibrary/${agent.role}/outbox',
256
+ },
257
+ };
258
+
259
+ const resolved = resolveAgentDefinition(agent, mockConfig);
260
+
261
+ expect(resolved.description).toBe('Backend engineer for test-project');
262
+ expect(resolved.context_sources?.shared?.[0]).toBe('https://docs.example.com/architecture');
263
+ expect(resolved.context_sources?.personal?.[0]).toBe(
264
+ 'KnowledgeLibrary/backend-engineer/context'
265
+ );
266
+ expect(resolved.communication?.inbox).toBe('KnowledgeLibrary/backend-engineer/inbox');
267
+ });
268
+
269
+ it('should work without config', () => {
270
+ const agent: AgentDefinition = {
271
+ role: 'test-agent',
272
+ type: 'ic-engineer',
273
+ display_name: 'Test Agent',
274
+ description: 'Agent role: ${agent.role}',
275
+ };
276
+
277
+ const resolved = resolveAgentDefinition(agent);
278
+
279
+ expect(resolved.description).toBe('Agent role: test-agent');
280
+ });
281
+ });
282
+ });
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Variable Resolution System
3
+ *
4
+ * Resolves variable placeholders in agent definitions.
5
+ * Supports: ${config.*}, ${agent.*}, ${remote.*}
6
+ */
7
+
8
+ import type { CoreAIConfig } from '../config/types.js';
9
+ import type { AgentDefinition } from './types.js';
10
+
11
+ /**
12
+ * Context for variable resolution
13
+ */
14
+ export interface ResolutionContext {
15
+ config?: CoreAIConfig;
16
+ agent?: AgentDefinition;
17
+ }
18
+
19
+ /**
20
+ * Options for variable resolution
21
+ */
22
+ export interface ResolutionOptions {
23
+ /**
24
+ * If true, throw an error for unresolved variables.
25
+ * If false, leave unresolved variables as-is.
26
+ * Default: false
27
+ */
28
+ strict?: boolean;
29
+ }
30
+
31
+ /**
32
+ * Error thrown when variable resolution fails
33
+ */
34
+ export class ResolutionError extends Error {
35
+ constructor(
36
+ message: string,
37
+ public readonly variable: string,
38
+ public readonly path?: string
39
+ ) {
40
+ super(message);
41
+ this.name = 'ResolutionError';
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Pattern to match variable placeholders: ${namespace.path.to.value}
47
+ */
48
+ const VARIABLE_PATTERN = /\$\{([a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)*)\}/gi;
49
+
50
+ /**
51
+ * Get a nested value from an object using dot notation
52
+ */
53
+ function getNestedValue(obj: unknown, path: string): unknown {
54
+ const parts = path.split('.');
55
+ let current: unknown = obj;
56
+
57
+ for (const part of parts) {
58
+ if (current === null || current === undefined) {
59
+ return undefined;
60
+ }
61
+ if (typeof current !== 'object') {
62
+ return undefined;
63
+ }
64
+ current = (current as Record<string, unknown>)[part];
65
+ }
66
+
67
+ return current;
68
+ }
69
+
70
+ /**
71
+ * Resolve a single variable reference
72
+ */
73
+ function resolveVariable(
74
+ variable: string,
75
+ context: ResolutionContext,
76
+ options: ResolutionOptions
77
+ ): string | undefined {
78
+ const parts = variable.split('.');
79
+ const namespace = parts[0];
80
+ const path = parts.slice(1).join('.');
81
+
82
+ let value: unknown;
83
+
84
+ switch (namespace) {
85
+ case 'config':
86
+ if (!context.config) {
87
+ if (options.strict) {
88
+ throw new ResolutionError(
89
+ `Cannot resolve \${${variable}}: no config context provided`,
90
+ variable
91
+ );
92
+ }
93
+ return undefined;
94
+ }
95
+ value = getNestedValue(context.config, path);
96
+ break;
97
+
98
+ case 'agent':
99
+ if (!context.agent) {
100
+ if (options.strict) {
101
+ throw new ResolutionError(
102
+ `Cannot resolve \${${variable}}: no agent context provided`,
103
+ variable
104
+ );
105
+ }
106
+ return undefined;
107
+ }
108
+ value = getNestedValue(context.agent, path);
109
+ break;
110
+
111
+ case 'remote':
112
+ // Remote is a shortcut for integration URLs
113
+ value = resolveRemoteVariable(path, context, options);
114
+ break;
115
+
116
+ default:
117
+ if (options.strict) {
118
+ throw new ResolutionError(`Unknown variable namespace: ${namespace}`, variable);
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ if (value === undefined) {
124
+ if (options.strict) {
125
+ throw new ResolutionError(`Cannot resolve \${${variable}}: path not found`, variable, path);
126
+ }
127
+ return undefined;
128
+ }
129
+
130
+ // Convert value to string representation
131
+ if (typeof value === 'string') {
132
+ return value;
133
+ }
134
+ if (typeof value === 'number' || typeof value === 'boolean') {
135
+ return String(value);
136
+ }
137
+ // For objects/arrays, return JSON representation
138
+ return JSON.stringify(value);
139
+ }
140
+
141
+ /**
142
+ * Resolve remote.* variables (shortcuts to integration URLs)
143
+ */
144
+ function resolveRemoteVariable(
145
+ path: string,
146
+ context: ResolutionContext,
147
+ options: ResolutionOptions
148
+ ): string | undefined {
149
+ if (!context.config?.integrations) {
150
+ if (options.strict) {
151
+ throw new ResolutionError(
152
+ `Cannot resolve \${remote.${path}}: no integrations configured`,
153
+ `remote.${path}`
154
+ );
155
+ }
156
+ return undefined;
157
+ }
158
+
159
+ const integrations = context.config.integrations;
160
+
161
+ // Map remote shortcuts to integration paths
162
+ switch (path) {
163
+ case 'documentation':
164
+ return (
165
+ integrations.documentation?.config?.base_url ??
166
+ integrations.documentation?.config?.base_path
167
+ );
168
+
169
+ case 'issues':
170
+ return integrations.issue_tracker?.config?.base_url;
171
+
172
+ case 'git':
173
+ return integrations.git?.config?.repo;
174
+
175
+ case 'state':
176
+ return integrations.state?.config?.base_path ?? integrations.state?.config?.bucket;
177
+
178
+ default:
179
+ // Try to resolve as nested path under integrations
180
+ return getNestedValue(integrations, path) as string | undefined;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Resolve all variables in a string
186
+ */
187
+ export function resolveString(
188
+ input: string,
189
+ context: ResolutionContext,
190
+ options: ResolutionOptions = {}
191
+ ): string {
192
+ return input.replace(VARIABLE_PATTERN, (match, variable: string) => {
193
+ const resolved = resolveVariable(variable, context, options);
194
+ return resolved !== undefined ? resolved : match;
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Check if a string contains variable placeholders
200
+ */
201
+ export function hasVariables(input: string): boolean {
202
+ // Create new regex to avoid state issues with global flag
203
+ const pattern = /\$\{([a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)*)\}/i;
204
+ return pattern.test(input);
205
+ }
206
+
207
+ /**
208
+ * Extract all variable references from a string
209
+ */
210
+ export function extractVariables(input: string): string[] {
211
+ const matches = input.matchAll(VARIABLE_PATTERN);
212
+ return Array.from(matches, (m) => m[1]).filter((v): v is string => v !== undefined);
213
+ }
214
+
215
+ /**
216
+ * Recursively resolve all variables in an object
217
+ */
218
+ export function resolveObject<T>(
219
+ obj: T,
220
+ context: ResolutionContext,
221
+ options: ResolutionOptions = {}
222
+ ): T {
223
+ if (obj === null || obj === undefined) {
224
+ return obj;
225
+ }
226
+
227
+ if (typeof obj === 'string') {
228
+ return resolveString(obj, context, options) as T;
229
+ }
230
+
231
+ if (Array.isArray(obj)) {
232
+ return obj.map((item) => resolveObject(item, context, options)) as T;
233
+ }
234
+
235
+ if (typeof obj === 'object') {
236
+ const result: Record<string, unknown> = {};
237
+ for (const [key, value] of Object.entries(obj)) {
238
+ result[key] = resolveObject(value, context, options);
239
+ }
240
+ return result as T;
241
+ }
242
+
243
+ return obj;
244
+ }
245
+
246
+ /**
247
+ * Resolve all variables in an agent definition
248
+ */
249
+ export function resolveAgentDefinition(
250
+ agent: AgentDefinition,
251
+ config?: CoreAIConfig,
252
+ options: ResolutionOptions = {}
253
+ ): AgentDefinition {
254
+ const context: ResolutionContext = {
255
+ agent,
256
+ };
257
+ if (config) {
258
+ context.config = config;
259
+ }
260
+
261
+ return resolveObject(agent, context, options);
262
+ }