@mastra/factory 0.18.0 → 0.19.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +13 -1
  2. package/dist/boards/registry.d.ts.map +1 -1
  3. package/dist/boards/registry.js +0 -2
  4. package/dist/boards/registry.js.map +1 -1
  5. package/dist/factory.d.ts.map +1 -1
  6. package/dist/factory.js +12 -2
  7. package/dist/factory.js.map +1 -1
  8. package/dist/integrations/github/default-rules.d.ts +10 -2
  9. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  10. package/dist/integrations/github/default-rules.js +28 -4
  11. package/dist/integrations/github/default-rules.js.map +1 -1
  12. package/dist/integrations/github/integration.js +1 -1
  13. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  14. package/dist/integrations/github/reconcile-worker.js +1 -2
  15. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  16. package/dist/integrations/github/routes.d.ts.map +1 -1
  17. package/dist/integrations/github/routes.js +2 -15
  18. package/dist/integrations/github/routes.js.map +1 -1
  19. package/dist/integrations/github/rules.d.ts +5 -0
  20. package/dist/integrations/github/rules.d.ts.map +1 -1
  21. package/dist/integrations/github/rules.js +17 -8
  22. package/dist/integrations/github/rules.js.map +1 -1
  23. package/dist/integrations/github/stale-reviews.d.ts +22 -0
  24. package/dist/integrations/github/stale-reviews.d.ts.map +1 -0
  25. package/dist/integrations/github/stale-reviews.js +70 -0
  26. package/dist/integrations/github/stale-reviews.js.map +1 -0
  27. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  28. package/dist/integrations/gitlab/version-control.js +4 -5
  29. package/dist/integrations/gitlab/version-control.js.map +1 -1
  30. package/dist/integrations/gitlab/webhook.d.ts.map +1 -1
  31. package/dist/integrations/gitlab/webhook.js +2 -2
  32. package/dist/integrations/gitlab/webhook.js.map +1 -1
  33. package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
  34. package/dist/integrations/issue-reconcile-worker.js +1 -2
  35. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  36. package/dist/integrations/jira/integration.d.ts.map +1 -1
  37. package/dist/integrations/jira/integration.js +7 -1
  38. package/dist/integrations/jira/integration.js.map +1 -1
  39. package/dist/integrations/linear/integration.d.ts.map +1 -1
  40. package/dist/integrations/linear/integration.js +10 -30
  41. package/dist/integrations/linear/integration.js.map +1 -1
  42. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  43. package/dist/integrations/platform/github/event-worker.js +1 -2
  44. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  45. package/dist/integrations/platform/github/integration.js +1 -1
  46. package/dist/integrations/platform/gitlab/event-worker.d.ts.map +1 -1
  47. package/dist/integrations/platform/gitlab/event-worker.js +1 -2
  48. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  49. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  50. package/dist/integrations/platform/jira/integration.js +7 -1
  51. package/dist/integrations/platform/jira/integration.js.map +1 -1
  52. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  53. package/dist/integrations/platform/linear/event-worker.js +1 -2
  54. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  55. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  56. package/dist/integrations/platform/linear/integration.js +9 -9
  57. package/dist/integrations/platform/linear/integration.js.map +1 -1
  58. package/dist/integrations/slack/slack.d.ts.map +1 -1
  59. package/dist/integrations/slack/slack.js +1 -2
  60. package/dist/integrations/slack/slack.js.map +1 -1
  61. package/dist/review-verdict.d.ts +6 -0
  62. package/dist/review-verdict.d.ts.map +1 -0
  63. package/dist/review-verdict.js +14 -0
  64. package/dist/review-verdict.js.map +1 -0
  65. package/dist/routes/attention-providers.d.ts +6 -7
  66. package/dist/routes/attention-providers.d.ts.map +1 -1
  67. package/dist/routes/attention-providers.js +12 -5
  68. package/dist/routes/attention-providers.js.map +1 -1
  69. package/dist/routes/attention.d.ts +2 -0
  70. package/dist/routes/attention.d.ts.map +1 -1
  71. package/dist/routes/attention.js +9 -3
  72. package/dist/routes/attention.js.map +1 -1
  73. package/dist/routes/oauth.d.ts.map +1 -1
  74. package/dist/routes/oauth.js +3 -3
  75. package/dist/routes/oauth.js.map +1 -1
  76. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  77. package/dist/routes/source-control-sessions.js +1 -2
  78. package/dist/routes/source-control-sessions.js.map +1 -1
  79. package/dist/routes/work-items.d.ts.map +1 -1
  80. package/dist/routes/work-items.js +10 -5
  81. package/dist/routes/work-items.js.map +1 -1
  82. package/dist/rules/decision-applicability.d.ts +26 -0
  83. package/dist/rules/decision-applicability.d.ts.map +1 -0
  84. package/dist/rules/decision-applicability.js +47 -0
  85. package/dist/rules/decision-applicability.js.map +1 -0
  86. package/dist/rules/dispatcher.d.ts +4 -0
  87. package/dist/rules/dispatcher.d.ts.map +1 -1
  88. package/dist/rules/dispatcher.js +33 -24
  89. package/dist/rules/dispatcher.js.map +1 -1
  90. package/dist/rules/processor.d.ts.map +1 -1
  91. package/dist/rules/processor.js +5 -5
  92. package/dist/rules/processor.js.map +1 -1
  93. package/dist/rules/transition-service.d.ts.map +1 -1
  94. package/dist/rules/transition-service.js +1 -2
  95. package/dist/rules/transition-service.js.map +1 -1
  96. package/dist/rules/types.d.ts +18 -1
  97. package/dist/rules/types.d.ts.map +1 -1
  98. package/dist/rules/types.js.map +1 -1
  99. package/dist/rules/validation.d.ts.map +1 -1
  100. package/dist/rules/validation.js +20 -0
  101. package/dist/rules/validation.js.map +1 -1
  102. package/dist/secret-encryption.js +2 -2
  103. package/dist/secret-encryption.js.map +1 -1
  104. package/dist/session/factory-session.d.ts.map +1 -1
  105. package/dist/session/factory-session.js +1 -2
  106. package/dist/session/factory-session.js.map +1 -1
  107. package/dist/session/source-control-tools.d.ts +9 -0
  108. package/dist/session/source-control-tools.d.ts.map +1 -1
  109. package/dist/session/source-control-tools.js +51 -2
  110. package/dist/session/source-control-tools.js.map +1 -1
  111. package/dist/state-signing.js +3 -3
  112. package/dist/state-signing.js.map +1 -1
  113. package/dist/storage/domains/audit/base.d.ts.map +1 -1
  114. package/dist/storage/domains/audit/base.js +2 -3
  115. package/dist/storage/domains/audit/base.js.map +1 -1
  116. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  117. package/dist/storage/domains/source-control/inmemory.js +5 -6
  118. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  119. package/dist/storage/domains/work-items/base.d.ts +3 -0
  120. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  121. package/dist/storage/domains/work-items/base.js +15 -2
  122. package/dist/storage/domains/work-items/base.js.map +1 -1
  123. package/dist/supervisor/write-tools.d.ts +2 -0
  124. package/dist/supervisor/write-tools.d.ts.map +1 -1
  125. package/dist/supervisor/write-tools.js +3 -0
  126. package/dist/supervisor/write-tools.js.map +1 -1
  127. package/factory-skills/configure-factory-rules/SKILL.md +1 -1
  128. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  129. package/factory-skills/factory-gitlab-review/SKILL.md +1 -1
  130. package/factory-skills/factory-rereview/SKILL.md +12 -3
  131. package/factory-skills/factory-review/SKILL.md +12 -3
  132. package/package.json +9 -9
