plugin-agent-orchestrator 1.1.5 → 1.1.7

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 (69) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/client-v2/index.js +1 -1
  3. package/dist/externalVersion.js +7 -7
  4. package/dist/server/collections/agent-loop-runs.js +6 -0
  5. package/dist/server/collections/skill-metrics.js +66 -0
  6. package/dist/server/plugin.js +91 -2
  7. package/dist/server/resources/agent-loop-events-stream.js +1 -0
  8. package/dist/server/resources/agent-loop.js +1 -1
  9. package/dist/server/services/DurableCircuitBreakerService.js +9 -12
  10. package/dist/server/services/ExecutionSpanService.js +8 -3
  11. package/dist/server/services/HarnessProfileService.js +23 -26
  12. package/dist/server/services/LoopBudgetService.js +36 -39
  13. package/dist/server/services/LoopControlService.js +8 -11
  14. package/dist/server/services/LoopPatternSchema.js +51 -17
  15. package/dist/server/services/LoopPatternService.js +31 -11
  16. package/dist/server/services/LoopRunRepository.js +2 -5
  17. package/dist/server/services/LoopRunStateMachine.js +31 -34
  18. package/dist/server/services/LoopSchedulerService.js +4 -7
  19. package/dist/server/services/LoopTriggerService.js +11 -6
  20. package/dist/server/services/LoopWorkerService.js +88 -22
  21. package/dist/server/services/PathLockService.js +19 -22
  22. package/dist/server/services/PluginAiRuntimeAdapter.js +51 -8
  23. package/dist/server/services/RunEventBus.js +14 -2
  24. package/dist/server/services/SkillAccessService.js +50 -1
  25. package/dist/server/services/TokenTracker.js +17 -1
  26. package/dist/server/services/ToolLoopDetectionService.js +14 -17
  27. package/dist/server/services/VerificationService.js +47 -16
  28. package/dist/server/services/harness-runtime-policy.js +7 -12
  29. package/dist/server/skill-hub/plugin.js +34 -27
  30. package/dist/server/utils/ha-lock.js +73 -0
  31. package/dist/server/utils/loop-pattern-context.js +42 -5
  32. package/dist/server/utils/record-utils.js +44 -0
  33. package/package.json +1 -1
  34. package/src/client/plugin.tsx +1 -1
  35. package/src/client-v2/plugin.tsx +14 -13
  36. package/src/server/__tests__/tool-loop-detection.test.ts +1 -0
  37. package/src/server/collections/agent-loop-runs.ts +7 -0
  38. package/src/server/collections/skill-metrics.ts +36 -0
  39. package/src/server/plugin.ts +117 -1
  40. package/src/server/resources/agent-loop-events-stream.ts +108 -105
  41. package/src/server/resources/agent-loop.ts +1 -1
  42. package/src/server/resources/tracing.ts +267 -266
  43. package/src/server/services/DurableCircuitBreakerService.ts +235 -239
  44. package/src/server/services/ExecutionSpanService.ts +37 -12
  45. package/src/server/services/HarnessProfileService.ts +1 -5
  46. package/src/server/services/LoopBudgetService.ts +271 -275
  47. package/src/server/services/LoopControlService.ts +120 -124
  48. package/src/server/services/LoopPatternSchema.ts +60 -14
  49. package/src/server/services/LoopPatternService.ts +171 -143
  50. package/src/server/services/LoopRunRepository.ts +1 -5
  51. package/src/server/services/LoopRunStateMachine.ts +1 -5
  52. package/src/server/services/LoopSchedulerService.ts +195 -199
  53. package/src/server/services/LoopTriggerService.ts +7 -5
  54. package/src/server/services/LoopWorkerService.ts +102 -12
  55. package/src/server/services/PathLockService.ts +317 -321
  56. package/src/server/services/PluginAiRuntimeAdapter.ts +59 -4
  57. package/src/server/services/RunEventBus.ts +13 -0
  58. package/src/server/services/SkillAccessService.ts +80 -5
  59. package/src/server/services/TokenTracker.ts +59 -7
  60. package/src/server/services/ToolLoopDetectionService.ts +8 -11
  61. package/src/server/services/VerificationSchema.ts +31 -31
  62. package/src/server/services/VerificationService.ts +60 -11
  63. package/src/server/services/harness-runtime-policy.ts +2 -9
  64. package/src/server/skill-hub/plugin.ts +36 -28
  65. package/src/server/types.ts +5 -39
  66. package/src/server/utils/ensure-indexes.ts +96 -96
  67. package/src/server/utils/ha-lock.ts +80 -0
  68. package/src/server/utils/loop-pattern-context.ts +84 -20
  69. package/src/server/utils/record-utils.ts +19 -0
@@ -29,10 +29,7 @@ __export(LoopBudgetService_exports, {
29
29
  LoopBudgetService: () => LoopBudgetService
30
30
  });
31
31
  module.exports = __toCommonJS(LoopBudgetService_exports);
32
- function read(record, key) {
33
- const model = record;
34
- return typeof model.get === "function" ? model.get(key) : record[key];
35
- }
32
+ var import_record_utils = require("../utils/record-utils");
36
33
  function storedCount(value, label) {
37
34
  if (value === null || value === void 0) return 0;
38
35
  const parsed = Number(value);
@@ -112,8 +109,8 @@ class LoopBudgetService {
112
109
  lock: transaction.LOCK.UPDATE
113
110
  });
