plugin-agent-orchestrator 1.1.4 → 1.1.6

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 (148) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  6. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  7. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +7 -8
  10. package/dist/locale/en-US.json +226 -170
  11. package/dist/locale/vi-VN.json +226 -170
  12. package/dist/locale/zh-CN.json +226 -170
  13. package/dist/server/collections/agent-execution-spans.js +8 -0
  14. package/dist/server/collections/agent-loop-action-approvals.js +1 -0
  15. package/dist/server/collections/agent-loop-runs.js +7 -1
  16. package/dist/server/collections/agent-loop-steps.js +7 -0
  17. package/dist/server/collections/skill-executions.js +8 -0
  18. package/dist/server/plugin.js +3 -1
  19. package/dist/server/resources/agent-harness-profile.js +117 -0
  20. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  21. package/dist/server/resources/agent-loop-approval.js +25 -0
  22. package/dist/server/resources/agent-loop.js +3 -1
  23. package/dist/server/services/AgentMemoryContextService.js +34 -0
  24. package/dist/server/services/HarnessCompiler.js +35 -2
  25. package/dist/server/services/HarnessProfileService.js +74 -9
  26. package/dist/server/services/HarnessSchema.js +30 -3
  27. package/dist/server/services/LoopPatternSchema.js +16 -1
  28. package/dist/server/services/LoopRunRepository.js +80 -0
  29. package/dist/server/services/LoopRunStateMachine.js +92 -3
  30. package/dist/server/services/LoopTriggerService.js +37 -0
  31. package/dist/server/services/LoopWorkerService.js +261 -23
  32. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  33. package/dist/server/services/PluginAiRuntimeAdapter.js +16 -5
  34. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  35. package/dist/server/services/VerificationService.js +66 -0
  36. package/dist/server/services/harness-runtime-policy.js +139 -0
  37. package/dist/server/skill-hub/plugin.js +36 -3
  38. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  39. package/package.json +53 -53
  40. package/src/client/ApprovalsTab.tsx +2 -0
  41. package/src/client/OrchestratorSettings.tsx +11 -0
  42. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  43. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  44. package/src/client/skill-hub/index.tsx +0 -52
  45. package/src/client-v2/components/AgentRunsTab.tsx +576 -576
  46. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  47. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -105
  48. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -141
  49. package/src/client-v2/components/TracingTab.tsx +515 -515
  50. package/src/client-v2/hooks/useApiRequest.ts +141 -141
  51. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  52. package/src/client-v2/plugin.tsx +6 -6
  53. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +5 -2
  54. package/src/locale/en-US.json +226 -174
  55. package/src/locale/vi-VN.json +226 -174
  56. package/src/locale/zh-CN.json +226 -174
  57. package/src/server/__tests__/circuit-breaker.test.ts +248 -248
  58. package/src/server/__tests__/harness-compiler.test.ts +83 -0
  59. package/src/server/__tests__/harness-profile-service.test.ts +51 -0
  60. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  61. package/src/server/__tests__/harness-tool-plan.test.ts +24 -0
  62. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  63. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  64. package/src/server/__tests__/loop-budget-service.test.ts +255 -255
  65. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -266
  66. package/src/server/__tests__/loop-pattern-schema.test.ts +18 -1
  67. package/src/server/__tests__/loop-pattern-service.test.ts +148 -148
  68. package/src/server/__tests__/loop-run-state-machine.test.ts +11 -0
  69. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  70. package/src/server/__tests__/loop-worker-claim.test.ts +341 -341
  71. package/src/server/__tests__/loop-worker-execution.test.ts +82 -1
  72. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  73. package/src/server/__tests__/path-lock-service.test.ts +254 -254
  74. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  75. package/src/server/__tests__/smoke.test.ts +162 -162
  76. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  77. package/src/server/collections/agent-execution-spans.ts +8 -0
  78. package/src/server/collections/agent-harness-profile-versions.ts +26 -26
  79. package/src/server/collections/agent-harness-profiles.ts +71 -71
  80. package/src/server/collections/agent-loop-action-approvals.ts +1 -0
  81. package/src/server/collections/agent-loop-artifacts.ts +25 -25
  82. package/src/server/collections/agent-loop-circuit-states.ts +23 -23
  83. package/src/server/collections/agent-loop-control-settings.ts +21 -21
  84. package/src/server/collections/agent-loop-events.ts +98 -98
  85. package/src/server/collections/agent-loop-path-locks.ts +27 -27
  86. package/src/server/collections/agent-loop-patterns.ts +42 -42
  87. package/src/server/collections/agent-loop-runs.ts +7 -1
  88. package/src/server/collections/agent-loop-steps.ts +7 -0
  89. package/src/server/collections/agent-loop-usage-buckets.ts +22 -22
  90. package/src/server/collections/agent-loop-worktrees.ts +25 -25
  91. package/src/server/collections/skill-executions.ts +8 -0
  92. package/src/server/migrations/20260427000002-change-packages-to-text.ts +52 -52
  93. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -47
  94. package/src/server/migrations/20260429000001-fix-inputargs-json-to-text.ts +45 -45
  95. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -33
  96. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -31
  97. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -293
  98. package/src/server/plugin.ts +3 -1
  99. package/src/server/resources/agent-harness-profile.ts +94 -0
  100. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  101. package/src/server/resources/agent-loop-approval.ts +32 -0
  102. package/src/server/resources/agent-loop-artifact.ts +56 -56
  103. package/src/server/resources/agent-loop-events-stream.ts +105 -105
  104. package/src/server/resources/agent-loop.ts +3 -1
  105. package/src/server/resources/resource-helpers.ts +33 -33
  106. package/src/server/resources/tracing.ts +266 -266
  107. package/src/server/services/AgentMemoryContextService.ts +44 -0
  108. package/src/server/services/DurableCircuitBreakerService.ts +239 -239
  109. package/src/server/services/ExecutionSpanService.ts +2 -0
  110. package/src/server/services/HarnessCompiler.ts +37 -0
  111. package/src/server/services/HarnessProfileService.ts +92 -10
  112. package/src/server/services/HarnessSchema.ts +31 -0
  113. package/src/server/services/LoopBudgetService.ts +275 -275
  114. package/src/server/services/LoopControlService.ts +124 -124
  115. package/src/server/services/LoopPatternSchema.ts +19 -1
  116. package/src/server/services/LoopPatternService.ts +143 -143
  117. package/src/server/services/LoopRunRepository.ts +99 -0
  118. package/src/server/services/LoopRunStateMachine.ts +100 -3
  119. package/src/server/services/LoopSchedulerService.ts +199 -199
  120. package/src/server/services/LoopTriggerService.ts +42 -0
  121. package/src/server/services/LoopWorkerService.ts +327 -27
  122. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  123. package/src/server/services/PathLockService.ts +321 -321
  124. package/src/server/services/PluginAiRuntimeAdapter.ts +24 -7
  125. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  126. package/src/server/services/VerificationSchema.ts +31 -31
  127. package/src/server/services/VerificationService.ts +81 -2
  128. package/src/server/services/harness-runtime-policy.ts +141 -0
  129. package/src/server/skill-hub/plugin.ts +41 -3
  130. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -235
  131. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -61
  132. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  133. package/src/server/utils/ensure-indexes.ts +96 -96
  134. package/src/server/utils/logging.ts +62 -62
  135. package/src/server/utils/loop-pattern-context.ts +20 -20
  136. package/dist/client-v2/214.b063f33ba044a808.js +0 -10
  137. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  138. package/dist/client-v2/418.58fa350f5496efd3.js +0 -10
  139. package/dist/client-v2/53.9a10455323390f14.js +0 -10
  140. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  141. package/dist/client-v2/925.e5925bf21ed68e7a.js +0 -10
  142. package/src/client/AIEmployeeSelect.tsx +0 -47
  143. package/src/client/AIEmployeesContext.tsx +0 -102
  144. package/src/client/RulesTab.tsx +0 -2
  145. package/src/client/TracingTab.tsx +0 -436
  146. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  147. package/src/client-v2/components/RulesTab.tsx +0 -2
  148. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