@@ -1,3 +1,4 @@
1
+ import type { BoardRegistry } from '../boards/index.js';
1
2
  import type { IntegrationTools } from '../integrations/base.js';
2
3
  import type { FactoryTransitionService } from '../rules/transition-service.js';
3
4
  import type { AuditRecorder } from '../storage/domains/audit/domain.js';
@@ -8,6 +9,7 @@ interface SupervisorWriteDependencies {
8
9
  scope: SupervisorScope;
9
10
  userId: string;
10
11
  workItems: WorkItemsStorage;
12
+ boards: BoardRegistry;
11
13
  audit: AuditRecorder;
12
14
  transitionService: FactoryTransitionService;
13
15
  reconcileAcceptanceLabels?: (input: {
@@ -1 +1 @@
1
- {"version":3,"file":"write-tools.d.ts","sourceRoot":"","sources":["../../src/supervisor/write-tools.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,E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OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAG/E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElE,UAAU,2BAA2B;IACnC,KAAK,EAAE,eAAe,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,gBAAgB,CAAC;IAC5B,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,EAAE,aAAa,CAAC;IACrB,iBAAiB,EAAE,wBAAwB,CAAC;IAC5C,yBAAyB,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,WAAW,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrH,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE;QACvB,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;KAC5B,KAAK,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACnC,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;CAClB;AAED,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,2BAA2B,GAAG,gBAAgB,CAoNrG"}
@@ -1,6 +1,7 @@
1
1
  import { BOARD_IDENTIFIER_RE } from "../rules/validation.js";
2
2
  import { boardForWorkItem } from "../boards/semantics.js";
3
3
  import "../boards/index.js";
4
+ import { overtakenDecisionIds } from "../rules/decision-applicability.js";
4
5
  import { createTool } from "@mastra/core/tools";
5
6
  import { z } from "zod";
6
7
  //#region src/supervisor/write-tools.ts
@@ -26,6 +27,8 @@ function createFactorySupervisorWriteTools(deps) {
26
27
  inputSchema: z.object({ decisionId: z.string().min(1) }),
27
28
  requireApproval: true,
28
29
  execute: async ({ decisionId }) => {
30
+ const current = await deps.workItems.getDeferredDecision(deps.scope.orgId, deps.scope.factoryProjectId, decisionId);
31
+ if (current && (await overtakenDecisionIds(deps.workItems, deps.boards, deps.scope, [current])).size > 0) throw new Error("The work item has moved on from the phase this run was decided for; it cannot be retried.");
29
32
  const decision = await deps.workItems.retryDeferredDecision(deps.scope.orgId, deps.scope.factoryProjectId, decisionId, now());
30
33
  if (!decision) throw new Error("The decision is not failed, no longer exists, or belongs to another factory.");
31
34
  await audit("factory.run.retry", {
@@ -1 +1 @@
1
- {"version":3,"file":"write-tools.js","names":[],"sources":["../../src/supervisor/write-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from '../rules/validation.js';\nimport type { AuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SupervisorScope } from './read-tools.js';\nimport type { WorkerMessageResult } from './session-messaging.js';\n\ninterface SupervisorWriteDependencies {\n scope: SupervisorScope;\n userId: string;\n workItems: WorkItemsStorage;\n audit: AuditRecorder;\n transitionService: FactoryTransitionService;\n reconcileAcceptanceLabels?: (input: { orgId: string; factoryProjectId: string; item: WorkItemRow }) => Promise<void>;\n messageSession?: (input: {\n sessionId: string;\n message: string;\n userId: string;\n delivery: 'send' | 'queue';\n }) => Promise<WorkerMessageResult>;\n now?: () => Date;\n}\n\nexport function createFactorySupervisorWriteTools(deps: SupervisorWriteDependencies): IntegrationTools {\n const now = deps.now ?? (() => new Date());\n const audit = async (\n action: AuditAction,\n target: { type: string; id: string },\n metadata: Record<string, unknown> = {},\n ) =>\n deps.audit.record({\n orgId: deps.scope.orgId,\n actorId: deps.userId,\n actorType: 'human',\n action,\n targets: [target],\n factoryProjectId: deps.scope.factoryProjectId,\n metadata: { ...metadata, cause: 'supervisor' },\n occurredAt: now(),\n });\n\n return {\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description: 'Retry one failed Factory decision after the person confirms the repair.',\n inputSchema: z.object({ decisionId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ decisionId }) => {\n const decision = await deps.workItems.retryDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision) throw new Error('The decision is not failed, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.run.retry',\n { type: 'rule_decision', id: decisionId },\n { workItemId: decision.workItemId },\n );\n return { decisionId, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one parked Factory proposal after the person confirms it is no longer wanted.',\n inputSchema: z.object({ decisionId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ decisionId }) => {\n const decision = await deps.workItems.dismissDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision)\n throw new Error('The decision is not proposed, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.run.dismissed',\n { type: 'rule_decision', id: decisionId },\n { workItemId: decision.workItemId },\n );\n return { decisionId, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description: 'Approve or dismiss one proposed Factory decision after the person confirms the choice.',\n inputSchema: z.object({ decisionId: z.string().min(1), resolution: z.enum(['approve', 'dismiss']) }),\n requireApproval: true,\n execute: async ({ decisionId, resolution }) => {\n const decision =\n resolution === 'approve'\n ? await deps.workItems.approveDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n deps.userId,\n )\n : await deps.workItems.dismissDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision) throw new Error('The proposal is no longer open or belongs to another factory.');\n await audit(\n resolution === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n {\n type: 'rule_decision',\n id: decisionId,\n },\n { workItemId: decision.workItemId },\n );\n return { decisionId, resolution, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description: 'Move or accept one Factory work item after the person confirms the destination stage.',\n inputSchema: z.object({\n workItemId: z.string().min(1),\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n }),\n requireApproval: true,\n execute: async ({ workItemId, stage }) => {\n const item = await deps.workItems.get({ orgId: deps.scope.orgId, id: workItemId });\n if (!item || item.factoryProjectId !== deps.scope.factoryProjectId) throw new Error('Work item not found.');\n const from = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!from) throw new Error('The work item does not have one valid Factory stage.');\n const result = await deps.transitionService.transition({\n orgId: deps.scope.orgId,\n factoryProjectId: deps.scope.factoryProjectId,\n workItemId,\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n actor: { type: 'human', id: deps.userId },\n ingress: { type: 'human', identity: `supervisor:${deps.userId}:${workItemId}:${item.revision}:${stage}` },\n cause: 'supervisor',\n });\n if (result.status !== 'accepted') {\n throw new Error(`The transition was rejected (${result.code}): ${result.reason}`);\n }\n return result;\n },\n }),\n factory_reconcile_labels: createTool({\n id: 'factory_reconcile_labels',\n description: 'Reconcile stale acceptance labels for one accepted work item after the person confirms the repair.',\n inputSchema: z.object({ workItemId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ workItemId }) => {\n if (!deps.reconcileAcceptanceLabels) throw new Error('Acceptance-label reconciliation is unavailable.');\n const item = await deps.workItems.get({ orgId: deps.scope.orgId, id: workItemId });\n if (!item || item.factoryProjectId !== deps.scope.factoryProjectId) throw new Error('Work item not found.');\n if (!item.acceptedAt) throw new Error('The work item has not been accepted.');\n await deps.reconcileAcceptanceLabels({ ...deps.scope, item });\n await audit('factory.work_item.labels_reconciled', { type: 'work_item', id: workItemId });\n return { workItemId, reconciled: true };\n },\n }),\n factory_revoke_binding: createTool({\n id: 'factory_revoke_binding',\n description: 'Revoke an orphaned or stale run binding after a health finding and person confirmation.',\n inputSchema: z.object({ bindingId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ bindingId }) => {\n const binding = await deps.workItems.revokeRunBinding({\n orgId: deps.scope.orgId,\n factoryProjectId: deps.scope.factoryProjectId,\n bindingId,\n revokedAt: now(),\n });\n if (!binding) throw new Error('The binding is not active, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.intake.binding_updated',\n { type: 'run_binding', id: bindingId },\n {\n workItemId: binding.workItemId,\n role: binding.role,\n status: 'revoked',\n },\n );\n return { bindingId, status: binding.status, workItemId: binding.workItemId, role: binding.role };\n },\n }),\n factory_signal_session: createTool({\n id: 'factory_signal_session',\n description:\n 'Send bounded guidance to a worker session after the person confirms the exact message. Use queue only when the guidance should wait for the current run to finish.',\n inputSchema: z.object({\n sessionId: z.string().min(1),\n message: z.string().trim().min(1).max(2000),\n delivery: z.enum(['send', 'queue']).default('send'),\n }),\n requireApproval: true,\n execute: async ({ sessionId, message, delivery }) => {\n if (!deps.messageSession) throw new Error('Worker session messaging is unavailable.');\n const bindings = await deps.workItems.listRunBindings(deps.scope.orgId, deps.scope.factoryProjectId);\n const binding = bindings.find(row => row.sessionId === sessionId);\n if (!binding) throw new Error('The session does not belong to this factory.');\n const result = await deps.messageSession({ sessionId, message, userId: deps.userId, delivery });\n if (result?.status === 'interrupted') {\n return {\n sessionId,\n delivered: false,\n status: 'interrupted',\n delivery,\n workItemId: binding.workItemId,\n role: binding.role,\n };\n }\n await audit(\n 'factory.agent.signaled',\n { type: 'factory_session', id: sessionId },\n {\n workItemId: binding.workItemId,\n role: binding.role,\n delivery,\n },\n );\n return { sessionId, delivered: true, delivery, workItemId: binding.workItemId, role: binding.role };\n },\n }),\n };\n}\n"],"mappings":";;;;;;AA6BA,SAAgB,kCAAkC,MAAqD;CACrG,MAAM,MAAM,KAAK,8BAAc,IAAI,KAAK;CACxC,MAAM,QAAQ,OACZ,QACA,QACA,WAAoC,CAAC,MAErC,KAAK,MAAM,OAAO;EAChB,OAAO,KAAK,MAAM;EAClB,SAAS,KAAK;EACd,WAAW;EACX;EACA,SAAS,CAAC,MAAM;EAChB,kBAAkB,KAAK,MAAM;EAC7B,UAAU;GAAE,GAAG;GAAU,OAAO;EAAa;EAC7C,YAAY,IAAI;CAClB,CAAC;CAEH,OAAO;EACL,wBAAwB,WAAW;GACjC,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACvD,iBAAiB;GACjB,SAAS,OAAO,EAAE,iBAAiB;IACjC,MAAM,WAAW,MAAM,KAAK,UAAU,sBACpC,KAAK,MAAM,OACX,KAAK,MAAM,kBACX,YACA,IAAI,CACN;IACA,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8EAA8E;IAC7G,MAAM,MACJ,qBACA;KAAE,MAAM;KAAiB,IAAI;IAAW,GACxC,EAAE,YAAY,SAAS,WAAW,CACpC;IACA,OAAO;KAAE;KAAY,QAAQ,SAAS;KAAQ,YAAY,SAAS;IAAW;GAChF;EACF,CAAC;EACD,0BAA0B,WAAW;GACnC,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACvD,iBAAiB;GACjB,SAAS,OAAO,EAAE,iBAAiB;IACjC,MAAM,WAAW,MAAM,KAAK,UAAU,wBACpC,KAAK,MAAM,O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IAE5E,KAAI,MADiB,KAAK,eAAe;KAAE;KAAW;KAAS,QAAQ,KAAK;KAAQ;IAAS,CAAC,EAAA,EAClF,WAAW,eACrB,OAAO;KACL;KACA,WAAW;KACX,QAAQ;KACR;KACA,YAAY,QAAQ;KACpB,MAAM,QAAQ;IAChB;IAEF,MAAM,MACJ,0BACA;KAAE,MAAM;KAAmB,IAAI;IAAU,GACzC;KACE,YAAY,QAAQ;KACpB,MAAM,QAAQ;KACd;IACF,CACF;IACA,OAAO;KAAE;KAAW,WAAW;KAAM;KAAU,YAAY,QAAQ;KAAY,MAAM,QAAQ;IAAK;GACpG;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"write-tools.js","names":[],"sources":["../../src/supervisor/write-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { overtakenDecisionIds } from '../rules/decision-applicability.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from '../rules/validation.js';\nimport type { AuditAction } from '../storage/domains/audit/actions.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SupervisorScope } from './read-tools.js';\nimport type { WorkerMessageResult } from './session-messaging.js';\n\ninterface SupervisorWriteDependencies {\n scope: SupervisorScope;\n userId: string;\n workItems: WorkItemsStorage;\n boards: BoardRegistry;\n audit: AuditRecorder;\n transitionService: FactoryTransitionService;\n reconcileAcceptanceLabels?: (input: { orgId: string; factoryProjectId: string; item: WorkItemRow }) => Promise<void>;\n messageSession?: (input: {\n sessionId: string;\n message: string;\n userId: string;\n delivery: 'send' | 'queue';\n }) => Promise<WorkerMessageResult>;\n now?: () => Date;\n}\n\nexport function createFactorySupervisorWriteTools(deps: SupervisorWriteDependencies): IntegrationTools {\n const now = deps.now ?? (() => new Date());\n const audit = async (\n action: AuditAction,\n target: { type: string; id: string },\n metadata: Record<string, unknown> = {},\n ) =>\n deps.audit.record({\n orgId: deps.scope.orgId,\n actorId: deps.userId,\n actorType: 'human',\n action,\n targets: [target],\n factoryProjectId: deps.scope.factoryProjectId,\n metadata: { ...metadata, cause: 'supervisor' },\n occurredAt: now(),\n });\n\n return {\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description: 'Retry one failed Factory decision after the person confirms the repair.',\n inputSchema: z.object({ decisionId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ decisionId }) => {\n const current = await deps.workItems.getDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n );\n if (current && (await overtakenDecisionIds(deps.workItems, deps.boards, deps.scope, [current])).size > 0) {\n throw new Error('The work item has moved on from the phase this run was decided for; it cannot be retried.');\n }\n const decision = await deps.workItems.retryDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision) throw new Error('The decision is not failed, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.run.retry',\n { type: 'rule_decision', id: decisionId },\n { workItemId: decision.workItemId },\n );\n return { decisionId, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one parked Factory proposal after the person confirms it is no longer wanted.',\n inputSchema: z.object({ decisionId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ decisionId }) => {\n const decision = await deps.workItems.dismissDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision)\n throw new Error('The decision is not proposed, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.run.dismissed',\n { type: 'rule_decision', id: decisionId },\n { workItemId: decision.workItemId },\n );\n return { decisionId, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description: 'Approve or dismiss one proposed Factory decision after the person confirms the choice.',\n inputSchema: z.object({ decisionId: z.string().min(1), resolution: z.enum(['approve', 'dismiss']) }),\n requireApproval: true,\n execute: async ({ decisionId, resolution }) => {\n const decision =\n resolution === 'approve'\n ? await deps.workItems.approveDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n deps.userId,\n )\n : await deps.workItems.dismissDeferredDecision(\n deps.scope.orgId,\n deps.scope.factoryProjectId,\n decisionId,\n now(),\n );\n if (!decision) throw new Error('The proposal is no longer open or belongs to another factory.');\n await audit(\n resolution === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n {\n type: 'rule_decision',\n id: decisionId,\n },\n { workItemId: decision.workItemId },\n );\n return { decisionId, resolution, status: decision.status, workItemId: decision.workItemId };\n },\n }),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description: 'Move or accept one Factory work item after the person confirms the destination stage.',\n inputSchema: z.object({\n workItemId: z.string().min(1),\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n }),\n requireApproval: true,\n execute: async ({ workItemId, stage }) => {\n const item = await deps.workItems.get({ orgId: deps.scope.orgId, id: workItemId });\n if (!item || item.factoryProjectId !== deps.scope.factoryProjectId) throw new Error('Work item not found.');\n const from = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!from) throw new Error('The work item does not have one valid Factory stage.');\n const result = await deps.transitionService.transition({\n orgId: deps.scope.orgId,\n factoryProjectId: deps.scope.factoryProjectId,\n workItemId,\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n actor: { type: 'human', id: deps.userId },\n ingress: { type: 'human', identity: `supervisor:${deps.userId}:${workItemId}:${item.revision}:${stage}` },\n cause: 'supervisor',\n });\n if (result.status !== 'accepted') {\n throw new Error(`The transition was rejected (${result.code}): ${result.reason}`);\n }\n return result;\n },\n }),\n factory_reconcile_labels: createTool({\n id: 'factory_reconcile_labels',\n description: 'Reconcile stale acceptance labels for one accepted work item after the person confirms the repair.',\n inputSchema: z.object({ workItemId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ workItemId }) => {\n if (!deps.reconcileAcceptanceLabels) throw new Error('Acceptance-label reconciliation is unavailable.');\n const item = await deps.workItems.get({ orgId: deps.scope.orgId, id: workItemId });\n if (!item || item.factoryProjectId !== deps.scope.factoryProjectId) throw new Error('Work item not found.');\n if (!item.acceptedAt) throw new Error('The work item has not been accepted.');\n await deps.reconcileAcceptanceLabels({ ...deps.scope, item });\n await audit('factory.work_item.labels_reconciled', { type: 'work_item', id: workItemId });\n return { workItemId, reconciled: true };\n },\n }),\n factory_revoke_binding: createTool({\n id: 'factory_revoke_binding',\n description: 'Revoke an orphaned or stale run binding after a health finding and person confirmation.',\n inputSchema: z.object({ bindingId: z.string().min(1) }),\n requireApproval: true,\n execute: async ({ bindingId }) => {\n const binding = await deps.workItems.revokeRunBinding({\n orgId: deps.scope.orgId,\n factoryProjectId: deps.scope.factoryProjectId,\n bindingId,\n revokedAt: now(),\n });\n if (!binding) throw new Error('The binding is not active, no longer exists, or belongs to another factory.');\n await audit(\n 'factory.intake.binding_updated',\n { type: 'run_binding', id: bindingId },\n {\n workItemId: binding.workItemId,\n role: binding.role,\n status: 'revoked',\n },\n );\n return { bindingId, status: binding.status, workItemId: binding.workItemId, role: binding.role };\n },\n }),\n factory_signal_session: createTool({\n id: 'factory_signal_session',\n description:\n 'Send bounded guidance to a worker session after the person confirms the exact message. Use queue only when the guidance should wait for the current run to finish.',\n inputSchema: z.object({\n sessionId: z.string().min(1),\n message: z.string().trim().min(1).max(2000),\n delivery: z.enum(['send', 'queue']).default('send'),\n }),\n requireApproval: true,\n execute: async ({ sessionId, message, delivery }) => {\n if (!deps.messageSession) throw new Error('Worker session messaging is unavailable.');\n const bindings = await deps.workItems.listRunBindings(deps.scope.orgId, deps.scope.factoryProjectId);\n const binding = bindings.find(row => row.sessionId === sessionId);\n if (!binding) throw new Error('The session does not belong to this factory.');\n const result = await deps.messageSession({ sessionId, message, userId: deps.userId, delivery });\n if (result?.status === 'interrupted') {\n return {\n sessionId,\n delivered: false,\n status: 'interrupted',\n delivery,\n workItemId: binding.workItemId,\n role: binding.role,\n };\n }\n await audit(\n 'factory.agent.signaled',\n { type: 'factory_session', id: sessionId },\n {\n workItemId: binding.workItemId,\n role: binding.role,\n delivery,\n },\n );\n return { sessionId, delivered: true, delivery, workItemId: binding.workItemId, role: binding.role };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,kCAAkC,MAAqD;CACrG,MAAM,MAAM,KAAK,8BAAc,IAAI,KAAK;CACxC,MAAM,QAAQ,OACZ,QACA,QACA,WAAoC,CAAC,MAErC,KAAK,MAAM,OAAO;EAChB,OAAO,KAAK,MAAM;EAClB,SAAS,KAAK;EACd,WAAW;EACX;EACA,SAAS,CAAC,MAAM;EAChB,kBAAkB,KAAK,MAAM;EAC7B,UAAU;GAAE,GAAG;GAAU,OAAO;EAAa;EAC7C,YAAY,IAAI;CAClB,CAAC;CAEH,OAAO;EACL,wBAAwB,WAAW;GACjC,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACvD,iBAAiB;GACjB,SAAS,OAAO,EAAE,iBAAiB;IACjC,MAAM,UAAU,MAAM,KAAK,UAAU,oBACnC,KAAK,MAAM,OACX,KAAK,MAAM,kBACX,UACF;IACA,IAAI,YAAY,MAAM,qBAAqB,KAAK,WAAW,KAAK,QAAQ,KAAK,OAAO,CAAC,OAAO,CAAC,EAAA,CAAG,OAAO,GACrG,MAAM,IAAI,MAAM,2FAA2F;IAE7G,MAAM,WAAW,MAAM,KAAK,UAAU,sBACpC,KAAK,MAAM,OACX,KAAK,MAAM,kBACX,YACA,IAAI,CACN;IACA,IAAI,CAAC,UAAU,MAAM,IAAI,M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AAI,CAAC,CAAC,CAAC,IAAI,GAAI;IAC1C,UAAU,EAAE,KAAK,CAAC,QAAQ,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM;GACpD,CAAC;GACD,iBAAiB;GACjB,SAAS,OAAO,EAAE,WAAW,SAAS,eAAe;IACnD,IAAI,CAAC,KAAK,gBAAgB,MAAM,IAAI,MAAM,0CAA0C;IAEpF,MAAM,WAAU,MADO,KAAK,UAAU,gBAAgB,KAAK,MAAM,OAAO,KAAK,MAAM,gBAAgB,EAAA,CAC1E,MAAK,QAAO,IAAI,cAAc,SAAS;IAChE,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,8CAA8C;IAE5E,KAAI,MADiB,KAAK,eAAe;KAAE;KAAW;KAAS,QAAQ,KAAK;KAAQ;IAAS,CAAC,EAAA,EAClF,WAAW,eACrB,OAAO;KACL;KACA,WAAW;KACX,QAAQ;KACR;KACA,YAAY,QAAQ;KACpB,MAAM,QAAQ;IAChB;IAEF,MAAM,MACJ,0BACA;KAAE,MAAM;KAAmB,IAAI;IAAU,GACzC;KACE,YAAY,QAAQ;KACpB,MAAM,QAAQ;KACd;IACF,CACF;IACA,OAAO;KAAE;KAAW,WAAW;KAAM;KAAU,YAAY,QAAQ;KAAY,MAAM,QAAQ;IAAK;GACpG;EACF,CAAC;CACH;AACF"}
@@ -20,7 +20,7 @@ Do not guess a file path. Factory deployments can assemble `MastraFactory` from
20
20
 
21
21
  Installed board definitions exclusively own lifecycle handlers: use `phases.<phase>.onEnter.<source>` and `phases.<phase>.onExit.<source>` in `defineBoard()`. Sources are `issue`, `pullRequest`, `linearIssue`, and `manual`. Work and Review install automatically with preferred defaults. Custom boards are installed through `boards`; `includeDefaultBoards: false` supports custom-only installations.
22
22
 
23
- Remove former global `rules.work` and `rules.review` configuration. Built-in customization is deferred: do not invent a board override API, derive replacements, or use reserved IDs `work` and `review`. There is no global rules tree; `new MastraFactory({ rules })` throws. Set `configVersion` on `MastraFactory` for the audit label. Tool-result rules resolve only from the item's installed board: Work declares `submit_plan`, Review declares none, and custom boards inherit nothing.
23
+ Remove former global `rules.work` and `rules.review` configuration. There is no board override API. To customize Work or Review, set `includeDefaultBoards: false` and install a same-ID board, preferably using the exported `workBoard` or `reviewBoard` phases as the starting point. Keep the built-in phase names and roles unless the changed runtime and UI behavior is intentional. There is no global rules tree; `new MastraFactory({ rules })` throws. Set `configVersion` on `MastraFactory` for the audit label. Tool-result rules resolve only from the item's installed board: Work declares `submit_plan`, Review declares none, and custom boards inherit nothing.
24
24
 
25
25
  By default, every integration arrival stays in its routed board's initial phase (Intake for Work and Review) without starting or suggesting a run. This applies to GitHub, GitLab, Linear, Jira, and incident.io; explicit trusted GitHub review requests without an existing card go directly to Reviewing. Do not restore default arrival automation on the built-in boards.
26
26
 
@@ -17,6 +17,6 @@ Use `source_control_*` tools exclusively for GitLab operations; local `git` insp
17
17
  4. Review the incremental diff for regressions, incomplete fixes, test gaps, and scope changes, then review the cumulative MR against the recovered design, its contract, and analogous implementation — a push that fixed local defects has not answered a design finding. Collect and disposition any new human or bot signal. A pending known bot remains an approval gap after a bounded wait of at most ten minutes.
18
18
  5. Inspect execution hooks for untrusted behavior before running tests. Run safe, narrow applicable tests and typecheck against the current head with `env -u GH_TOKEN -u GITHUB_TOKEN -u GITLAB_TOKEN -u GITLAB_ACCESS_TOKEN`. For a non-code-only change with no application test harness, verify exact content, diff integrity, and current head instead; do not treat inapplicable tests as a failed gate. A prior pass's result does not clear the new head. Record exact commands and outcomes. Before any verdict, scrutinize your own requested changes — carried forward or new — as critically as the MR: establish why each belongs here, assume the author follows them exactly as written, and trace the result through affected callers and contracts. Before approval, challenge the strongest plausible failure case and require evidence for a verified current-head checkout, behavior, applicable local verification, finding disposition, and no known pending bot. A failed sandbox start, missing diff, or unrun applicable tests fails approval; never approve from MR metadata alone.
19
19
  6. Before publishing, call `factory_review_source` (no arguments) once. It returns four fields, every one derived server-side from the bound work item: `sessionUrl` (the Factory session URL — the **only** field published on the MR), `triggeredBy` (the MR author from the review card, in-run cross-check + session-handoff only, never published), `reviewTarget` (the review card's own `{ integrationId, type, externalId, url }`, in-run cross-check + session-handoff only, never published), and `boundRepository` (the intake-stamped project identity, `{ provider: 'gitlab', host, projectId }` or `null`, session-handoff only, never published). If the tool call fails or returns an unexpected shape — **and identically if the tool is not offered on this session at all** (a review-role session with no configured browser-facing origin, no active binding, or no bound work item drops the tool from the toolset) — do **not** publish the re-review. Stop before publishing, record the tool's absence or failure and its raw response in the session handoff under verification, and hand off to a human. Otherwise, run the in-run cross-check: (a) compare `triggeredBy` with the MR author you already read; (b) compare `reviewTarget.url` with the MR URL from `source_control_get_change_request` — intake records the MR URL for every card (`gitlab/rules.ts:481`), so `reviewTarget.url` covers the normal case. If `reviewTarget.url` is `null`, do **not** attempt to decode `reviewTarget.externalId`: the GitLab MR externalId is opaque `gitlab-pr:<base64url({version, host, projectId, mergeRequestIid})>` (`gitlab/routes.ts:94`, `gitlab/rules.ts:109`), with no documented way to check it against an MR IID. The bound identity itself is not the gap — the tool returns the intake-stamped `boundRepository`, and the MR fetch is binding-scoped (`session/source-control-tools.ts` resolves the repository from the session record, so it cannot return another project's MR) — but the normalized change-request result carries no numeric project id or intake identifier to compare it against, and a matching `triggeredBy` author cannot distinguish two MRs by the same author within the project. With no URL, nothing confirms the fetched MR **is the card's MR**. Do not publish: record the `reviewTarget.url` gap and both raw values in the session handoff, skip the verdict call, and hand off to a human. On any mismatch, stop and record a blocking security finding with both values verbatim; do **not** publish anything on the MR — posting any verdict (a request-changes comment included) puts a review on an MR that may be the wrong one. Re-read the MR with `source_control_get_change_request` once and re-run the cross-check; publish only if the fresh check matches, otherwise record the mismatch in the **Factory routing** block, skip the verdict call, and hand off to a human. When publication does proceed, include only `sessionUrl` as a `Factory Session` section at the end of every published body (approve, request-changes comment, and the approval-fallback comment).
20
- 7. Publish a complete current-head verdict with `source_control_review_change_request`. Use `approve` only when all applicable gates pass; otherwise use `comment` with `Verdict: request changes` and an actionable defect or verification gap because GitLab has no request-changes review state. If approval is rejected for a confirmed authorization reason (self-review or missing permission), keep the substantive approve verdict: make a separate `source_control_comment_change_request` call with `Verdict: approve (approval not recorded)` and explain the rejection. Confirm that this fallback comment succeeded before recording the verdict. For any other rejection, refresh the checkout, re-establish the current head, and re-run the substantive review and approval gates against the refreshed head before retrying; a provider rejection is not a reason to switch to request changes, an approval evaluated against a head that has since changed is never published, and a retry that still fails means no verdict was posted — report the failure. Never claim a formal approval that was not recorded, and never merge the MR.
20
+ 7. Publish a complete current-head verdict with `source_control_review_change_request`. Compose the body fresh in this pass — never reuse an earlier pass's body. It opens with the verdict line (`Verdict: approve` or `Verdict: request changes`), then `Reviewed head: <full SHA>` equal to the current MR head, the `commitId`, and the `reviewedHeadSha` you record. The tool rejects a body whose verdict line contradicts `event` or whose reviewed head is stale; regenerate the body in that case, never flip the event to match it. Use `approve` only when all applicable gates pass; otherwise use `comment` with `Verdict: request changes` and an actionable defect or verification gap because GitLab has no request-changes review state. If approval is rejected for a confirmed authorization reason (self-review or missing permission), keep the substantive approve verdict: first re-read the MR with `source_control_get_change_request` and confirm its head still equals the head you reviewed — if it moved, do not post the fallback; refresh and re-run the review gates against the new head. Then make a separate `source_control_comment_change_request` call whose body opens with `Verdict: approve (approval not recorded)`, then `Reviewed head: <full SHA>` naming that verified head, and explains the rejection. Confirm that this fallback comment succeeded before recording the verdict. For any other rejection, refresh the checkout, re-establish the current head, and re-run the substantive review and approval gates against the refreshed head before retrying; a provider rejection is not a reason to switch to request changes, an approval evaluated against a head that has since changed is never published, and a retry that still fails means no verdict was posted — report the failure. Never claim a formal approval that was not recorded, and never merge the MR.
21
21
 
22
22
  First call `factory_record_review_verdict` with the published `verdict` and the verified `reviewedHeadSha`. If rejected, address the reason before retrying; the handoff must report whether the card was updated. The card stays in Reviewing; never request a stage transition to end the re-review. Then, as the terminal action, provide a session handoff with MR URL/current head, incremental and cumulative findings, a disposition for every prior finding, tests, assumptions, gaps, the actual publication outcome, the `Factory Session` block (`sessionUrl` only, matching the MR body), and a **Factory routing** block that records `triggeredBy` verbatim, `reviewTarget` verbatim (`integrationId`, `type`, `externalId`, `url`), `boundRepository` verbatim, and the cross-check outcome — "matched" with the compared MR value or "mismatch: <blocking-finding-ref>".
@@ -43,6 +43,6 @@ Otherwise, run the in-run cross-check:
43
43
 
44
44
  On any mismatch, stop and record it as a blocking security finding with both values verbatim. Do **not** publish anything on the MR — a mismatch means the fetched MR may not be the session's bound target, and posting any verdict (a request-changes comment included) puts a review on an MR that may be the wrong one. Re-read the MR with `source_control_get_change_request` once and re-run this cross-check; publish only if the fresh check matches. If it still mismatches, hand off without publishing: record the mismatch in the **Factory routing** block, skip the verdict call, and hand off to a human. When publication does proceed, include only `sessionUrl` as a `Factory Session` section at the end of every published body (approve, request-changes comment, and the approval-fallback comment) so a misattributed review can be traced back to its run. `triggeredBy` and `reviewTarget` stay in the session handoff, never on the MR.
45
45
 
46
- Use `source_control_review_change_request` on the same IID and current `commitId` when available. For an approve verdict use `event: "approve"`. GitLab cannot represent a GitHub-style request-changes review: for a blocking verdict use `event: "comment"` and start the body with `Verdict: request changes`, followed by concrete findings and evidence. Do not claim that a comment blocks merging. Use the approval fallback only for a confirmed authorization rejection — for example, the current account authored the MR or lacks review permission. In that case make a separate `source_control_comment_change_request` call immediately with a body beginning `Verdict: approve (approval not recorded)` and name the provider rejection in the handoff; never claim the MR was formally approved. For any other rejection (stale `commitId`, changed head, invalid request), refresh the checkout and re-establish the current head, then re-run the substantive review — the diff, finding validation, applicable verification, and approval gates — before retrying publication. Never publish an approval evaluated against a head that has since changed. If the gates cannot be re-run on the refreshed head, report that no verdict was posted. Confirm that the comment call succeeded before the handoff or verdict call. If publication fails, report that failure and do not imply a verdict was posted. Where useful, anchor a specific finding with `source_control_create_diff_comment`, but keep a complete verdict in the top-level review.
46
+ Use `source_control_review_change_request` on the same IID and current `commitId` when available. Compose the body fresh in this pass — never reuse a body from an earlier pass. Its first line is the verdict line (`Verdict: approve` or `Verdict: request changes`) and its second line is `Reviewed head: <full SHA>` naming the head you verified, which must equal the current MR head, the `commitId`, and the `reviewedHeadSha` you record. The tool rejects a body whose verdict line contradicts `event` or whose `Reviewed head:` is not the current head; treat that rejection as a stale body — regenerate it from this pass's findings, never flip the event to match it. For an approve verdict use `event: "approve"`. GitLab cannot represent a GitHub-style request-changes review: for a blocking verdict use `event: "comment"` and start the body with `Verdict: request changes`, followed by concrete findings and evidence. Do not claim that a comment blocks merging. Use the approval fallback only for a confirmed authorization rejection — for example, the current account authored the MR or lacks review permission. In that case re-read the MR with `source_control_get_change_request` and confirm its head still equals the head you reviewed — if it moved, do not post the fallback; refresh and re-run the review gates against the new head. Otherwise make a separate `source_control_comment_change_request` call with a body beginning `Verdict: approve (approval not recorded)`, then `Reviewed head: <full SHA>` naming that verified head, and name the provider rejection in the handoff; never claim the MR was formally approved. For any other rejection (stale `commitId`, changed head, invalid request), refresh the checkout and re-establish the current head, then re-run the substantive review — the diff, finding validation, applicable verification, and approval gates — before retrying publication. Never publish an approval evaluated against a head that has since changed. If the gates cannot be re-run on the refreshed head, report that no verdict was posted. Confirm that the comment call succeeded before the handoff or verdict call. If publication fails, report that failure and do not imply a verdict was posted. Where useful, anchor a specific finding with `source_control_create_diff_comment`, but keep a complete verdict in the top-level review.
47
47
 
48
48
  After the review publication attempt, call `factory_record_review_verdict` with the published `verdict` and the verified `reviewedHeadSha`. The card stays in Reviewing; never request a stage transition to end the review. If the call is rejected, address the stated reason before retrying. Then, as the terminal action, give the session handoff and report whether the card was updated. In the session handoff, include MR URL and head SHA, verdict and whether GitLab recorded it, goal, findings with file/line evidence, prior-review disposition, commands/results, assumptions, open questions, any verification limitation, the `Factory Session` block (`sessionUrl` only, matching the MR body), and a **Factory routing** block that records `triggeredBy` verbatim, `reviewTarget` verbatim (`integrationId`, `type`, `externalId`, `url`), `boundRepository` verbatim, and the cross-check outcome — "matched" with the compared MR value or "mismatch: <blocking-finding-ref>".
@@ -152,7 +152,7 @@ On any mismatch, stop and record it as a blocking security finding with both val
152
152
 
153
153
  Compose two artifacts, in order — the **published body** goes on the PR, the **session handoff** goes back into the run's conversation. Don't send either to the conversation yet; both are drafted here, the published body is sent to the PR, the verdict is recorded, and only then is the session handoff posted.
154
154
 
155
- The **published body** (what `gh pr review --body-file` receives) **must open with the verdict line**: `Verdict: approve` or `Verdict: request changes`, followed by:
155
+ The **published body** (what `gh pr review --body-file` receives) **must open with the verdict line**: `Verdict: approve` or `Verdict: request changes`, then on the next line `Reviewed head: <full 40-character SHA>` naming the exact head you verified, followed by:
156
156
 
157
157
  - **Prior pass disposition** — every substantive item from your previous review, classified: addressed, partially addressed, still open, refuted by the push, or invalidated by the push. Cite the commit or `file:line` proving each addressed/refuted/invalidated call. A prior blocking finding still open is called out plainly at the top of this section.
158
158
  - **Findings** — lead with the mechanism of the most consequential finding; new-this-pass findings from the push and from the fresh whole-PR sweep are each labeled as `[push]` or `[fresh]` so the record is honest about where they came from. Distill — this is a handoff, not a transcript.
@@ -172,19 +172,28 @@ The **session handoff** (posted as the final conversation message after the verd
172
172
 
173
173
  **The head must not have moved.** Immediately before publishing, run `gh pr view <number> --json headRefOid --jq .headRefOid` and compare it with the SHA your verification ran on (`git rev-parse HEAD`). A push can land while you verify or wait on bots, and a verdict on a superseded head misleads the author. If the head moved, do not publish: refresh the checkout to the new head, review the new commits and re-run the verification they affect, revise the handoff, then check again. Name the reviewed head SHA in the handoff.
174
174
 
175
- Next, publish the re-review on the PR itself — this is part of every pass, not something to wait to be asked for. Write the published body to `.artifacts/factory-rereview/pr-<number>.md` and submit a PR review matching the verdict:
175
+ Next, publish the re-review on the PR itself — this is part of every pass, not something to wait to be asked for. Write the published body to `.artifacts/factory-rereview/pr-<number>-<headSha>.md`, where `<headSha>` is the full SHA you reviewed. Always write this file fresh in the current pass — never reuse, copy, or edit a body file from an earlier pass, which describes a different head and may carry the opposite verdict.
176
+
177
+ **Gate the file immediately before posting.** Run these checks against the exact file you are about to pass to `--body-file`, and post nothing if any fails — regenerate the body from this pass's findings instead:
178
+
179
+ 1. `head -n1 <file>` is exactly `Verdict: approve` when you will use `--approve`, or exactly `Verdict: request changes` when you will use `--request-changes`.
180
+ 2. The `Reviewed head:` SHA in the file equals `gh pr view <number> --json headRefOid --jq .headRefOid` and the `reviewedHeadSha` you will pass to `factory_record_review_verdict`.
181
+
182
+ Then submit a PR review matching the verdict:
176
183
 
177
184
  - approve → `gh pr review <number> --approve --body-file <file>`
178
185
  - request changes → `gh pr review <number> --request-changes --body-file <file>`
179
186
 
180
187
  **Author-identity misconfiguration must be visible, never silent.** GitHub refuses both approve and request changes from the PR's author, so a review token that authored the PR can never record a verdict in `reviewDecision` or satisfy branch protection. Before submitting, compare the reviewing identity (`gh api user --jq .login`; for an App installation token that call may fail — then treat a submission rejected with GitHub's "Can not approve/request changes on your own pull request" error as the same signal) with the PR's `.author.login`. When they match:
181
188
 
182
- 1. Add this line to the published body immediately after the verdict line (the verdict line stays first): `> ⚠️ **Factory misconfiguration:** the review token is the PR author, so GitHub cannot record this verdict as an approving or changes-requested review (it will not satisfy branch protection or workflows that require an approving or changes-requested review). Configure a separate reviewer token for Factory reviews.`
189
+ 1. Add this line to the published body immediately after the `Reviewed head:` line (the verdict line stays first and `Reviewed head:` stays second): `> ⚠️ **Factory misconfiguration:** the review token is the PR author, so GitHub cannot record this verdict as an approving or changes-requested review (it will not satisfy branch protection or workflows that require an approving or changes-requested review). Configure a separate reviewer token for Factory reviews.`
183
190
  2. Publish with `gh pr comment <number> --body-file <file>`. Do not use `gh pr review --comment`: Factory's repair loop only routes a request-changes verdict from a plain PR comment whose first line is the verdict, and ignores `COMMENTED` reviews.
184
191
  3. Report the misconfiguration and the publish method under **Verification** and in the **Factory routing** block of the handoff.
185
192
 
186
193
  If submission fails for any other reason, fall back to `gh pr comment <number> --body-file <file>` so the verdict still lands on the PR, and report the fallback under **Verification** — how the verdict was published is an operational outcome, not an assumption.
187
194
 
195
+ After the body is posted successfully (review or comment fallback), delete the body file so no later pass can post it.
196
+
188
197
  After publishing, reconcile the verdict label: approve adds `status:auto-approved` and removes `status:changes-requested`; request changes adds `status:changes-requested` and removes `status:auto-approved`.
189
198
 
190
199
  **Non-blocking follow-ups become a PR, not homework.** After publishing the re-review, if it produced non-blocking findings with concrete mechanical fixes — typos, small hardening, a supplemental test case, doc touch-ups — implement them yourself instead of leaving them as a burden on the author. Supplemental means coverage beyond what the behavior-tested gate required: a test gap that failed that gate is a requested change on the reviewed PR, never follow-up work:
@@ -145,7 +145,7 @@ On any mismatch, stop and record it as a blocking security finding with both val
145
145
 
146
146
  Compose two artifacts, in order — the **published body** goes on the PR, the **session handoff** goes back into the run's conversation. Don't send either to the conversation yet; both are drafted here, the published body is sent to the PR, the verdict is recorded, and only then is the session handoff posted.
147
147
 
148
- The **published body** (what `gh pr review --body-file` receives) **must open with the verdict line**: `Verdict: approve` or `Verdict: request changes`, followed by:
148
+ The **published body** (what `gh pr review --body-file` receives) **must open with the verdict line**: `Verdict: approve` or `Verdict: request changes`, then on the next line `Reviewed head: <full 40-character SHA>` naming the exact head you verified, followed by:
149
149
 
150
150
  - **Findings** — lead with the mechanism of the most consequential finding, then correctness, tests, scope, and pattern-consistency, each grounded in the history you traced. Distill — this is a handoff, not a transcript.
151
151
  - **Approach** — the required outcome and the simplest sufficient design from your Phase 1 record, and whether the PR's approach and scope are justified against it. Agreement stated in one line; disagreement with the evidence that supports the alternative.
@@ -164,19 +164,28 @@ The **session handoff** (posted as the final conversation message after the verd
164
164
 
165
165
  **The head must not have moved.** Immediately before publishing, run `gh pr view <number> --json headRefOid --jq .headRefOid` and compare it with the SHA your verification ran on (`git rev-parse HEAD`). A push can land while you verify or wait on bots, and a verdict on a superseded head misleads the author. If the head moved, do not publish: refresh the checkout to the new head, review the new commits and re-run the verification they affect, revise the handoff, then check again. Name the reviewed head SHA in the handoff.
166
166
 
167
- Next, publish the review on the PR itself — this is part of every pass, not something to wait to be asked for. Write the published body to `.artifacts/factory-review/pr-<number>.md` and submit a PR review matching the verdict:
167
+ Next, publish the review on the PR itself — this is part of every pass, not something to wait to be asked for. Write the published body to `.artifacts/factory-review/pr-<number>-<headSha>.md`, where `<headSha>` is the full SHA you reviewed. Always write this file fresh in the current pass — never reuse, copy, or edit a body file from an earlier pass, which describes a different head and may carry the opposite verdict.
168
+
169
+ **Gate the file immediately before posting.** Run these checks against the exact file you are about to pass to `--body-file`, and post nothing if any fails — regenerate the body from this pass's findings instead:
170
+
171
+ 1. `head -n1 <file>` is exactly `Verdict: approve` when you will use `--approve`, or exactly `Verdict: request changes` when you will use `--request-changes`.
172
+ 2. The `Reviewed head:` SHA in the file equals `gh pr view <number> --json headRefOid --jq .headRefOid` and the `reviewedHeadSha` you will pass to `factory_record_review_verdict`.
173
+
174
+ Then submit a PR review matching the verdict:
168
175
 
169
176
  - approve → `gh pr review <number> --approve --body-file <file>`
170
177
  - request changes → `gh pr review <number> --request-changes --body-file <file>`
171
178
 
172
179
  **Author-identity misconfiguration must be visible, never silent.** GitHub refuses both approve and request changes from the PR's author, so a review token that authored the PR can never record a verdict in `reviewDecision` or satisfy branch protection. Before submitting, compare the reviewing identity (`gh api user --jq .login`; for an App installation token that call may fail — then treat a submission rejected with GitHub's "Can not approve/request changes on your own pull request" error as the same signal) with the PR's `.author.login`. When they match:
173
180
 
174
- 1. Add this line to the published body immediately after the verdict line (the verdict line stays first): `> ⚠️ **Factory misconfiguration:** the review token is the PR author, so GitHub cannot record this verdict as an approving or changes-requested review (it will not satisfy branch protection or workflows that require an approving or changes-requested review). Configure a separate reviewer token for Factory reviews.`
181
+ 1. Add this line to the published body immediately after the `Reviewed head:` line (the verdict line stays first and `Reviewed head:` stays second): `> ⚠️ **Factory misconfiguration:** the review token is the PR author, so GitHub cannot record this verdict as an approving or changes-requested review (it will not satisfy branch protection or workflows that require an approving or changes-requested review). Configure a separate reviewer token for Factory reviews.`
175
182
  2. Publish with `gh pr comment <number> --body-file <file>`. Do not use `gh pr review --comment`: Factory's repair loop only routes a request-changes verdict from a plain PR comment whose first line is the verdict, and ignores `COMMENTED` reviews.
176
183
  3. Report the misconfiguration and the publish method under **Verification** and in the **Factory routing** block of the handoff.
177
184
 
178
185
  If submission fails for any other reason, fall back to `gh pr comment <number> --body-file <file>` so the verdict still lands on the PR, and report the fallback under **Verification** — how the verdict was published is an operational outcome, not an assumption.
179
186
 
187
+ After the body is posted successfully (review or comment fallback), delete the body file so no later pass can post it.
188
+
180
189
  After publishing, reconcile the verdict label: approve adds `status:auto-approved` and removes `status:changes-requested`; request changes adds `status:changes-requested` and removes `status:auto-approved`.
181
190
 
182
191
  **Non-blocking follow-ups become a PR, not homework.** After publishing the review, if it produced non-blocking findings with concrete mechanical fixes — typos, small hardening, a supplemental test case, doc touch-ups — implement them yourself instead of leaving them as a burden on the author. Supplemental means coverage beyond what the behavior-tested gate required: a test gap that failed that gate is a requested change on the reviewed PR, never follow-up work:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/factory",
3
- "version": "0.18.0",
3
+ "version": "0.19.0-alpha.1",
4
4
  "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -57,11 +57,11 @@
57
57
  "hono": "^4.13.7",
58
58
  "posthog-node": "^5.46.1",
59
59
  "zod": "^4.6.4",
60
- "@mastra/auth-studio": "1.3.7",
61
- "@mastra/code-sdk": "1.9.0",
62
- "@mastra/slack": "1.7.0",
63
- "@mastra/core": "1.72.0",
64
- "@mastra/auth-workos": "1.6.6"
60
+ "@mastra/auth-studio": "1.3.8-alpha.0",
61
+ "@mastra/auth-workos": "1.6.6",
62
+ "@mastra/code-sdk": "1.10.0-alpha.1",
63
+ "@mastra/slack": "1.7.1-alpha.1",
64
+ "@mastra/core": "1.73.0-alpha.1"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/node": "22.20.1",
@@ -70,11 +70,11 @@
70
70
  "typescript": "^6.0.3",
71
71
  "typescript-eslint": "^8.57.0",
72
72
  "vitest": "4.1.11",
73
- "@mastra/libsql": "1.24.0",
73
+ "@mastra/libsql": "1.24.1-alpha.1",
74
74
  "@internal/types-builder": "0.0.113",
75
- "@mastra/pg": "1.28.0",
76
75
  "@internal/workspace": "0.0.10",
77
- "@internal/lint": "0.0.138"
76
+ "@internal/lint": "0.0.138",
77
+ "@mastra/pg": "1.28.1-alpha.1"
78
78
  },
79
79
  "engines": {
80
80
  "node": ">=22.19.0"