114
111
  if (!control) throw new Error("Global Loop Control settings were not found.");
115
- if (String(read(control, "state")) !== "running") {
116
- throw new Error(String(read(control, "reason") || "Loop Control Plane is not running."));
112
+ if (String((0, import_record_utils.read)(control, "state")) !== "running") {
113
+ throw new Error(String((0, import_record_utils.read)(control, "reason") || "Loop Control Plane is not running."));
117
114
  }
118
115
  const runs = this.database.getRepository("agentLoopRuns");
119
116
  const run = await runs.findOne({
@@ -122,10 +119,10 @@ class LoopBudgetService {
122
119
  lock: transaction.LOCK.UPDATE
123
120
  });
124
121
  if (!run) throw new Error(`Agent loop run ${input.runId} was not found.`);
125
- if (String(read(run, "runtimeVersion")) !== "control-plane-v2") {
122
+ if (String((0, import_record_utils.read)(run, "runtimeVersion")) !== "control-plane-v2") {
126
123
  throw new Error("Historical plan-era runs cannot consume Loop Control Plane budgets.");
127
124
  }
128
- if (Number(read(run, "patternId")) !== input.patternId) {
125
+ if (Number((0, import_record_utils.read)(run, "patternId")) !== input.patternId) {
129
126
  throw new Error(`Agent loop run ${input.runId} does not belong to pattern ${input.patternId}.`);
130
127
  }
131
128
  const buckets = this.database.getRepository("agentLoopUsageBuckets");
@@ -151,27 +148,27 @@ class LoopBudgetService {
151
148
  await runs.update({
152
149
  filterByTk: input.runId,
153
150
  values: {
154
- invocationCount: storedCount(read(run, "invocationCount"), "Run invocation") + delta.invocations,
155
- toolCallCount: storedCount(read(run, "toolCallCount"), "Run tool call") + delta.toolCalls,
156
- delegationCount: storedCount(read(run, "delegationCount"), "Run delegation") + delta.delegations,
157
- verificationCount: storedCount(read(run, "verificationCount"), "Run verification") + delta.verifications,
158
- totalInputTokens: storedCount(read(run, "totalInputTokens"), "Run input token") + delta.inputTokens,
159
- totalOutputTokens: storedCount(read(run, "totalOutputTokens"), "Run output token") + delta.outputTokens,
160
- totalTokens: storedCount(read(run, "totalTokens"), "Run total token") + delta.totalTokens,
161
- totalCost: storedCost(read(run, "totalCost"), "Run cost") + delta.cost
151
+ invocationCount: storedCount((0, import_record_utils.read)(run, "invocationCount"), "Run invocation") + delta.invocations,
152
+ toolCallCount: storedCount((0, import_record_utils.read)(run, "toolCallCount"), "Run tool call") + delta.toolCalls,
153
+ delegationCount: storedCount((0, import_record_utils.read)(run, "delegationCount"), "Run delegation") + delta.delegations,
154
+ verificationCount: storedCount((0, import_record_utils.read)(run, "verificationCount"), "Run verification") + delta.verifications,
155
+ totalInputTokens: storedCount((0, import_record_utils.read)(run, "totalInputTokens"), "Run input token") + delta.inputTokens,
156
+ totalOutputTokens: storedCount((0, import_record_utils.read)(run, "totalOutputTokens"), "Run output token") + delta.outputTokens,
157
+ totalTokens: storedCount((0, import_record_utils.read)(run, "totalTokens"), "Run total token") + delta.totalTokens,
158
+ totalCost: storedCost((0, import_record_utils.read)(run, "totalCost"), "Run cost") + delta.cost
162
159
  },
163
160
  transaction
164
161
  });
165
162
  await buckets.update({
166
- filterByTk: read(bucket, "id"),
163
+ filterByTk: (0, import_record_utils.read)(bucket, "id"),
167
164
  values: {
168
- invocationCount: storedCount(read(bucket, "invocationCount"), "Daily invocation") + delta.invocations,
169
- toolCallCount: storedCount(read(bucket, "toolCallCount"), "Daily tool call") + delta.toolCalls,
170
- delegationCount: storedCount(read(bucket, "delegationCount"), "Daily delegation") + delta.delegations,
171
- inputTokens: storedCount(read(bucket, "inputTokens"), "Daily input token") + delta.inputTokens,
172
- outputTokens: storedCount(read(bucket, "outputTokens"), "Daily output token") + delta.outputTokens,
173
- totalTokens: storedCount(read(bucket, "totalTokens"), "Daily total token") + delta.totalTokens,
174
- totalCost: storedCost(read(bucket, "totalCost"), "Daily cost") + delta.cost
165
+ invocationCount: storedCount((0, import_record_utils.read)(bucket, "invocationCount"), "Daily invocation") + delta.invocations,
166
+ toolCallCount: storedCount((0, import_record_utils.read)(bucket, "toolCallCount"), "Daily tool call") + delta.toolCalls,
167
+ delegationCount: storedCount((0, import_record_utils.read)(bucket, "delegationCount"), "Daily delegation") + delta.delegations,
168
+ inputTokens: storedCount((0, import_record_utils.read)(bucket, "inputTokens"), "Daily input token") + delta.inputTokens,
169
+ outputTokens: storedCount((0, import_record_utils.read)(bucket, "outputTokens"), "Daily output token") + delta.outputTokens,
170
+ totalTokens: storedCount((0, import_record_utils.read)(bucket, "totalTokens"), "Daily total token") + delta.totalTokens,
171
+ totalCost: storedCost((0, import_record_utils.read)(bucket, "totalCost"), "Daily cost") + delta.cost
175
172
  },
176
173
  transaction
177
174
  });
@@ -181,84 +178,84 @@ class LoopBudgetService {
181
178
  assertRunBudget(run, policy, delta) {
182
179
  const limits = policy.perRun;
183
180
  exceeds(
184
- storedCount(read(run, "invocationCount"), "Run invocation"),
181
+ storedCount((0, import_record_utils.read)(run, "invocationCount"), "Run invocation"),
185
182
  delta.invocations,
186
183
  limits.maxInvocations,
187
184
  "Per-run invocation"
188
185
  );
189
186
  exceeds(
190
- storedCount(read(run, "toolCallCount"), "Run tool call"),
187
+ storedCount((0, import_record_utils.read)(run, "toolCallCount"), "Run tool call"),
191
188
  delta.toolCalls,
192
189
  limits.maxToolCalls,
193
190
  "Per-run tool call"
194
191
  );
195
192
  exceeds(
196
- storedCount(read(run, "delegationCount"), "Run delegation"),
193
+ storedCount((0, import_record_utils.read)(run, "delegationCount"), "Run delegation"),
197
194
  delta.delegations,
198
195
  limits.maxDelegations,
199
196
  "Per-run delegation"
200
197
  );
201
198
  exceeds(
202
- storedCount(read(run, "verificationCount"), "Run verification"),
199
+ storedCount((0, import_record_utils.read)(run, "verificationCount"), "Run verification"),
203
200
  delta.verifications,
204
201
  limits.maxVerifications,
205
202
  "Per-run verification"
206
203
  );
207
204
  exceeds(
208
- storedCount(read(run, "totalTokens"), "Run total token"),
205
+ storedCount((0, import_record_utils.read)(run, "totalTokens"), "Run total token"),
209
206
  delta.totalTokens,
210
207
  limits.maxTokens,
211
208
  "Per-run token"
212
209
  );
213
- exceeds(storedCost(read(run, "totalCost"), "Run cost"), delta.cost, limits.maxCost, "Per-run cost");
210
+ exceeds(storedCost((0, import_record_utils.read)(run, "totalCost"), "Run cost"), delta.cost, limits.maxCost, "Per-run cost");
214
211
  }
215
212
  assertDailyBudget(bucket, policy, delta) {
216
213
  const limits = policy.daily;
217
214
  exceeds(
218
- storedCount(read(bucket, "invocationCount"), "Daily invocation"),
215
+ storedCount((0, import_record_utils.read)(bucket, "invocationCount"), "Daily invocation"),
219
216
  delta.invocations,
220
217
  limits.maxInvocations,
221
218
  "Daily invocation"
222
219
  );
223
220
  exceeds(
224
- storedCount(read(bucket, "toolCallCount"), "Daily tool call"),
221
+ storedCount((0, import_record_utils.read)(bucket, "toolCallCount"), "Daily tool call"),
225
222
  delta.toolCalls,
226
223
  limits.maxToolCalls,
227
224
  "Daily tool call"
228
225
  );
229
226
  exceeds(
230
- storedCount(read(bucket, "delegationCount"), "Daily delegation"),
227
+ storedCount((0, import_record_utils.read)(bucket, "delegationCount"), "Daily delegation"),
231
228
  delta.delegations,
232
229
  limits.maxDelegations,
233
230
  "Daily delegation"
234
231
  );
235
232
  exceeds(
236
- storedCount(read(bucket, "totalTokens"), "Daily total token"),
233
+ storedCount((0, import_record_utils.read)(bucket, "totalTokens"), "Daily total token"),
237
234
  delta.totalTokens,
238
235
  limits.maxTokens,
239
236
  "Daily token"
240
237
  );
241
- exceeds(storedCost(read(bucket, "totalCost"), "Daily cost"), delta.cost, limits.maxCost, "Daily cost");
238
+ exceeds(storedCost((0, import_record_utils.read)(bucket, "totalCost"), "Daily cost"), delta.cost, limits.maxCost, "Daily cost");
242
239
  }
243
240
  assertGlobalDailyBudget(buckets, control, delta) {
244
241
  const currentTokens = buckets.reduce(
245
- (total, bucket) => total + storedCount(read(bucket, "totalTokens"), "Daily total token"),
242
+ (total, bucket) => total + storedCount((0, import_record_utils.read)(bucket, "totalTokens"), "Daily total token"),
246
243
  0
247
244
  );
248
245
  const currentCost = buckets.reduce(
249
- (total, bucket) => total + storedCost(read(bucket, "totalCost"), "Daily cost"),
246
+ (total, bucket) => total + storedCost((0, import_record_utils.read)(bucket, "totalCost"), "Daily cost"),
250
247
  0
251
248
  );
252
249
  exceeds(
253
250
  currentTokens,
254
251
  delta.totalTokens,
255
- storedLimit(read(control, "dailyMaxTokens"), "Global daily token"),
252
+ storedLimit((0, import_record_utils.read)(control, "dailyMaxTokens"), "Global daily token"),
256
253
  "Global daily token"
257
254
  );
258
255
  exceeds(
259
256
  currentCost,
260
257
  delta.cost,
261
- storedLimit(read(control, "dailyMaxCost"), "Global daily cost"),
258
+ storedLimit((0, import_record_utils.read)(control, "dailyMaxCost"), "Global daily cost"),
262
259
  "Global daily cost"
263
260
  );
264
261
  }
@@ -29,10 +29,7 @@ __export(LoopControlService_exports, {
29
29
  LoopControlService: () => LoopControlService
30
30
  });
31
31
  module.exports = __toCommonJS(LoopControlService_exports);
32
- function read(record, key) {
33
- const model = record;
34
- return typeof model.get === "function" ? model.get(key) : record[key];
35
- }
32
+ var import_record_utils = require("../utils/record-utils");
36
33
  function optionalLimit(value, label) {
37
34
  if (value === null || value === void 0) return null;
38
35
  const parsed = Number(value);
@@ -40,9 +37,9 @@ function optionalLimit(value, label) {
40
37
  return parsed;
41
38
  }
42
39
  function snapshot(record) {
43
- const id = Number(read(record, "id"));
44
- const state = read(record, "state");
45
- const maxConcurrency = Number(read(record, "globalMaxConcurrency"));
40
+ const id = Number((0, import_record_utils.read)(record, "id"));
41
+ const state = (0, import_record_utils.read)(record, "state");
42
+ const maxConcurrency = Number((0, import_record_utils.read)(record, "globalMaxConcurrency"));
46
43
  if (!Number.isSafeInteger(id) || id <= 0) throw new Error("Global Loop Control settings have an invalid identifier.");
47
44
  if (state !== "running" && state !== "paused" && state !== "killed") {
48
45
  throw new Error("Global Loop Control state is invalid.");
@@ -52,12 +49,12 @@ function snapshot(record) {
52
49
  }
53
50
  return {
54
51
  id,
55
- acceptNewRuns: read(record, "acceptNewRuns") === true,
52
+ acceptNewRuns: (0, import_record_utils.read)(record, "acceptNewRuns") === true,
56
53
  state,
57
- reason: typeof read(record, "reason") === "string" ? String(read(record, "reason")) : "",
54
+ reason: typeof (0, import_record_utils.read)(record, "reason") === "string" ? String((0, import_record_utils.read)(record, "reason")) : "",
58
55
  globalMaxConcurrency: maxConcurrency,
59
- dailyMaxTokens: optionalLimit(read(record, "dailyMaxTokens"), "Global daily token limit"),
60
- dailyMaxCost: optionalLimit(read(record, "dailyMaxCost"), "Global daily cost limit")
56
+ dailyMaxTokens: optionalLimit((0, import_record_utils.read)(record, "dailyMaxTokens"), "Global daily token limit"),
57
+ dailyMaxCost: optionalLimit((0, import_record_utils.read)(record, "dailyMaxCost"), "Global daily cost limit")
61
58
  };
62
59
  }
63
60
  class LoopControlService {
@@ -71,6 +71,14 @@ const loopPatternPolicySchema = import_zod.z.object({
71
71
  }).default({}),
72
72
  verification: import_zod.z.object({
73
73
  requiredChecks: import_zod.z.array(import_zod.z.string().min(1)).min(1).default(["goal"]),
74
+ // Risk-aware checks that are added to the verifier prompt based on runtime context
75
+ // (e.g. how many files the run touched, whether core paths were affected).
76
+ dynamicChecks: import_zod.z.object({
77
+ codeChangeThreshold: import_zod.z.number().int().nonnegative().default(10),
78
+ riskPathPatterns: import_zod.z.array(import_zod.z.string().min(1)).default([]),
79
+ requireSecurityReview: import_zod.z.boolean().default(false),
80
+ requirePerformanceReview: import_zod.z.boolean().default(false)
81
+ }).optional(),
74
82
  maxAttempts: import_zod.z.number().int().positive().default(2)
75
83
  }).default({}),
76
84
  loopDetection: import_zod.z.object({
@@ -111,26 +119,52 @@ const loopPatternSchema = import_zod.z.object({
111
119
  repositoryRoot: import_zod.z.string().trim().max(1e3).nullable().default(null),
112
120
  baseRef: import_zod.z.string().trim().min(1).max(200).default("main"),
113
121
  actingOn: import_zod.z.array(import_zod.z.string().trim().min(1)).default([]),
114
- policy: loopPatternPolicySchema.default({})
122
+ policy: loopPatternPolicySchema.default({}),
123
+ // Dynamic role resolution strategies
124
+ roleResolution: import_zod.z.object({
125
+ enabled: import_zod.z.boolean().default(false),
126
+ leaderStrategy: import_zod.z.enum(["fixed", "team-lead", "round-robin", "skill-match"]).default("fixed"),
127
+ makerStrategy: import_zod.z.enum(["fixed", "team-members", "auto-assign"]).default("fixed"),
128
+ verifierStrategy: import_zod.z.enum(["fixed", "independent-only"]).default("fixed"),
129
+ teamBindings: import_zod.z.array(
130
+ import_zod.z.object({
131
+ teamKey: import_zod.z.string().min(1),
132
+ role: import_zod.z.enum(["leader", "maker", "verifier"]),
133
+ employeeUsernames: import_zod.z.array(import_zod.z.string().min(1)).default([])
134
+ })
135
+ ).default([]),
136
+ fallbackBehavior: import_zod.z.enum(["skip", "fail", "assign-admin"]).default("fail")
137
+ }).optional()
115
138
  }).superRefine((pattern, context) => {
116
- var _a;
117
- const makers = new Set(pattern.makerUsernames);
118
- if (pattern.verifierUsername === pattern.leaderUsername || makers.has(pattern.verifierUsername)) {
119
- context.addIssue({
120
- code: import_zod.z.ZodIssueCode.custom,
121
- path: ["verifierUsername"],
122
- message: "Verifier must be different from the leader and every maker."
123
- });
124
- }
125
- if (makers.size !== pattern.makerUsernames.length) {
126
- context.addIssue({
127
- code: import_zod.z.ZodIssueCode.custom,
128
- path: ["makerUsernames"],
129
- message: "Maker usernames must be unique."
130
- });
139
+ var _a, _b, _c;
140
+ if (((_a = pattern.roleResolution) == null ? void 0 : _a.enabled) === true) {
141
+ const hasStrategy = pattern.roleResolution.leaderStrategy !== "fixed" || pattern.roleResolution.makerStrategy !== "fixed" || pattern.roleResolution.verifierStrategy !== "fixed";
142
+ if (!hasStrategy && !((_b = pattern.roleResolution.teamBindings) == null ? void 0 : _b.length)) {
143
+ context.addIssue({
144
+ code: import_zod.z.ZodIssueCode.custom,
145
+ path: ["roleResolution"],
146
+ message: "Dynamic role resolution requires at least one non-fixed strategy or team bindings."
147
+ });
148
+ }
149
+ } else {
150
+ const makers = new Set(pattern.makerUsernames);
151
+ if (pattern.verifierUsername === pattern.leaderUsername || makers.has(pattern.verifierUsername)) {
152
+ context.addIssue({
153
+ code: import_zod.z.ZodIssueCode.custom,
154
+ path: ["verifierUsername"],
155
+ message: "Verifier must be different from the leader and every maker."
156
+ });
157
+ }
158
+ if (makers.size !== pattern.makerUsernames.length) {
159
+ context.addIssue({
160
+ code: import_zod.z.ZodIssueCode.custom,
161
+ path: ["makerUsernames"],
162
+ message: "Maker usernames must be unique."
163
+ });
164
+ }
131
165
  }
132
166
  if (pattern.triggerType === "cron") {
133
- const parts = ((_a = pattern.cronExpression) == null ? void 0 : _a.split(/\s+/).filter(Boolean)) || [];
167
+ const parts = ((_c = pattern.cronExpression) == null ? void 0 : _c.split(/\s+/).filter(Boolean)) || [];
134
168
  if (parts.length !== 5 && parts.length !== 6) {
135
169
  context.addIssue({
136
170
  code: import_zod.z.ZodIssueCode.custom,
@@ -32,6 +32,7 @@ module.exports = __toCommonJS(LoopPatternService_exports);
32
32
  var import_HarnessCompiler = require("./HarnessCompiler");
33
33
  var import_HarnessProfileService = require("./HarnessProfileService");
34
34
  var import_LoopPatternSchema = require("./LoopPatternSchema");
35
+ var import_record_utils = require("../utils/record-utils");
35
36
  const platformHarness = {
36
37
  tools: {},
37
38
  memory: { maxChars: 2e4 },
@@ -40,10 +41,6 @@ const platformHarness = {
40
41
  isolation: { networkAccess: "allow" },
41
42
  observability: { tracingRetentionDays: 3650 }
42
43
  };
43
- function read(record, key) {
44
- const model = record;
45
- return typeof model.get === "function" ? model.get(key) : record[key];
46
- }
47
44
  function toPlain(record) {
48
45
  return typeof record.toJSON === "function" ? record.toJSON() : record;
49
46
  }
@@ -58,7 +55,7 @@ class LoopPatternService {
58
55
  async get(patternId) {
59
56
  const record = await this.database.getRepository("agentLoopPatterns").findOne({ filterByTk: patternId });
60
57
  if (!record) throw new Error(`Loop pattern ${patternId} was not found.`);
61
- return { id: Number(read(record, "id")), pattern: (0, import_LoopPatternSchema.parseLoopPattern)(toPlain(record)) };
58
+ return { id: Number((0, import_record_utils.read)(record, "id")), pattern: (0, import_LoopPatternSchema.parseLoopPattern)(toPlain(record)) };
62
59
  }
63
60
  async validate(value) {
64
61
  const pattern = (0, import_LoopPatternSchema.parseLoopPattern)(value);
@@ -70,13 +67,26 @@ class LoopPatternService {
70
67
  if (!pattern.enabled) throw new Error(`Loop pattern ${pattern.key} is disabled.`);
71
68
  await this.assertCapabilities(pattern);
72
69
  const makerUsernames = pattern.makerUsernames.length ? pattern.makerUsernames : [pattern.leaderUsername];
70
+ const profileCache = /* @__PURE__ */ new Map();
73
71
  const [leaderHarness, verifierHarness, ...makerSnapshots] = await Promise.all([
74
- this.compileRole(pattern.leaderHarnessTag, pattern.leaderUsername, pattern.policy.harness, perRunHarness),
75
- this.compileRole(pattern.verifierHarnessTag, pattern.verifierUsername, pattern.policy.harness, perRunHarness),
72
+ this.compileRole(
73
+ pattern.leaderHarnessTag,
74
+ pattern.leaderUsername,
75
+ pattern.policy.harness,
76
+ perRunHarness,
77
+ profileCache
78
+ ),
79
+ this.compileRole(
80
+ pattern.verifierHarnessTag,
81
+ pattern.verifierUsername,
82
+ pattern.policy.harness,
83
+ perRunHarness,
84
+ profileCache
85
+ ),
76
86
  // Every maker gets its own snapshot: employee-level harness overrides differ per username,
77
87
  // so reusing the first maker's compilation would grant or deny the wrong tools.
78
88
  ...makerUsernames.map(
79
- (username) => this.compileRole(pattern.makerHarnessTag, username, pattern.policy.harness, perRunHarness)
89
+ (username) => this.compileRole(pattern.makerHarnessTag, username, pattern.policy.harness, perRunHarness, profileCache)
80
90
  )
81
91
  ]);
82
92
  const makerHarnesses = Object.fromEntries(
@@ -99,9 +109,19 @@ class LoopPatternService {
99
109
  policy: structuredClone(pattern.policy)
100
110
  };
101
111
  }
102
- async compileRole(tag, username, patternHarness, perRunHarness) {
103
- const published = await this.harnessProfiles.getPublishedByTag(tag);
104
- if (!published) throw new Error(`Harness profile "${tag}" has no published version.`);
112
+ async compileRole(tag, username, patternHarness, perRunHarness, profileCache) {
113
+ let published = profileCache == null ? void 0 : profileCache.get(tag);
114
+ if (!published) {
115
+ const fetched = await this.harnessProfiles.getPublishedByTag(tag);
116
+ if (!fetched) throw new Error(`Harness profile "${tag}" has no published version.`);
117
+ published = {
118
+ id: Number(fetched.id),
119
+ version: Number(fetched.version),
120
+ schemaVersion: Number(fetched.schemaVersion),
121
+ settings: fetched.settings
122
+ };
123
+ profileCache == null ? void 0 : profileCache.set(tag, published);
124
+ }
105
125
  const employeeHarness = await this.resolveEmployeeHarness(username);
106
126
  const layers = [
107
127
  { source: "platform", settings: platformHarness },
@@ -31,6 +31,7 @@ __export(LoopRunRepository_exports, {
31
31
  });
32
32
  module.exports = __toCommonJS(LoopRunRepository_exports);
33
33
  var import_RunEventBus = require("./RunEventBus");
34
+ var import_record_utils = require("../utils/record-utils");
34
35
  class LoopRunAccessError extends Error {
35
36
  constructor(status, message) {
36
37
  super(message);
@@ -38,10 +39,6 @@ class LoopRunAccessError extends Error {
38
39
  this.name = "LoopRunAccessError";
39
40
  }
40
41
  }
41
- function read(record, key) {
42
- const model = record;
43
- return typeof model.get === "function" ? model.get(key) : record[key];
44
- }
45
42
  function plain(record) {
46
43
  return typeof record.toJSON === "function" ? record.toJSON() : structuredClone(record);
47
44
  }
@@ -115,7 +112,7 @@ class LoopRunRepository {
115
112
  for (let page = 1; ; page += 1) {
116
113
  const rows = await repository.find({ filter, fields: ["id"], sort: ["id"], page, pageSize });
117
114
  for (const row of rows) {
118
- ids.push(positiveId(read(row, "id"), "Agent loop run"));
115
+ ids.push(positiveId((0, import_record_utils.read)(row, "id"), "Agent loop run"));
119
116
  }
120
117
  if (rows.length < pageSize) break;
121
118
  }
@@ -36,6 +36,7 @@ var import_LoopControlService = require("./LoopControlService");
36
36
  var import_LoopPatternSchema = require("./LoopPatternSchema");
37
37
  var import_RunEventBus = require("./RunEventBus");
38
38
  var import_VerificationSchema = require("./VerificationSchema");
39
+ var import_record_utils = require("../utils/record-utils");
39
40
  const loopRunStatuses = [
40
41
  "queued",
41
42
  "preparing",
@@ -101,10 +102,6 @@ function assertRunTransition(input) {
101
102
  }
102
103
  }
103
104
  }
104
- function read(record, key) {
105
- const model = record;
106
- return typeof model.get === "function" ? model.get(key) : record[key];
107
- }
108
105
  function asStatus(value) {
109
106
  if (typeof value === "string" && loopRunStatuses.includes(value)) {
110
107
  return value;
@@ -122,11 +119,11 @@ function asDate(value) {
122
119
  return null;
123
120
  }
124
121
  function leaseIsExpired(record, now) {
125
- const lockedUntil = asDate(read(record, "lockedUntil"));
122
+ const lockedUntil = asDate((0, import_record_utils.read)(record, "lockedUntil"));
126
123
  return !lockedUntil || lockedUntil.getTime() <= now.getTime();
127
124
  }
128
125
  function leaseOwner(record) {
129
- const owner = read(record, "lockedBy");
126
+ const owner = (0, import_record_utils.read)(record, "lockedBy");
130
127
  return typeof owner === "string" && owner.trim() ? owner : null;
131
128
  }
132
129
  function leaseIsReclaimable(record, now) {
@@ -164,12 +161,12 @@ class LoopRunStateMachine {
164
161
  });
165
162
  for (const candidate of staleActive) {
166
163
  if (!leaseIsReclaimable(candidate, now)) continue;
167
- const runId = asPositiveInteger(read(candidate, "id"), "Run identifier");
168
- const from = asStatus(read(candidate, "status"));
164
+ const runId = asPositiveInteger((0, import_record_utils.read)(candidate, "id"), "Run identifier");
165
+ const from = asStatus((0, import_record_utils.read)(candidate, "status"));
169
166
  assertRunTransition({
170
167
  from,
171
168
  to: "queued",
172
- runtimeVersion: String(read(candidate, "runtimeVersion") || "")
169
+ runtimeVersion: String((0, import_record_utils.read)(candidate, "runtimeVersion") || "")
173
170
  });
174
171
  await runs.update({
175
172
  filterByTk: runId,
@@ -183,10 +180,10 @@ class LoopRunStateMachine {
183
180
  title: "Worker lease expired",
184
181
  content: `Run returned to the queue after its ${from} worker lease expired.`,
185
182
  status: "queued",
186
- payload: { from, previousOwner: read(candidate, "lockedBy") ?? null },
183
+ payload: { from, previousOwner: (0, import_record_utils.read)(candidate, "lockedBy") ?? null },
187
184
  actorType: "system",
188
185
  actorIdentity: normalizedWorkerId,
189
- correlationKey: `lease-expired:${runId}:${String(read(candidate, "lockedBy") || "")}`,
186
+ correlationKey: `lease-expired:${runId}:${String((0, import_record_utils.read)(candidate, "lockedBy") || "")}`,
190
187
  createdAt: now
191
188
  },
192
189
  transaction
@@ -206,8 +203,8 @@ class LoopRunStateMachine {
206
203
  });
207
204
  const blockedEvents = [...reclaimedEvents];
208
205
  for (const candidate of candidates) {
209
- const runId = asPositiveInteger(read(candidate, "id"), "Run identifier");
210
- const patternId = Number(read(candidate, "patternId"));
206
+ const runId = asPositiveInteger((0, import_record_utils.read)(candidate, "id"), "Run identifier");
207
+ const patternId = Number((0, import_record_utils.read)(candidate, "patternId"));
211
208
  const pattern = Number.isSafeInteger(patternId) && patternId > 0 ? await this.database.getRepository("agentLoopPatterns").findOne({
212
209
  filterByTk: patternId,
213
210
  transaction,
@@ -216,14 +213,14 @@ class LoopRunStateMachine {
216
213
  let blockedReason = "";
217
214
  if (!Number.isSafeInteger(patternId) || patternId <= 0) blockedReason = "Run has no valid pattern snapshot.";
218
215
  else if (!pattern) blockedReason = "Loop pattern was deleted.";
219
- else if (read(pattern, "enabled") !== true) blockedReason = "Loop pattern is disabled.";
220
- const parsedPolicy = import_LoopPatternSchema.loopPatternPolicySchema.safeParse(read(candidate, "policySnapshot"));
216
+ else if ((0, import_record_utils.read)(pattern, "enabled") !== true) blockedReason = "Loop pattern is disabled.";
217
+ const parsedPolicy = import_LoopPatternSchema.loopPatternPolicySchema.safeParse((0, import_record_utils.read)(candidate, "policySnapshot"));
221
218
  if (!blockedReason && !parsedPolicy.success) blockedReason = "Run policy snapshot is invalid.";
222
219
  if (blockedReason) {
223
220
  assertRunTransition({
224
- from: asStatus(read(candidate, "status")),
221
+ from: asStatus((0, import_record_utils.read)(candidate, "status")),
225
222
  to: "blocked",
226
- runtimeVersion: String(read(candidate, "runtimeVersion") || "")
223
+ runtimeVersion: String((0, import_record_utils.read)(candidate, "runtimeVersion") || "")
227
224
  });
228
225
  await runs.update({
229
226
  filterByTk: runId,
@@ -253,9 +250,9 @@ class LoopRunStateMachine {
253
250
  const leaseToken = `${normalizedWorkerId}:${(0, import_node_crypto.randomUUID)()}`;
254
251
  const leaseUntil = new Date(now.getTime() + leaseMs);
255
252
  assertRunTransition({
256
- from: asStatus(read(candidate, "status")),
253
+ from: asStatus((0, import_record_utils.read)(candidate, "status")),
257
254
  to: "preparing",
258
- runtimeVersion: String(read(candidate, "runtimeVersion") || "")
255
+ runtimeVersion: String((0, import_record_utils.read)(candidate, "runtimeVersion") || "")
259
256
  });
260
257
  await runs.update({
261
258
  filterByTk: runId,
@@ -311,9 +308,9 @@ class LoopRunStateMachine {
311
308
  const pending = await approvals.find({ filter: { status: "pending" }, transaction });
312
309
  const overdueByRun = /* @__PURE__ */ new Map();
313
310
  for (const approval of pending) {
314
- const expiresAt = asDate(read(approval, "expiresAt"));
311
+ const expiresAt = asDate((0, import_record_utils.read)(approval, "expiresAt"));
315
312
  if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
316
- const runId = Number(read(approval, "runId"));
313
+ const runId = Number((0, import_record_utils.read)(approval, "runId"));
317
314
  if (!Number.isSafeInteger(runId) || runId <= 0) continue;
318
315
  const bucket = overdueByRun.get(runId) || [];
319
316
  bucket.push(approval);
@@ -322,16 +319,16 @@ class LoopRunStateMachine {
322
319
  for (const [runId, overdue] of overdueByRun) {
323
320
  const run = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
324
321
  if (!run) continue;
325
- if (String(read(run, "runtimeVersion")) !== "control-plane-v2") continue;
326
- if (asStatus(read(run, "status")) !== "waiting_approval") continue;
322
+ if (String((0, import_record_utils.read)(run, "runtimeVersion")) !== "control-plane-v2") continue;
323
+ if (asStatus((0, import_record_utils.read)(run, "status")) !== "waiting_approval") continue;
327
324
  assertRunTransition({
328
325
  from: "waiting_approval",
329
326
  to: "blocked",
330
- runtimeVersion: String(read(run, "runtimeVersion") || "")
327
+ runtimeVersion: String((0, import_record_utils.read)(run, "runtimeVersion") || "")
331
328
  });
332
329
  for (const approval of overdue) {
333
330
  await approvals.update({
334
- filterByTk: Number(read(approval, "id")),
331
+ filterByTk: Number((0, import_record_utils.read)(approval, "id")),
335
332
  values: { status: "expired", decidedAt: now },
336
333
  transaction
337
334
  });
@@ -376,11 +373,11 @@ class LoopRunStateMachine {
376
373
  return this.database.sequelize.transaction(async (transaction) => {
377
374
  const runs = this.database.getRepository("agentLoopRuns");
378
375
  const run = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
379
- if (!run || read(run, "lockedBy") !== leaseToken)
376
+ if (!run || (0, import_record_utils.read)(run, "lockedBy") !== leaseToken)
380
377
  throw new Error("Worker lease is no longer owned by this worker.");
381
- if (String(read(run, "runtimeVersion")) !== "control-plane-v2")
378
+ if (String((0, import_record_utils.read)(run, "runtimeVersion")) !== "control-plane-v2")
382
379
  throw new Error("Historical plan-era runs are read-only.");
383
- if (!activeExecutionStatuses.includes(asStatus(read(run, "status")))) {
380
+ if (!activeExecutionStatuses.includes(asStatus((0, import_record_utils.read)(run, "status")))) {
384
381
  throw new Error("Only actively executing runs can renew a worker lease.");
385
382
  }
386
383
  const leaseUntil = new Date(Date.now() + leaseMs);
@@ -394,7 +391,7 @@ class LoopRunStateMachine {
394
391
  const runs = this.database.getRepository("agentLoopRuns");
395
392
  const run = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
396
393
  if (!run) return false;
397
- if (read(run, "lockedBy") !== leaseToken) throw new Error("Worker lease is no longer owned by this worker.");
394
+ if ((0, import_record_utils.read)(run, "lockedBy") !== leaseToken) throw new Error("Worker lease is no longer owned by this worker.");
398
395
  await runs.update({ filterByTk: runId, values: { lockedBy: null, lockedUntil: null }, transaction });
399
396
  return true;
400
397
  });
@@ -410,20 +407,20 @@ class LoopRunStateMachine {
410
407
  });
411
408
  if (!run) throw new Error(`Agent loop run ${input.runId} was not found.`);
412
409
  if (input.actorType === "worker") {
413
- if (!((_a = input.leaseToken) == null ? void 0 : _a.trim()) || read(run, "lockedBy") !== input.leaseToken) {
410
+ if (!((_a = input.leaseToken) == null ? void 0 : _a.trim()) || (0, import_record_utils.read)(run, "lockedBy") !== input.leaseToken) {
414
411
  throw new Error("Worker lease is no longer owned by this worker.");
415
412
  }
416
413
  if (leaseIsExpired(run, /* @__PURE__ */ new Date())) throw new Error("Worker lease has expired.");
417
414
  }
418
- const from = asStatus(read(run, "status"));
415
+ const from = asStatus((0, import_record_utils.read)(run, "status"));
419
416
  if (input.actorType === "worker" && !activeExecutionStatuses.includes(from)) {
420
417
  throw new Error(`A worker cannot transition a run that is ${from}.`);
421
418
  }
422
- const verifierEvidence = ((_b = input.values) == null ? void 0 : _b.verifierEvidence) ?? read(run, "verifierEvidence");
419
+ const verifierEvidence = ((_b = input.values) == null ? void 0 : _b.verifierEvidence) ?? (0, import_record_utils.read)(run, "verifierEvidence");
423
420
  assertRunTransition({
424
421
  from,
425
422
  to: input.to,
426
- runtimeVersion: String(read(run, "runtimeVersion") || ""),
423
+ runtimeVersion: String((0, import_record_utils.read)(run, "runtimeVersion") || ""),
427
424
  verifierEvidence,
428
425
  humanAccepted: input.humanAccepted
429
426
  });
@@ -433,7 +430,7 @@ class LoopRunStateMachine {
433
430
  values: {
434
431
  ...input.values || {},
435
432
  status: input.to,
436
- ...input.to === "running" && !read(run, "startedAt") ? { startedAt: now } : {},
433
+ ...input.to === "running" && !(0, import_record_utils.read)(run, "startedAt") ? { startedAt: now } : {},
437
434
  ...["succeeded", "failed", "canceled"].includes(input.to) ? { endedAt: now } : {}
438
435
  },
439
436
  transaction