@@ -1,248 +1,248 @@
1
- import type { Database } from '@nocobase/database';
2
- import { describe, expect, it } from 'vitest';
3
- import { DurableCircuitBreakerService, normalizeErrorSignature } from '../services/DurableCircuitBreakerService';
4
- import { loopPatternPolicySchema } from '../services/LoopPatternSchema';
5
-
6
- type Row = Record<string, unknown>;
7
-
8
- function matches(row: Row, filter: Row) {
9
- return Object.entries(filter).every(([key, value]) => row[key] === value);
10
- }
11
-
12
- class MemoryRepository {
13
- private nextId = 1;
14
-
15
- constructor(readonly rows: Row[] = []) {
16
- this.nextId = rows.reduce((maximum, row) => Math.max(maximum, Number(row.id) || 0), 0) + 1;
17
- }
18
-
19
- async findOne(options: Row) {
20
- if (options.filterByTk !== undefined) return this.rows.find((row) => row.id === options.filterByTk) || null;
21
- return this.rows.find((row) => matches(row, (options.filter as Row | undefined) || {})) || null;
22
- }
23
-
24
- async create(options: Row) {
25
- const row = { id: this.nextId++, ...((options.values as Row | undefined) || {}) };
26
- this.rows.push(row);
27
- return row;
28
- }
29
-
30
- async update(options: Row) {
31
- const values = (options.values as Row | undefined) || {};
32
- for (const row of this.rows) {
33
- if (options.filterByTk !== undefined && row.id === options.filterByTk) Object.assign(row, values);
34
- }
35
- }
36
-
37
- restore(rows: Row[]) {
38
- this.rows.splice(0, this.rows.length, ...structuredClone(rows));
39
- this.nextId = this.rows.reduce((maximum, row) => Math.max(maximum, Number(row.id) || 0), 0) + 1;
40
- }
41
- }
42
-
43
- class SerialLock {
44
- private readonly tails = new Map<string, Promise<void>>();
45
-
46
- async runExclusive<T>(key: string, operation: () => Promise<T>) {
47
- const previous = this.tails.get(key) || Promise.resolve();
48
- let release = () => {};
49
- const pending = new Promise<void>((resolve) => {
50
- release = resolve;
51
- });
52
- const tail = previous.then(() => pending);
53
- this.tails.set(key, tail);
54
- await previous;
55
- try {
56
- return await operation();
57
- } finally {
58
- release();
59
- if (this.tails.get(key) === tail) this.tails.delete(key);
60
- }
61
- }
62
- }
63
-
64
- function createService(initialRows: Row[] = []) {
65
- const circuits = new MemoryRepository(initialRows);
66
- const transaction = { LOCK: { UPDATE: 'UPDATE' } };
67
- const database = {
68
- getRepository(name: string) {
69
- if (name !== 'agentLoopCircuitStates') throw new Error(`Unexpected repository ${name}`);
70
- return circuits;
71
- },
72
- sequelize: {
73
- async transaction<T>(callback: (value: typeof transaction) => Promise<T>) {
74
- const before = structuredClone(circuits.rows);
75
- try {
76
- return await callback(transaction);
77
- } catch (error) {
78
- circuits.restore(before);
79
- throw error;
80
- }
81
- },
82
- },
83
- };
84
- return {
85
- circuits,
86
- service: new DurableCircuitBreakerService(database as unknown as Database, new SerialLock()),
87
- };
88
- }
89
-
90
- function circuitPolicy(overrides: Record<string, number> = {}) {
91
- return loopPatternPolicySchema.parse({ circuit: overrides }).circuit;
92
- }
93
-
94
- describe('DurableCircuitBreakerService', () => {
95
- it('normalizes volatile paths, identifiers, and numbers into one error signature', () => {
96
- const first = new Error('Failed C:\\repo\\one\\file.ts for 123e4567-e89b-12d3-a456-426614174000 at line 42');
97
- const second = new Error('Failed C:\\repo\\two\\file.ts for 223e4567-e89b-12d3-a456-426614174999 at line 99');
98
- expect(normalizeErrorSignature(first)).toBe(normalizeErrorSignature(second));
99
- expect(normalizeErrorSignature(new Error('Permission denied'))).not.toBe(normalizeErrorSignature(first));
100
- });
101
-
102
- it('canonicalizes the scope and durably opens after the maximum attempt count', async () => {
103
- const { circuits, service } = createService();
104
- const policy = circuitPolicy({
105
- maxAttempts: 2,
106
- maxConsecutiveFailures: 99,
107
- maxRepeatedError: 99,
108
- cooldownMs: 1_000,
109
- });
110
- const now = new Date('2026-08-03T00:00:00.000Z');
111
-
112
- await expect(service.authorizeAttempt({ patternId: 1, scopeKey: ' repo ', policy, now })).resolves.toMatchObject({
113
- state: 'closed',
114
- attempt: 1,
115
- });
116
- await service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now });
117
- await expect(service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now })).rejects.toThrow(
118
- 'maximum attempts',
119
- );
120
-
121
- expect(circuits.rows).toHaveLength(1);
122
- expect(circuits.rows[0]).toMatchObject({ scopeKey: 'repo', state: 'open', attempts: 2 });
123
- expect(circuits.rows[0].retryAt).toEqual(new Date('2026-08-03T00:00:01.000Z'));
124
- });
125
-
126
- it('opens on repeated normalized errors and consecutive different failures', async () => {
127
- const repeated = createService();
128
- const repeatedPolicy = circuitPolicy({
129
- maxAttempts: 99,
130
- maxConsecutiveFailures: 99,
131
- maxRepeatedError: 2,
132
- cooldownMs: 1_000,
133
- });
134
- await repeated.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: repeatedPolicy });
135
- await repeated.service.recordFailure({
136
- patternId: 1,
137
- scopeKey: 'repo',
138
- policy: repeatedPolicy,
139
- error: new Error('Failed C:\\repo\\one\\file.ts at line 42'),
140
- });
141
- await repeated.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: repeatedPolicy });
142
- const repeatedResult = await repeated.service.recordFailure({
143
- patternId: 1,
144
- scopeKey: 'repo',
145
- policy: repeatedPolicy,
146
- error: new Error('Failed C:\\repo\\two\\file.ts at line 99'),
147
- });
148
- expect(repeatedResult).toMatchObject({ open: true, repeatedErrorCount: 2 });
149
-
150
- const consecutive = createService();
151
- const consecutivePolicy = circuitPolicy({
152
- maxAttempts: 99,
153
- maxConsecutiveFailures: 2,
154
- maxRepeatedError: 99,
155
- cooldownMs: 1_000,
156
- });
157
- await consecutive.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: consecutivePolicy });
158
- await consecutive.service.recordFailure({
159
- patternId: 1,
160
- scopeKey: 'repo',
161
- policy: consecutivePolicy,
162
- error: new Error('First failure'),
163
- });
164
- await consecutive.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: consecutivePolicy });
165
- const consecutiveResult = await consecutive.service.recordFailure({
166
- patternId: 1,
167
- scopeKey: 'repo',
168
- policy: consecutivePolicy,
169
- error: new Error('Different failure'),
170
- });
171
- expect(consecutiveResult).toMatchObject({ open: true, consecutiveFailures: 2, repeatedErrorCount: 1 });
172
- });
173
-
174
- it('rejects before cooldown and allows exactly one half-open probe', async () => {
175
- const retryAt = new Date('2026-08-03T00:00:10.000Z');
176
- const { circuits, service } = createService([
177
- {
178
- id: 1,
179
- patternId: 1,
180
- scopeKey: 'repo',
181
- state: 'open',
182
- attempts: 1,
183
- consecutiveFailures: 1,
184
- errorSignature: 'signature',
185
- repeatedErrorCount: 1,
186
- retryAt,
187
- },
188
- ]);
189
- const policy = circuitPolicy({ maxAttempts: 99, maxConsecutiveFailures: 99, maxRepeatedError: 99 });
190
-
191
- await expect(
192
- service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: new Date('2026-08-03T00:00:09.000Z') }),
193
- ).rejects.toThrow('open until');
194
-
195
- const results = await Promise.allSettled([
196
- service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt }),
197
- service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt }),
198
- ]);
199
- expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
200
- expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1);
201
- expect(circuits.rows[0]).toMatchObject({ state: 'half_open', attempts: 2 });
202
- });
203
-
204
- it('reopens a failed probe and resets all state after success', async () => {
205
- const retryAt = new Date('2026-08-03T00:00:00.000Z');
206
- const { circuits, service } = createService([
207
- {
208
- id: 1,
209
- patternId: 1,
210
- scopeKey: 'repo',
211
- state: 'open',
212
- attempts: 1,
213
- consecutiveFailures: 1,
214
- errorSignature: 'old',
215
- repeatedErrorCount: 1,
216
- retryAt,
217
- },
218
- ]);
219
- const policy = circuitPolicy({
220
- maxAttempts: 99,
221
- maxConsecutiveFailures: 99,
222
- maxRepeatedError: 99,
223
- cooldownMs: 1_000,
224
- });
225
-
226
- await service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt });
227
- const failure = await service.recordFailure({
228
- patternId: 1,
229
- scopeKey: 'repo',
230
- policy,
231
- error: new Error('Probe failed'),
232
- now: retryAt,
233
- });
234
- expect(failure.open).toBe(true);
235
- expect(circuits.rows[0].state).toBe('open');
236
-
237
- await service.recordSuccess(1, ' repo ', 9);
238
- expect(circuits.rows[0]).toMatchObject({
239
- state: 'closed',
240
- attempts: 0,
241
- consecutiveFailures: 0,
242
- errorSignature: null,
243
- repeatedErrorCount: 0,
244
- lastRunId: 9,
245
- retryAt: null,
246
- });
247
- });
248
- });
1
+ import type { Database } from '@nocobase/database';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { DurableCircuitBreakerService, normalizeErrorSignature } from '../services/DurableCircuitBreakerService';
4
+ import { loopPatternPolicySchema } from '../services/LoopPatternSchema';
5
+
6
+ type Row = Record<string, unknown>;
7
+
8
+ function matches(row: Row, filter: Row) {
9
+ return Object.entries(filter).every(([key, value]) => row[key] === value);
10
+ }
11
+
12
+ class MemoryRepository {
13
+ private nextId = 1;
14
+
15
+ constructor(readonly rows: Row[] = []) {
16
+ this.nextId = rows.reduce((maximum, row) => Math.max(maximum, Number(row.id) || 0), 0) + 1;
17
+ }
18
+
19
+ async findOne(options: Row) {
20
+ if (options.filterByTk !== undefined) return this.rows.find((row) => row.id === options.filterByTk) || null;
21
+ return this.rows.find((row) => matches(row, (options.filter as Row | undefined) || {})) || null;
22
+ }
23
+
24
+ async create(options: Row) {
25
+ const row = { id: this.nextId++, ...((options.values as Row | undefined) || {}) };
26
+ this.rows.push(row);
27
+ return row;
28
+ }
29
+
30
+ async update(options: Row) {
31
+ const values = (options.values as Row | undefined) || {};
32
+ for (const row of this.rows) {
33
+ if (options.filterByTk !== undefined && row.id === options.filterByTk) Object.assign(row, values);
34
+ }
35
+ }
36
+
37
+ restore(rows: Row[]) {
38
+ this.rows.splice(0, this.rows.length, ...structuredClone(rows));
39
+ this.nextId = this.rows.reduce((maximum, row) => Math.max(maximum, Number(row.id) || 0), 0) + 1;
40
+ }
41
+ }
42
+
43
+ class SerialLock {
44
+ private readonly tails = new Map<string, Promise<void>>();
45
+
46
+ async runExclusive<T>(key: string, operation: () => Promise<T>) {
47
+ const previous = this.tails.get(key) || Promise.resolve();
48
+ let release = () => {};
49
+ const pending = new Promise<void>((resolve) => {
50
+ release = resolve;
51
+ });
52
+ const tail = previous.then(() => pending);
53
+ this.tails.set(key, tail);
54
+ await previous;
55
+ try {
56
+ return await operation();
57
+ } finally {
58
+ release();
59
+ if (this.tails.get(key) === tail) this.tails.delete(key);
60
+ }
61
+ }
62
+ }
63
+
64
+ function createService(initialRows: Row[] = []) {
65
+ const circuits = new MemoryRepository(initialRows);
66
+ const transaction = { LOCK: { UPDATE: 'UPDATE' } };
67
+ const database = {
68
+ getRepository(name: string) {
69
+ if (name !== 'agentLoopCircuitStates') throw new Error(`Unexpected repository ${name}`);
70
+ return circuits;
71
+ },
72
+ sequelize: {
73
+ async transaction<T>(callback: (value: typeof transaction) => Promise<T>) {
74
+ const before = structuredClone(circuits.rows);
75
+ try {
76
+ return await callback(transaction);
77
+ } catch (error) {
78
+ circuits.restore(before);
79
+ throw error;
80
+ }
81
+ },
82
+ },
83
+ };
84
+ return {
85
+ circuits,
86
+ service: new DurableCircuitBreakerService(database as unknown as Database, new SerialLock()),
87
+ };
88
+ }
89
+
90
+ function circuitPolicy(overrides: Record<string, number> = {}) {
91
+ return loopPatternPolicySchema.parse({ circuit: overrides }).circuit;
92
+ }
93
+
94
+ describe('DurableCircuitBreakerService', () => {
95
+ it('normalizes volatile paths, identifiers, and numbers into one error signature', () => {
96
+ const first = new Error('Failed C:\\repo\\one\\file.ts for 123e4567-e89b-12d3-a456-426614174000 at line 42');
97
+ const second = new Error('Failed C:\\repo\\two\\file.ts for 223e4567-e89b-12d3-a456-426614174999 at line 99');
98
+ expect(normalizeErrorSignature(first)).toBe(normalizeErrorSignature(second));
99
+ expect(normalizeErrorSignature(new Error('Permission denied'))).not.toBe(normalizeErrorSignature(first));
100
+ });
101
+
102
+ it('canonicalizes the scope and durably opens after the maximum attempt count', async () => {
103
+ const { circuits, service } = createService();
104
+ const policy = circuitPolicy({
105
+ maxAttempts: 2,
106
+ maxConsecutiveFailures: 99,
107
+ maxRepeatedError: 99,
108
+ cooldownMs: 1_000,
109
+ });
110
+ const now = new Date('2026-08-03T00:00:00.000Z');
111
+
112
+ await expect(service.authorizeAttempt({ patternId: 1, scopeKey: ' repo ', policy, now })).resolves.toMatchObject({
113
+ state: 'closed',
114
+ attempt: 1,
115
+ });
116
+ await service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now });
117
+ await expect(service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now })).rejects.toThrow(
118
+ 'maximum attempts',
119
+ );
120
+
121
+ expect(circuits.rows).toHaveLength(1);
122
+ expect(circuits.rows[0]).toMatchObject({ scopeKey: 'repo', state: 'open', attempts: 2 });
123
+ expect(circuits.rows[0].retryAt).toEqual(new Date('2026-08-03T00:00:01.000Z'));
124
+ });
125
+
126
+ it('opens on repeated normalized errors and consecutive different failures', async () => {
127
+ const repeated = createService();
128
+ const repeatedPolicy = circuitPolicy({
129
+ maxAttempts: 99,
130
+ maxConsecutiveFailures: 99,
131
+ maxRepeatedError: 2,
132
+ cooldownMs: 1_000,
133
+ });
134
+ await repeated.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: repeatedPolicy });
135
+ await repeated.service.recordFailure({
136
+ patternId: 1,
137
+ scopeKey: 'repo',
138
+ policy: repeatedPolicy,
139
+ error: new Error('Failed C:\\repo\\one\\file.ts at line 42'),
140
+ });
141
+ await repeated.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: repeatedPolicy });
142
+ const repeatedResult = await repeated.service.recordFailure({
143
+ patternId: 1,
144
+ scopeKey: 'repo',
145
+ policy: repeatedPolicy,
146
+ error: new Error('Failed C:\\repo\\two\\file.ts at line 99'),
147
+ });
148
+ expect(repeatedResult).toMatchObject({ open: true, repeatedErrorCount: 2 });
149
+
150
+ const consecutive = createService();
151
+ const consecutivePolicy = circuitPolicy({
152
+ maxAttempts: 99,
153
+ maxConsecutiveFailures: 2,
154
+ maxRepeatedError: 99,
155
+ cooldownMs: 1_000,
156
+ });
157
+ await consecutive.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: consecutivePolicy });
158
+ await consecutive.service.recordFailure({
159
+ patternId: 1,
160
+ scopeKey: 'repo',
161
+ policy: consecutivePolicy,
162
+ error: new Error('First failure'),
163
+ });
164
+ await consecutive.service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy: consecutivePolicy });
165
+ const consecutiveResult = await consecutive.service.recordFailure({
166
+ patternId: 1,
167
+ scopeKey: 'repo',
168
+ policy: consecutivePolicy,
169
+ error: new Error('Different failure'),
170
+ });
171
+ expect(consecutiveResult).toMatchObject({ open: true, consecutiveFailures: 2, repeatedErrorCount: 1 });
172
+ });
173
+
174
+ it('rejects before cooldown and allows exactly one half-open probe', async () => {
175
+ const retryAt = new Date('2026-08-03T00:00:10.000Z');
176
+ const { circuits, service } = createService([
177
+ {
178
+ id: 1,
179
+ patternId: 1,
180
+ scopeKey: 'repo',
181
+ state: 'open',
182
+ attempts: 1,
183
+ consecutiveFailures: 1,
184
+ errorSignature: 'signature',
185
+ repeatedErrorCount: 1,
186
+ retryAt,
187
+ },
188
+ ]);
189
+ const policy = circuitPolicy({ maxAttempts: 99, maxConsecutiveFailures: 99, maxRepeatedError: 99 });
190
+
191
+ await expect(
192
+ service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: new Date('2026-08-03T00:00:09.000Z') }),
193
+ ).rejects.toThrow('open until');
194
+
195
+ const results = await Promise.allSettled([
196
+ service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt }),
197
+ service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt }),
198
+ ]);
199
+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
200
+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1);
201
+ expect(circuits.rows[0]).toMatchObject({ state: 'half_open', attempts: 2 });
202
+ });
203
+
204
+ it('reopens a failed probe and resets all state after success', async () => {
205
+ const retryAt = new Date('2026-08-03T00:00:00.000Z');
206
+ const { circuits, service } = createService([
207
+ {
208
+ id: 1,
209
+ patternId: 1,
210
+ scopeKey: 'repo',
211
+ state: 'open',
212
+ attempts: 1,
213
+ consecutiveFailures: 1,
214
+ errorSignature: 'old',
215
+ repeatedErrorCount: 1,
216
+ retryAt,
217
+ },
218
+ ]);
219
+ const policy = circuitPolicy({
220
+ maxAttempts: 99,
221
+ maxConsecutiveFailures: 99,
222
+ maxRepeatedError: 99,
223
+ cooldownMs: 1_000,
224
+ });
225
+
226
+ await service.authorizeAttempt({ patternId: 1, scopeKey: 'repo', policy, now: retryAt });
227
+ const failure = await service.recordFailure({
228
+ patternId: 1,
229
+ scopeKey: 'repo',
230
+ policy,
231
+ error: new Error('Probe failed'),
232
+ now: retryAt,
233
+ });
234
+ expect(failure.open).toBe(true);
235
+ expect(circuits.rows[0].state).toBe('open');
236
+
237
+ await service.recordSuccess(1, ' repo ', 9);
238
+ expect(circuits.rows[0]).toMatchObject({
239
+ state: 'closed',
240
+ attempts: 0,
241
+ consecutiveFailures: 0,
242
+ errorSignature: null,
243
+ repeatedErrorCount: 0,
244
+ lastRunId: 9,
245
+ retryAt: null,
246
+ });
247
+ });
248
+ });
@@ -128,4 +128,87 @@ describe('HarnessCompiler', () => {
128
128
  expect(decideTool(compiled, 'trusted_write')).toBe('allow');
129
129
  expect(decideTool(compiled, 'unknown_tool')).toBe('ask');
130
130
  });
