@mastra/factory 0.30.0 → 0.31.0-alpha.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.
- package/README.md +32 -10
- package/dist/factory.d.ts +12 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +72 -31
- package/dist/factory.js.map +1 -1
- package/dist/integrations/gitlab/api.d.ts +3 -2
- package/dist/integrations/gitlab/api.d.ts.map +1 -1
- package/dist/integrations/gitlab/api.js +12 -9
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts +5 -0
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +17 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +22 -13
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +63 -64
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/foundation/connect-binding.d.ts +125 -0
- package/dist/integrations/platform/foundation/connect-binding.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-binding.js +252 -0
- package/dist/integrations/platform/foundation/connect-binding.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts +49 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js +304 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts +31 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.js +7 -0
- package/dist/integrations/platform/foundation/connect-events.js.map +1 -0
- package/dist/integrations/platform/foundation/index.d.ts +10 -0
- package/dist/integrations/platform/foundation/index.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/index.js +6 -0
- package/dist/integrations/platform/foundation/intake.d.ts +39 -0
- package/dist/integrations/platform/foundation/intake.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/intake.js +45 -0
- package/dist/integrations/platform/foundation/intake.js.map +1 -0
- package/dist/integrations/platform/foundation/integration.d.ts +84 -0
- package/dist/integrations/platform/foundation/integration.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/integration.js +107 -0
- package/dist/integrations/platform/foundation/integration.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +2 -2
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +4 -8
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +3 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +131 -70
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/connect-events.d.ts +22 -0
- package/dist/integrations/platform/gitlab/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/gitlab/connect-events.js +49 -0
- package/dist/integrations/platform/gitlab/connect-events.js.map +1 -0
- package/dist/integrations/platform/gitlab/integration.d.ts +24 -15
- package/dist/integrations/platform/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js +61 -26
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/intake.d.ts +33 -0
- package/dist/integrations/platform/incidentio/intake.d.ts.map +1 -0
- package/dist/integrations/platform/incidentio/intake.js +271 -0
- package/dist/integrations/platform/incidentio/intake.js.map +1 -0
- package/dist/integrations/platform/incidentio/integration.d.ts +11 -23
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +27 -297
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/intake.d.ts +60 -0
- package/dist/integrations/platform/jira/intake.d.ts.map +1 -0
- package/dist/integrations/platform/jira/intake.js +445 -0
- package/dist/integrations/platform/jira/intake.js.map +1 -0
- package/dist/integrations/platform/jira/integration.d.ts +13 -37
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +29 -468
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +5 -9
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +3 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/logging.d.ts +6 -0
- package/dist/integrations/platform/logging.d.ts.map +1 -0
- package/dist/integrations/platform/logging.js +25 -0
- package/dist/integrations/platform/logging.js.map +1 -0
- package/dist/integrations/platform/platform-connect.d.ts +38 -0
- package/dist/integrations/platform/platform-connect.d.ts.map +1 -0
- package/dist/integrations/platform/platform-connect.js +109 -0
- package/dist/integrations/platform/platform-connect.js.map +1 -0
- package/dist/integrations/platform/vanta/integration.d.ts +12 -18
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +38 -38
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/memory-embedder.d.ts +11 -0
- package/dist/memory-embedder.d.ts.map +1 -0
- package/dist/memory-embedder.js +19 -0
- package/dist/memory-embedder.js.map +1 -0
- package/dist/metrics/config.d.ts +1 -1
- package/dist/metrics/config.d.ts.map +1 -1
- package/dist/metrics/config.js +1 -0
- package/dist/metrics/config.js.map +1 -1
- package/dist/metrics/index.js +2 -2
- package/dist/metrics/index.js.map +1 -1
- package/dist/metrics/sandbox.d.ts +3 -3
- package/dist/metrics/sandbox.js +13 -13
- package/dist/metrics/sandbox.js.map +1 -1
- package/dist/metrics/session.d.ts +28 -0
- package/dist/metrics/session.d.ts.map +1 -0
- package/dist/metrics/session.js +76 -0
- package/dist/metrics/session.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +5 -0
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +65 -7
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +5 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -0
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +29 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +156 -23
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/public-failure-reason.js +1 -1
- package/dist/rules/public-failure-reason.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +33 -9
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +4 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-item-branch.d.ts +7 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +9 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-facts.d.ts.map +1 -1
- package/dist/work-items/card-facts.js +2 -2
- package/dist/work-items/card-facts.js.map +1 -1
- package/package.json +8 -8
- package/dist/integrations/platform/api-client.d.ts +0 -34
- package/dist/integrations/platform/api-client.d.ts.map +0 -1
- package/dist/integrations/platform/api-client.js +0 -186
- package/dist/integrations/platform/api-client.js.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts +0 -64
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.js +0 -304
- package/dist/integrations/platform/gitlab/event-worker.js.map +0 -1
|
@@ -39,6 +39,16 @@ export declare class FactoryPhaseStateProcessor implements Processor<'factory-ph
|
|
|
39
39
|
/** Request contexts whose caller row is already resolved for this request. */
|
|
40
40
|
private readonly loadedMemorySettings;
|
|
41
41
|
private readonly bindingReconciles;
|
|
42
|
+
/**
|
|
43
|
+
* Bindings a step ran on since they were last reconciled, or whose run was still
|
|
44
|
+
* going then. Only these can have tool results the step hook did not see, so a
|
|
45
|
+
* routine pass reads only them. `settled` marks one already read after its run
|
|
46
|
+
* stopped: it gets one trailing read, for results persisted after the run ended.
|
|
47
|
+
*/
|
|
48
|
+
private readonly pendingReconciles;
|
|
49
|
+
/** Messages at each binding's cursor time already ingested, by id, with the tool calls they held results for. */
|
|
50
|
+
private readonly cursorBoundaries;
|
|
51
|
+
private lastFullReconcileAt;
|
|
42
52
|
private readonly boards;
|
|
43
53
|
constructor(options: {
|
|
44
54
|
configVersion: string;
|
|
@@ -52,6 +62,8 @@ export declare class FactoryPhaseStateProcessor implements Processor<'factory-ph
|
|
|
52
62
|
defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;
|
|
53
63
|
/** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */
|
|
54
64
|
onBoundThreadRun?: () => void;
|
|
65
|
+
/** Whether a run is going on this thread in this process; its binding stays due for reconcile until it stops. */
|
|
66
|
+
isThreadRunning?: (threadId: string) => boolean;
|
|
55
67
|
transitionService?: Pick<FactoryTransitionService, 'transition'>;
|
|
56
68
|
messageReader?: PersistedMessageReader;
|
|
57
69
|
recordPullRequestProvenance?: (input: {
|
|
@@ -89,7 +101,23 @@ export declare class FactoryPhaseStateProcessor implements Processor<'factory-ph
|
|
|
89
101
|
*/
|
|
90
102
|
private loadCallerMemorySettings;
|
|
91
103
|
computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult>;
|
|
92
|
-
|
|
104
|
+
/**
|
|
105
|
+
* The dispatcher's recurring pass. Tool results reach the card from the step hook;
|
|
106
|
+
* this catches the ones it cannot see (results persisted after a run's last step,
|
|
107
|
+
* or while no process was watching). Only bindings a step ran on since the last
|
|
108
|
+
* pass can have new ones, so a routine pass reads just those. The first pass, and
|
|
109
|
+
* one every {@link FULL_RECONCILE_INTERVAL_MS}, walks every active binding instead.
|
|
110
|
+
*/
|
|
111
|
+
reconcileBoundThreads(now?: number): Promise<void>;
|
|
112
|
+
/** Walks every active binding: the boot catch-up and the safety net behind {@link reconcileBoundThreads}. */
|
|
113
|
+
reconcileAllBoundThreads(now?: number): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* A few bindings at a time, yielding between them: a pass is background work and
|
|
116
|
+
* must not hold the event loop or the database for the runs it follows. A binding
|
|
117
|
+
* that fails stays due for the next pass; the first failure is rethrown at the end.
|
|
118
|
+
*/
|
|
119
|
+
private reconcileEntries;
|
|
120
|
+
private reconcileEntry;
|
|
93
121
|
reconcileBinding(binding: FactoryRunBindingRecord): Promise<void>;
|
|
94
122
|
private reconcileBindingNow;
|
|
95
123
|
private ingestMessages;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../../src/rules/processor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yCAAyC,CAAC;AAE7E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAEpF,OAAO,KAAK,EACV,sBAAsB,EACtB,wBAAwB,EACxB,gBAAgB,EAChB,oBAAoB,EACpB,SAAS,EACV,MAAM,yBAAyB,CAAC;AASjC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAIxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEtE,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAE7G,OAAO,KAAK,EA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CHANGED
|
@@ -13,6 +13,9 @@ const STATE_ID = "factory-phase";
|
|
|
13
13
|
const RULE_TIMEOUT_MS = 5e3;
|
|
14
14
|
const TRANSCRIPT_PAGE_SIZE = 50;
|
|
15
15
|
const MAX_LINKED_ITEMS = 5;
|
|
16
|
+
const RECONCILE_CONCURRENCY = 4;
|
|
17
|
+
const FULL_RECONCILE_INTERVAL_MS = 6e5;
|
|
18
|
+
const yieldToEventLoop = () => new Promise((resolve) => setImmediate(resolve));
|
|
16
19
|
function ruleStage(boards, item) {
|
|
17
20
|
return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : void 0;
|
|
18
21
|
}
|
|
@@ -90,10 +93,8 @@ function completedStepToolCallIds(steps) {
|
|
|
90
93
|
}
|
|
91
94
|
return ids;
|
|
92
95
|
}
|
|
93
|
-
function
|
|
94
|
-
if (message.role !== "assistant") return
|
|
95
|
-
const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);
|
|
96
|
-
const completed = [];
|
|
96
|
+
function* completedInvocations(message) {
|
|
97
|
+
if (message.role !== "assistant") return;
|
|
97
98
|
for (const rawPart of messageParts(message)) {
|
|
98
99
|
if (!rawPart || typeof rawPart !== "object") continue;
|
|
99
100
|
const part = rawPart;
|
|
@@ -103,16 +104,35 @@ function completedToolResults(message) {
|
|
|
103
104
|
const toolCallId = invocation.toolCallId;
|
|
104
105
|
const toolName = invocation.toolName ?? invocation.name;
|
|
105
106
|
if (typeof toolCallId !== "string" || typeof toolName !== "string") continue;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
yield {
|
|
108
|
+
invocation,
|
|
109
|
+
state,
|
|
109
110
|
toolCallId,
|
|
110
|
-
toolName
|
|
111
|
-
|
|
112
|
-
status: state === "error" ? "error" : "success",
|
|
113
|
-
value: state === "error" ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result)
|
|
114
|
-
});
|
|
111
|
+
toolName
|
|
112
|
+
};
|
|
115
113
|
}
|
|
114
|
+
}
|
|
115
|
+
/** Which tool calls a message holds a result for, without serializing the results. */
|
|
116
|
+
function completedToolCallsKey(message) {
|
|
117
|
+
const keys = [];
|
|
118
|
+
for (const { state, toolCallId } of completedInvocations(message)) keys.push(`${toolCallId}:${state}`);
|
|
119
|
+
return keys.join("\n");
|
|
120
|
+
}
|
|
121
|
+
function messageTime(message) {
|
|
122
|
+
return (message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt)).getTime();
|
|
123
|
+
}
|
|
124
|
+
function completedToolResults(message) {
|
|
125
|
+
const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);
|
|
126
|
+
const completed = [];
|
|
127
|
+
for (const { invocation, state, toolCallId, toolName } of completedInvocations(message)) completed.push({
|
|
128
|
+
assistantMessageId: message.id,
|
|
129
|
+
messageCreatedAt: createdAt,
|
|
130
|
+
toolCallId,
|
|
131
|
+
toolName: toolName.slice(0, 256),
|
|
132
|
+
input: boundedResult(invocation.args ?? {}),
|
|
133
|
+
status: state === "error" ? "error" : "success",
|
|
134
|
+
value: state === "error" ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result)
|
|
135
|
+
});
|
|
116
136
|
return completed;
|
|
117
137
|
}
|
|
118
138
|
function currentCompletedToolMessage(messages, toolCallIds) {
|
|
@@ -195,6 +215,16 @@ var FactoryPhaseStateProcessor = class {
|
|
|
195
215
|
/** Request contexts whose caller row is already resolved for this request. */
|
|
196
216
|
loadedMemorySettings = /* @__PURE__ */ new WeakSet();
|
|
197
217
|
bindingReconciles = /* @__PURE__ */ new Map();
|
|
218
|
+
/**
|
|
219
|
+
* Bindings a step ran on since they were last reconciled, or whose run was still
|
|
220
|
+
* going then. Only these can have tool results the step hook did not see, so a
|
|
221
|
+
* routine pass reads only them. `settled` marks one already read after its run
|
|
222
|
+
* stopped: it gets one trailing read, for results persisted after the run ended.
|
|
223
|
+
*/
|
|
224
|
+
pendingReconciles = /* @__PURE__ */ new Map();
|
|
225
|
+
/** Messages at each binding's cursor time already ingested, by id, with the tool calls they held results for. */
|
|
226
|
+
cursorBoundaries = /* @__PURE__ */ new Map();
|
|
227
|
+
lastFullReconcileAt;
|
|
198
228
|
boards;
|
|
199
229
|
constructor(options) {
|
|
200
230
|
this.options = options;
|
|
@@ -226,6 +256,10 @@ var FactoryPhaseStateProcessor = class {
|
|
|
226
256
|
}
|
|
227
257
|
await this.loadCallerMemorySettings(args.requestContext, binding);
|
|
228
258
|
if (!binding || binding.status !== "active") return;
|
|
259
|
+
this.pendingReconciles.set(binding.id, {
|
|
260
|
+
binding,
|
|
261
|
+
settled: false
|
|
262
|
+
});
|
|
229
263
|
this.options.onBoundThreadRun?.();
|
|
230
264
|
const completedToolCallIds = completedStepToolCallIds(args.steps);
|
|
231
265
|
const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);
|
|
@@ -378,10 +412,85 @@ var FactoryPhaseStateProcessor = class {
|
|
|
378
412
|
metadata: { value: { phase: value } }
|
|
379
413
|
};
|
|
380
414
|
}
|
|
381
|
-
|
|
415
|
+
/**
|
|
416
|
+
* The dispatcher's recurring pass. Tool results reach the card from the step hook;
|
|
417
|
+
* this catches the ones it cannot see (results persisted after a run's last step,
|
|
418
|
+
* or while no process was watching). Only bindings a step ran on since the last
|
|
419
|
+
* pass can have new ones, so a routine pass reads just those. The first pass, and
|
|
420
|
+
* one every {@link FULL_RECONCILE_INTERVAL_MS}, walks every active binding instead.
|
|
421
|
+
*/
|
|
422
|
+
async reconcileBoundThreads(now = Date.now()) {
|
|
423
|
+
if (!this.options.messageReader) return;
|
|
424
|
+
if (this.lastFullReconcileAt === void 0 || now - this.lastFullReconcileAt >= FULL_RECONCILE_INTERVAL_MS) {
|
|
425
|
+
await this.reconcileAllBoundThreads(now);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const pending = [...this.pendingReconciles.values()];
|
|
429
|
+
this.pendingReconciles.clear();
|
|
430
|
+
await this.reconcileEntries(pending, true);
|
|
431
|
+
}
|
|
432
|
+
/** Walks every active binding: the boot catch-up and the safety net behind {@link reconcileBoundThreads}. */
|
|
433
|
+
async reconcileAllBoundThreads(now = Date.now()) {
|
|
382
434
|
if (!this.options.messageReader) return;
|
|
383
435
|
const bindings = await this.options.storage.listActiveRunBindings();
|
|
384
|
-
|
|
436
|
+
this.lastFullReconcileAt = now;
|
|
437
|
+
const pending = new Map(this.pendingReconciles);
|
|
438
|
+
this.pendingReconciles.clear();
|
|
439
|
+
const active = new Set(bindings.map((binding) => binding.id));
|
|
440
|
+
for (const id of this.cursorBoundaries.keys()) if (!active.has(id)) this.cursorBoundaries.delete(id);
|
|
441
|
+
await this.reconcileEntries(bindings.map((binding) => ({
|
|
442
|
+
binding,
|
|
443
|
+
settled: pending.get(binding.id)?.settled ?? true
|
|
444
|
+
})), false);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* A few bindings at a time, yielding between them: a pass is background work and
|
|
448
|
+
* must not hold the event loop or the database for the runs it follows. A binding
|
|
449
|
+
* that fails stays due for the next pass; the first failure is rethrown at the end.
|
|
450
|
+
*/
|
|
451
|
+
async reconcileEntries(entries, refresh) {
|
|
452
|
+
let next = 0;
|
|
453
|
+
let failure;
|
|
454
|
+
const worker = async () => {
|
|
455
|
+
while (next < entries.length) {
|
|
456
|
+
const entry = entries[next++];
|
|
457
|
+
try {
|
|
458
|
+
await this.reconcileEntry(entry, refresh);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
failure ??= { error };
|
|
461
|
+
if (!this.pendingReconciles.has(entry.binding.id)) this.pendingReconciles.set(entry.binding.id, entry);
|
|
462
|
+
}
|
|
463
|
+
await yieldToEventLoop();
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
await Promise.all(Array.from({ length: Math.min(RECONCILE_CONCURRENCY, entries.length) }, worker));
|
|
467
|
+
if (failure) throw failure.error;
|
|
468
|
+
}
|
|
469
|
+
async reconcileEntry(entry, refresh) {
|
|
470
|
+
let binding = entry.binding;
|
|
471
|
+
if (refresh) {
|
|
472
|
+
const current = await this.options.storage.findRunBindingById({
|
|
473
|
+
orgId: binding.orgId,
|
|
474
|
+
factoryProjectId: binding.factoryProjectId,
|
|
475
|
+
id: binding.id
|
|
476
|
+
});
|
|
477
|
+
if (current?.status !== "active") {
|
|
478
|
+
this.cursorBoundaries.delete(binding.id);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
binding = current;
|
|
482
|
+
}
|
|
483
|
+
const running = this.options.isThreadRunning?.(binding.threadId) ?? false;
|
|
484
|
+
await this.reconcileBinding(binding);
|
|
485
|
+
if (this.pendingReconciles.has(binding.id)) return;
|
|
486
|
+
if (running) this.pendingReconciles.set(binding.id, {
|
|
487
|
+
binding,
|
|
488
|
+
settled: false
|
|
489
|
+
});
|
|
490
|
+
else if (!entry.settled) this.pendingReconciles.set(binding.id, {
|
|
491
|
+
binding,
|
|
492
|
+
settled: true
|
|
493
|
+
});
|
|
385
494
|
}
|
|
386
495
|
async reconcileBinding(binding) {
|
|
387
496
|
const previous = this.bindingReconciles.get(binding.id);
|
|
@@ -403,8 +512,17 @@ var FactoryPhaseStateProcessor = class {
|
|
|
403
512
|
orgId: binding.orgId,
|
|
404
513
|
id: binding.workItemId
|
|
405
514
|
});
|
|
406
|
-
if (!itemInRuleStage(await this.boards.load(binding), item))
|
|
515
|
+
if (!itemInRuleStage(await this.boards.load(binding), item)) {
|
|
516
|
+
this.cursorBoundaries.delete(binding.id);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
407
519
|
const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);
|
|
520
|
+
const startAt = cursor ? new Date(cursor.lastMessageCreatedAt).getTime() : void 0;
|
|
521
|
+
const previous = this.cursorBoundaries.get(binding.id);
|
|
522
|
+
const ingested = previous && previous.at === startAt ? previous.seen : /* @__PURE__ */ new Map();
|
|
523
|
+
let cursorAt = startAt;
|
|
524
|
+
let boundary = /* @__PURE__ */ new Map();
|
|
525
|
+
let read = false;
|
|
408
526
|
let page = 0;
|
|
409
527
|
while (true) {
|
|
410
528
|
const result = await reader.listMessages({
|
|
@@ -418,18 +536,33 @@ var FactoryPhaseStateProcessor = class {
|
|
|
418
536
|
direction: "ASC"
|
|
419
537
|
}
|
|
420
538
|
});
|
|
421
|
-
|
|
539
|
+
const fresh = result.messages.filter((message) => messageTime(message) !== startAt || ingested.get(message.id) !== completedToolCallsKey(message));
|
|
540
|
+
if (fresh.length > 0) await this.ingestMessages(binding, fresh, void 0, item);
|
|
422
541
|
const last = result.messages.at(-1);
|
|
423
|
-
if (last)
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
542
|
+
if (last) {
|
|
543
|
+
read = true;
|
|
544
|
+
const lastAt = messageTime(last);
|
|
545
|
+
if (lastAt !== cursorAt) {
|
|
546
|
+
await this.options.storage.advanceToolResultCursor({
|
|
547
|
+
bindingId: binding.id,
|
|
548
|
+
orgId: binding.orgId,
|
|
549
|
+
factoryProjectId: binding.factoryProjectId,
|
|
550
|
+
lastMessageCreatedAt: new Date(lastAt),
|
|
551
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
552
|
+
});
|
|
553
|
+
cursorAt = lastAt;
|
|
554
|
+
boundary = /* @__PURE__ */ new Map();
|
|
555
|
+
}
|
|
556
|
+
for (const message of result.messages) if (messageTime(message) === lastAt) boundary.set(message.id, completedToolCallsKey(message));
|
|
557
|
+
}
|
|
430
558
|
if (!result.hasMore) break;
|
|
431
559
|
page += 1;
|
|
560
|
+
await yieldToEventLoop();
|
|
432
561
|
}
|
|
562
|
+
if (read && cursorAt !== void 0) this.cursorBoundaries.set(binding.id, {
|
|
563
|
+
at: cursorAt,
|
|
564
|
+
seen: boundary
|
|
565
|
+
});
|
|
433
566
|
}
|
|
434
567
|
async ingestMessages(binding, messages, toolCallIds, preloadedItem) {
|
|
435
568
|
const item = preloadedItem ?? await this.options.storage.get({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport {\n boardFlow,\n boardForWorkItem,\n resolveBoardToolRule,\n reviewsPullRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { workStageCarries } from '../boards/legacy-plan-role.js';\nimport { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\nfunction ruleStage(boards: BoardRegistry, item: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\nconst STAMP_ATTEMPTS = 3;\n\n/** When the card's current visit to `stage` began, if it is in `stage` alone. */\nfunction openEntry(item: Card, stage: string): string | undefined {\n if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined;\n return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt;\n}\n\n/**\n * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,\n * with an approved plan) in the session that works the card there. Undefined otherwise.\n */\nfunction finishedPhase(\n boards: BoardRegistry,\n board: string,\n item: Card,\n role: string,\n toolResult: CompletedToolResult,\n): string | undefined {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const definition = boards.get(board);\n const phase = stage === undefined ? undefined : definition?.phases[stage];\n if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined;\n if (toolResult.status !== 'success') return undefined;\n if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined;\n // Only the session that works the card in this phase finishes it: one in another context that\n // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished.\n // A Work card planned before Planning ran in the `work` context still holds its `plan` session.\n if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) {\n return undefined;\n }\n return stage;\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n defaultThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n // A result read during the run is the tool's in-memory value (submit_plan's holds undefined\n // fields); read it as the JSON the thread stores, so it means the same now as after the run.\n return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(value)));\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n if (message.role !== 'assistant') return [];\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\n/**\n * The tool results the step about to run follows: the latest assistant message, past any signals\n * after it. A run continued after a tool call (such as submit_plan's approval) carries steps\n * without their tool results, so the step ids alone can miss the result the agent acts on next.\n */\nfunction latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if ((message.role as string) === 'signal') continue;\n return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n private readonly bindingReconciles = new Map<string, Promise<void>>();\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {\n this.boards = toBoardSource(options.boards);\n }\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n return;\n }\n const latest = latestToolResultMessage(args.messages);\n if (latest) await this.ingestMessages(binding, [latest]);\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n // Say where the card went, so the session stops its work instead of guessing why its phase vanished.\n const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const movedBoards = moved ? await this.boards.load(binding) : undefined;\n const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined;\n const movedName = movedTo\n ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo)\n : undefined;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: movedName\n ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\\n`\n : '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const linked = await this.options.storage.listLinked({ item, limit: MAX_LINKED_ITEMS });\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const flow = boardFlow(boards.get(board));\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const definition = boards.get(board);\n const phase = definition?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const nextText = phase\n ? `Next phases: ${\n phase.nextPhases.length\n ? phase.nextPhases\n .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`)\n .join('; ')\n : 'none'\n }\\n`\n : '';\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${\n definition?.tools[phase.exitTool.id]\n ? 'Its result moves the card on.'\n : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.`\n }\\n`\n : '';\n // Skills name phases by role in the pull request loop, never by key: this line maps them.\n const flowPhase = (key: string | undefined) =>\n key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined;\n const completed = flow.completed?.phase;\n const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase;\n const flowParts = [\n definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined,\n flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined,\n flow.build ? `build: ${flowPhase(flow.build)}` : undefined,\n flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined,\n flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined,\n completed ? `completed: ${flowPhase(completed)}` : undefined,\n canceled ? `canceled: ${flowPhase(canceled)}` : undefined,\n ].filter(part => part !== undefined);\n const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\\n` : '';\n // The card moved to a phase another context works; this session's tools for it are gone.\n const handedOnText =\n phase?.kind === 'working' &&\n phase.runner.context !== binding.role &&\n // A Work card planned before Planning ran in `work` keeps its `plan` session there.\n workStageCarries(definition, stage, binding.role, undefined) !== true\n ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\\n`\n : '';\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n (phase?.kind === 'resting'\n ? `This card rests in ${escapeText(phaseLabel)}: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n`\n : '') +\n nextText +\n flowText +\n exitText +\n handedOnText +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n async reconcileAllBoundThreads(): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n for (const binding of bindings) await this.reconcileBinding(binding);\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const previous = this.bindingReconciles.get(binding.id);\n const run = (async () => {\n if (previous) await previous.catch(() => undefined);\n await this.reconcileBindingNow(binding);\n })();\n this.bindingReconciles.set(binding.id, run);\n try {\n await run;\n } finally {\n if (this.bindingReconciles.get(binding.id) === run) this.bindingReconciles.delete(binding.id);\n }\n }\n\n private async reconcileBindingNow(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n await this.ingestMessages(binding, result.messages, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),\n updatedAt: new Date(),\n });\n }\n if (!result.hasMore) break;\n page += 1;\n }\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n loaded: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n let item = loaded;\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const finished = finishedPhase(boards, board, item, binding.role, toolResult);\n // The exit tool finished the phase: the card may now leave it (the agent moves it). A result\n // read again later (the step, then the thread) stamps once: the stamp names its tool call.\n const at = new Date().toISOString();\n const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId;\n if (\n finished !== undefined &&\n stampedCall !== toolResult.toolCallId &&\n !exitToolSucceeded(item, finished, toolResult.toolName)\n ) {\n const entry = openEntry(item, finished);\n for (let attempt = 1; ; attempt++) {\n try {\n const stamped = await this.options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n [PHASE_EXIT_METADATA_KEY]: {\n phase: finished,\n tool: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n at,\n },\n ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}),\n },\n },\n expectedRevision: item.revision,\n });\n if (stamped) item = stamped.item;\n break;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n // Another write landed first. While the card is still in the same visit to the phase,\n // the result still finishes it; once the card moved on, it no longer needs finishing.\n const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id });\n if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) {\n return;\n }\n item = current;\n }\n }\n }\n const rule = resolveBoardToolRule(boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId },\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n // The bound agent's own tool call carries the same consent as its governed moves.\n consentedBy: `agent:${binding.id}`,\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n ...(entry.reenter ? { reenter: true } : {}),\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}),\n ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAAmD;CAC3F,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA6C;CAC3F,OAAO,UAAU,QAAQ,IAAI,MAAM,KAAA;AACrC;AAuBA,SAAS,qBAAqB,QAAsC;CAClE,IAAI,OAAO,aAAa,iBAAiB,OAAO,WAAW,WAAW,OAAO;CAC7E,IAAI,OAAO,OAAO,UAAU,UAAU,OAAO,OAAO,MAAM,WAAW,gBAAgB;CACrF,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ,OAAO,KAAK,GAAG,OAAO;CAC7F,MAAM,UAAU,OAAO,MAAM;CAC7B,OAAO,OAAO,YAAY,YAAY,QAAQ,WAAW,gBAAgB;AAC3E;AAEA,MAAM,iBAAiB;;AAGvB,SAAS,UAAU,MAAY,OAAmC;CAChE,IAAI,KAAK,OAAO,WAAW,KAAK,KAAK,OAAO,OAAO,OAAO,OAAO,KAAA;CACjE,OAAO,KAAK,cAAc,UAAS,UAAS,MAAM,UAAU,SAAS,MAAM,aAAa,KAAA,CAAS,CAAC,EAAE;AACtG;;;;;AAMA,SAAS,cACP,QACA,OACA,MACA,MACA,YACoB;CACpB,MAAM,QAAQ,KAAK,OAAO,WAAW,IAAI,KAAK,OAAO,KAAM,KAAA;CAC3D,MAAM,aAAa,OAAO,IAAI,KAAK;CACnC,MAAM,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,YAAY,OAAO;CACnE,IAAI,OAAO,SAAS,aAAa,MAAM,UAAU,OAAO,WAAW,UAAU,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AAc,MAAM;IAAK,CAAC;IACrD,GAAI,qBAAqB,UAAU,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport {\n boardFlow,\n boardForWorkItem,\n resolveBoardToolRule,\n reviewsPullRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { workStageCarries } from '../boards/legacy-plan-role.js';\nimport { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\n// Bindings read at once by a reconcile pass, which yields between them.\nconst RECONCILE_CONCURRENCY = 4;\n// The full walk of every active binding behind the routine reconcile pass.\nconst FULL_RECONCILE_INTERVAL_MS = 10 * 60_000;\n\nconst yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));\nfunction ruleStage(boards: BoardRegistry, item: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\nconst STAMP_ATTEMPTS = 3;\n\n/** When the card's current visit to `stage` began, if it is in `stage` alone. */\nfunction openEntry(item: Card, stage: string): string | undefined {\n if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined;\n return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt;\n}\n\n/**\n * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,\n * with an approved plan) in the session that works the card there. Undefined otherwise.\n */\nfunction finishedPhase(\n boards: BoardRegistry,\n board: string,\n item: Card,\n role: string,\n toolResult: CompletedToolResult,\n): string | undefined {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const definition = boards.get(board);\n const phase = stage === undefined ? undefined : definition?.phases[stage];\n if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined;\n if (toolResult.status !== 'success') return undefined;\n if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined;\n // Only the session that works the card in this phase finishes it: one in another context that\n // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished.\n // A Work card planned before Planning ran in the `work` context still holds its `plan` session.\n if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) {\n return undefined;\n }\n return stage;\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n defaultThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n // A result read during the run is the tool's in-memory value (submit_plan's holds undefined\n // fields); read it as the JSON the thread stores, so it means the same now as after the run.\n return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(value)));\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction* completedInvocations(message: MastraDBMessage): Generator<{\n invocation: Record<string, unknown>;\n state: 'result' | 'error';\n toolCallId: string;\n toolName: string;\n}> {\n if (message.role !== 'assistant') return;\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n yield { invocation, state, toolCallId, toolName };\n }\n}\n\n/** Which tool calls a message holds a result for, without serializing the results. */\nfunction completedToolCallsKey(message: MastraDBMessage): string {\n const keys: string[] = [];\n for (const { state, toolCallId } of completedInvocations(message)) keys.push(`${toolCallId}:${state}`);\n return keys.join('\\n');\n}\n\nfunction messageTime(message: MastraDBMessage): number {\n return (message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt)).getTime();\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const { invocation, state, toolCallId, toolName } of completedInvocations(message)) {\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\n/**\n * The tool results the step about to run follows: the latest assistant message, past any signals\n * after it. A run continued after a tool call (such as submit_plan's approval) carries steps\n * without their tool results, so the step ids alone can miss the result the agent acts on next.\n */\nfunction latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if ((message.role as string) === 'signal') continue;\n return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n private readonly bindingReconciles = new Map<string, Promise<void>>();\n /**\n * Bindings a step ran on since they were last reconciled, or whose run was still\n * going then. Only these can have tool results the step hook did not see, so a\n * routine pass reads only them. `settled` marks one already read after its run\n * stopped: it gets one trailing read, for results persisted after the run ended.\n */\n private readonly pendingReconciles = new Map<string, { binding: FactoryRunBindingRecord; settled: boolean }>();\n /** Messages at each binding's cursor time already ingested, by id, with the tool calls they held results for. */\n private readonly cursorBoundaries = new Map<string, { at: number; seen: Map<string, string> }>();\n private lastFullReconcileAt: number | undefined;\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n /** Whether a run is going on this thread in this process; its binding stays due for reconcile until it stops. */\n isThreadRunning?: (threadId: string) => boolean;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {\n this.boards = toBoardSource(options.boards);\n }\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n this.pendingReconciles.set(binding.id, { binding, settled: false });\n this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n return;\n }\n const latest = latestToolResultMessage(args.messages);\n if (latest) await this.ingestMessages(binding, [latest]);\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n // Say where the card went, so the session stops its work instead of guessing why its phase vanished.\n const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const movedBoards = moved ? await this.boards.load(binding) : undefined;\n const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined;\n const movedName = movedTo\n ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo)\n : undefined;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: movedName\n ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\\n`\n : '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const linked = await this.options.storage.listLinked({ item, limit: MAX_LINKED_ITEMS });\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const flow = boardFlow(boards.get(board));\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const definition = boards.get(board);\n const phase = definition?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const nextText = phase\n ? `Next phases: ${\n phase.nextPhases.length\n ? phase.nextPhases\n .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`)\n .join('; ')\n : 'none'\n }\\n`\n : '';\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${\n definition?.tools[phase.exitTool.id]\n ? 'Its result moves the card on.'\n : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.`\n }\\n`\n : '';\n // Skills name phases by role in the pull request loop, never by key: this line maps them.\n const flowPhase = (key: string | undefined) =>\n key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined;\n const completed = flow.completed?.phase;\n const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase;\n const flowParts = [\n definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined,\n flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined,\n flow.build ? `build: ${flowPhase(flow.build)}` : undefined,\n flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined,\n flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined,\n completed ? `completed: ${flowPhase(completed)}` : undefined,\n canceled ? `canceled: ${flowPhase(canceled)}` : undefined,\n ].filter(part => part !== undefined);\n const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\\n` : '';\n // The card moved to a phase another context works; this session's tools for it are gone.\n const handedOnText =\n phase?.kind === 'working' &&\n phase.runner.context !== binding.role &&\n // A Work card planned before Planning ran in `work` keeps its `plan` session there.\n workStageCarries(definition, stage, binding.role, undefined) !== true\n ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\\n`\n : '';\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n (phase?.kind === 'resting'\n ? `This card rests in ${escapeText(phaseLabel)}: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n`\n : '') +\n nextText +\n flowText +\n exitText +\n handedOnText +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n /**\n * The dispatcher's recurring pass. Tool results reach the card from the step hook;\n * this catches the ones it cannot see (results persisted after a run's last step,\n * or while no process was watching). Only bindings a step ran on since the last\n * pass can have new ones, so a routine pass reads just those. The first pass, and\n * one every {@link FULL_RECONCILE_INTERVAL_MS}, walks every active binding instead.\n */\n async reconcileBoundThreads(now = Date.now()): Promise<void> {\n if (!this.options.messageReader) return;\n if (this.lastFullReconcileAt === undefined || now - this.lastFullReconcileAt >= FULL_RECONCILE_INTERVAL_MS) {\n await this.reconcileAllBoundThreads(now);\n return;\n }\n const pending = [...this.pendingReconciles.values()];\n this.pendingReconciles.clear();\n await this.reconcileEntries(pending, true);\n }\n\n /** Walks every active binding: the boot catch-up and the safety net behind {@link reconcileBoundThreads}. */\n async reconcileAllBoundThreads(now = Date.now()): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n this.lastFullReconcileAt = now;\n const pending = new Map(this.pendingReconciles);\n this.pendingReconciles.clear();\n const active = new Set(bindings.map(binding => binding.id));\n for (const id of this.cursorBoundaries.keys()) if (!active.has(id)) this.cursorBoundaries.delete(id);\n await this.reconcileEntries(\n bindings.map(binding => ({ binding, settled: pending.get(binding.id)?.settled ?? true })),\n false,\n );\n }\n\n /**\n * A few bindings at a time, yielding between them: a pass is background work and\n * must not hold the event loop or the database for the runs it follows. A binding\n * that fails stays due for the next pass; the first failure is rethrown at the end.\n */\n private async reconcileEntries(\n entries: Array<{ binding: FactoryRunBindingRecord; settled: boolean }>,\n refresh: boolean,\n ): Promise<void> {\n let next = 0;\n let failure: { error: unknown } | undefined;\n const worker = async () => {\n while (next < entries.length) {\n const entry = entries[next++]!;\n try {\n await this.reconcileEntry(entry, refresh);\n } catch (error) {\n failure ??= { error };\n if (!this.pendingReconciles.has(entry.binding.id)) this.pendingReconciles.set(entry.binding.id, entry);\n }\n await yieldToEventLoop();\n }\n };\n await Promise.all(Array.from({ length: Math.min(RECONCILE_CONCURRENCY, entries.length) }, worker));\n if (failure) throw failure.error;\n }\n\n private async reconcileEntry(\n entry: { binding: FactoryRunBindingRecord; settled: boolean },\n refresh: boolean,\n ): Promise<void> {\n let binding = entry.binding;\n if (refresh) {\n // Noted at its last step; the card may have moved on and revoked it since.\n const current = await this.options.storage.findRunBindingById({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n id: binding.id,\n });\n if (current?.status !== 'active') {\n this.cursorBoundaries.delete(binding.id);\n return;\n }\n binding = current;\n }\n // Read before the transcript: a run that stops after this check gets its trailing read next pass.\n const running = this.options.isThreadRunning?.(binding.threadId) ?? false;\n await this.reconcileBinding(binding);\n // A step that ran meanwhile already queued it again.\n if (this.pendingReconciles.has(binding.id)) return;\n if (running) this.pendingReconciles.set(binding.id, { binding, settled: false });\n else if (!entry.settled) this.pendingReconciles.set(binding.id, { binding, settled: true });\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const previous = this.bindingReconciles.get(binding.id);\n const run = (async () => {\n if (previous) await previous.catch(() => undefined);\n await this.reconcileBindingNow(binding);\n })();\n this.bindingReconciles.set(binding.id, run);\n try {\n await run;\n } finally {\n if (this.bindingReconciles.get(binding.id) === run) this.bindingReconciles.delete(binding.id);\n }\n }\n\n private async reconcileBindingNow(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(await this.boards.load(binding), item)) {\n this.cursorBoundaries.delete(binding.id);\n return;\n }\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n // The cursor start is inclusive: a message at the cursor time can be rewritten in\n // place (a suspended tool call that later resumes with its result), and several\n // messages can share a timestamp. Messages there that were already ingested and\n // still hold the same results are skipped instead of ingested again every pass.\n const startAt = cursor ? new Date(cursor.lastMessageCreatedAt).getTime() : undefined;\n const previous = this.cursorBoundaries.get(binding.id);\n const ingested = previous && previous.at === startAt ? previous.seen : new Map<string, string>();\n let cursorAt = startAt;\n let boundary = new Map<string, string>();\n let read = false;\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n const fresh = result.messages.filter(\n message => messageTime(message) !== startAt || ingested.get(message.id) !== completedToolCallsKey(message),\n );\n if (fresh.length > 0) await this.ingestMessages(binding, fresh, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n read = true;\n const lastAt = messageTime(last);\n if (lastAt !== cursorAt) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageCreatedAt: new Date(lastAt),\n updatedAt: new Date(),\n });\n cursorAt = lastAt;\n boundary = new Map();\n }\n for (const message of result.messages) {\n if (messageTime(message) === lastAt) boundary.set(message.id, completedToolCallsKey(message));\n }\n }\n if (!result.hasMore) break;\n page += 1;\n await yieldToEventLoop();\n }\n if (read && cursorAt !== undefined) this.cursorBoundaries.set(binding.id, { at: cursorAt, seen: boundary });\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n loaded: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n let item = loaded;\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const finished = finishedPhase(boards, board, item, binding.role, toolResult);\n // The exit tool finished the phase: the card may now leave it (the agent moves it). A result\n // read again later (the step, then the thread) stamps once: the stamp names its tool call.\n const at = new Date().toISOString();\n const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId;\n if (\n finished !== undefined &&\n stampedCall !== toolResult.toolCallId &&\n !exitToolSucceeded(item, finished, toolResult.toolName)\n ) {\n const entry = openEntry(item, finished);\n for (let attempt = 1; ; attempt++) {\n try {\n const stamped = await this.options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n [PHASE_EXIT_METADATA_KEY]: {\n phase: finished,\n tool: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n at,\n },\n ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}),\n },\n },\n expectedRevision: item.revision,\n });\n if (stamped) item = stamped.item;\n break;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n // Another write landed first. While the card is still in the same visit to the phase,\n // the result still finishes it; once the card moved on, it no longer needs finishing.\n const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id });\n if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) {\n return;\n }\n item = current;\n }\n }\n }\n const rule = resolveBoardToolRule(boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId },\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n // The bound agent's own tool call carries the same consent as its governed moves.\n consentedBy: `agent:${binding.id}`,\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n ...(entry.reenter ? { reenter: true } : {}),\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}),\n ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AAEzB,MAAM,wBAAwB;AAE9B,MAAM,6BAA6B;AAEnC,MAAM,yBAAyB,IAAI,SAAc,YAAW,a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U,EAAE,GAAG,MAAM,EAAE;GAChD,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;GAEd,aAAa,SAAS,QAAQ;EAChC,CAAC,EAAA,CACa,WAAW,eAAe,CAAC,KAAK,QAAQ,mBAAmB;EACzE,KAAK,MAAM,SAAS,WAAW;GAC7B,IAAI,MAAM,SAAS,cAAc;GACjC,MAAM,KAAK,QAAQ,kBAAkB,WAAW;IAC9C,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,KAAK;IACjB,OAAO,MAAM;IACb,OAAO,MAAM;IACb,GAAI,MAAM,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;IACzC,kBAAkB,KAAK;IACvB,OAAO;KAAE,MAAM;KAAU,IAAI;IAA2B;IACxD,SAAS;KAAE,MAAM;KAAQ,UAAU,YAAY,MAAM;IAAiB;IACtE,OAAO;IACP,aAAa,CAAC;KAAE;KAAW,cAAc,MAAM;IAAK,CAAC;IACrD,GAAI,qBAAqB,UAAU,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,CAAC;EACH;CACF;AACF"}
|
|
@@ -58,7 +58,7 @@ const FACTORY_ERROR_NAMES = /* @__PURE__ */ new Set([
|
|
|
58
58
|
"LinearReauthRequiredError",
|
|
59
59
|
"MastraGatewayError",
|
|
60
60
|
"MaterializeError",
|
|
61
|
-
"
|
|
61
|
+
"PlatformConnectionNotConnectedError",
|
|
62
62
|
"PullRequestClosedError",
|
|
63
63
|
"RealtimeSessionError",
|
|
64
64
|
"ReviewBoardInUseError",
|