131
+
132
+ it('merges per-tool timeouts taking the smallest value per tool', () => {
133
+ const compiled = compileHarness([
134
+ {
135
+ source: 'platform',
136
+ settings: { tools: { timeouts: { skill_hub_execute: 120_000, skill_hub_report: 60_000 } } },
137
+ },
138
+ {
139
+ source: 'run',
140
+ settings: { tools: { timeouts: { skill_hub_execute: 30_000 } } },
141
+ },
142
+ ]);
143
+
144
+ expect(compiled.tools.timeouts).toEqual({ skill_hub_execute: 30_000, skill_hub_report: 60_000 });
145
+ });
146
+
147
+ it('compiles spill budget, redaction and sharing with safety-first merging', () => {
148
+ const compiled = compileHarness([
149
+ {
150
+ source: 'platform',
151
+ settings: {
152
+ context: { spill: { maxInlineBytes: 100_000 } },
153
+ observability: { redactSecrets: false, sharing: 'full' },
154
+ },
155
+ },
156
+ {
157
+ source: 'run',
158
+ settings: {
159
+ context: { spill: { maxInlineBytes: 40_000 } },
160
+ observability: { sharing: 'feedback-only' },
161
+ },
162
+ },
163
+ ]);
164
+
165
+ expect(compiled.context.spill.maxInlineBytes).toBe(40_000);
166
+ // Redaction is a union of concerns: any layer demanding it wins.
167
+ expect(compiled.observability.redactSecrets).toBe(true);
168
+ expect(compiled.observability.sharing).toBe('feedback-only');
169
+ });
170
+
171
+ it('defaults spill to null and sharing to full when no layer sets them', () => {
172
+ const compiled = compileHarness([{ source: 'default', settings: {} }]);
173
+
174
+ expect(compiled.context.spill.maxInlineBytes).toBeNull();
175
+ expect(compiled.tools.timeouts).toEqual({});
176
+ expect(compiled.observability.redactSecrets).toBe(true);
177
+ expect(compiled.observability.sharing).toBe('full');
178
+ });
179
+
180
+ it('disabled sharing outranks every other sharing level', () => {
181
+ const compiled = compileHarness([
182
+ { source: 'a', settings: { observability: { sharing: 'full' } } },
183
+ { source: 'b', settings: { observability: { sharing: 'disabled' } } },
184
+ ]);
185
+
186
+ expect(compiled.observability.sharing).toBe('disabled');
187
+ });
188
+
189
+ it('intersects escalatable tools across layers like allow', () => {
190
+ const compiled = compileHarness([
191
+ {
192
+ source: 'platform',
193
+ settings: { tools: { escalate: ['deployService', 'runShell', 'resetIndex'] } },
194
+ },
195
+ {
196
+ source: 'pattern',
197
+ settings: { tools: { escalate: ['deployService', 'runShell'] } },
198
+ },
199
+ ]);
200
+
201
+ expect(compiled.tools.escalate).toEqual(['deployService', 'runShell']);
202
+ // Escalatable tools are never granted outright: every call still resolves to ask.
203
+ expect(decideTool(compiled, 'deployService')).toBe('ask');
204
+ });
205
+
206
+ it('treats an empty escalate list as no opinion', () => {
207
+ const compiled = compileHarness([
208
+ { source: 'platform', settings: { tools: { escalate: ['deployService'] } } },
209
+ { source: 'pattern', settings: {} },
210
+ ]);
211
+
212
+ expect(compiled.tools.escalate).toEqual(['deployService']);
213
+ });
131
214
  });
@@ -4,6 +4,11 @@ import { HarnessProfileService } from '../services/HarnessProfileService';
4
4
 
5
5
  type Row = Record<string, unknown>;
6
6
 
7
+ function readField(record: unknown, key: string) {
8
+ const model = record as { get?: (name: string) => unknown; [key: string]: unknown };
9
+ return typeof model?.get === 'function' ? model.get(key) : model?.[key];
10
+ }
11
+
7
12
  function matches(row: Row, filter: Row) {
8
13
  return Object.entries(filter).every(([key, value]) => row[key] === value);
9
14
  }
@@ -113,4 +118,50 @@ describe('HarnessProfileService', () => {
113
118
  await expect(service.createDraft({ profileId: 1, settings: { limits: { timeoutMs: -1 } } })).rejects.toThrow();
114
119
  expect(versions.rows).toHaveLength(0);
115
120
  });
121
+
122
+ it('saveDraft keeps a single open draft and starts a new version after publish', async () => {
123
+ const { versions, service } = createService();
124
+
125
+ const first = await service.saveDraft({ profileId: 1, settings: { memory: { maxChars: 1000 } } });
126
+ expect(first).toMatchObject({ version: 1, status: 'draft' });
127
+
128
+ // The open draft is updated in place instead of accumulating another draft row.
129
+ const updated = await service.saveDraft({ profileId: 1, settings: { memory: { maxChars: 2000 } } });
130
+ expect(updated.id).toBe(first.id);
131
+ expect(updated.settings.memory.maxChars).toBe(2000);
132
+ expect(versions.rows).toHaveLength(1);
133
+
134
+ await service.publish(first.id, 9);
135
+ const next = await service.saveDraft({ profileId: 1, settings: { memory: { maxChars: 3000 } } });
136
+ expect(next).toMatchObject({ version: 2, status: 'draft' });
137
+ expect(versions.rows).toHaveLength(2);
138
+ });
139
+
140
+ it('createProfile publishes the first version atomically with the profile row', async () => {
141
+ const { profiles, service } = createService();
142
+
143
+ const { profile, version } = await service.createProfile({
144
+ tag: 'strict',
145
+ title: 'Strict policy',
146
+ settings: { memory: { scopes: ['public'] } },
147
+ publishedById: 9,
148
+ });
149
+
150
+ expect(readField(profile, 'tag')).toBe('strict');
151
+ expect(version).toMatchObject({ version: 1, status: 'published', publishedById: 9 });
152
+ const row = profiles.rows.find((item) => item.tag === 'strict');
153
+ expect(row?.currentVersionId).toBe(version.id);
154
+
155
+ // The published version is resolvable by tag immediately after create.
156
+ const published = await service.getPublishedByTag('strict');
157
+ expect(published?.version).toBe(1);
158
+ expect(published?.settings.memory.scopes).toEqual(['public']);
159
+ });
160
+
161
+ it('rejects createProfile when settings fail validation', async () => {
162
+ const { profiles, service } = createService();
163
+
164
+ await expect(service.createProfile({ tag: 'broken', settings: { limits: { timeoutMs: -1 } } })).rejects.toThrow();
165
+ expect(profiles.rows.find((item) => item.tag === 'broken')).toBeUndefined();
166
+ });
116
167
  });