@mastra/factory 0.28.0-alpha.4 → 0.28.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/README.md +52 -28
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +12 -6
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-writes.d.ts.map +1 -1
  6. package/dist/boards/board-writes.js +6 -7
  7. package/dist/boards/board-writes.js.map +1 -1
  8. package/dist/boards/index.d.ts +1 -1
  9. package/dist/boards/index.d.ts.map +1 -1
  10. package/dist/boards/index.js +2 -2
  11. package/dist/boards/project-boards.d.ts +30 -4
  12. package/dist/boards/project-boards.d.ts.map +1 -1
  13. package/dist/boards/project-boards.js +71 -19
  14. package/dist/boards/project-boards.js.map +1 -1
  15. package/dist/boards/registry.d.ts +7 -1
  16. package/dist/boards/registry.d.ts.map +1 -1
  17. package/dist/boards/registry.js +16 -3
  18. package/dist/boards/registry.js.map +1 -1
  19. package/dist/boards/semantics.d.ts +5 -4
  20. package/dist/boards/semantics.d.ts.map +1 -1
  21. package/dist/boards/semantics.js +5 -4
  22. package/dist/boards/semantics.js.map +1 -1
  23. package/dist/boards/work-migrations.d.ts +4 -3
  24. package/dist/boards/work-migrations.d.ts.map +1 -1
  25. package/dist/boards/work-migrations.js +6 -5
  26. package/dist/boards/work-migrations.js.map +1 -1
  27. package/dist/boards/work-seeds.d.ts +9 -0
  28. package/dist/boards/work-seeds.d.ts.map +1 -0
  29. package/dist/boards/work-seeds.js +56 -0
  30. package/dist/boards/work-seeds.js.map +1 -0
  31. package/dist/boards/work.d.ts +2 -2
  32. package/dist/boards/work.d.ts.map +1 -1
  33. package/dist/boards/work.js +0 -16
  34. package/dist/boards/work.js.map +1 -1
  35. package/dist/factory.d.ts +8 -4
  36. package/dist/factory.d.ts.map +1 -1
  37. package/dist/factory.js +33 -73
  38. package/dist/factory.js.map +1 -1
  39. package/dist/feed-events.d.ts +4 -4
  40. package/dist/feed-events.d.ts.map +1 -1
  41. package/dist/feed-events.js +6 -6
  42. package/dist/feed-events.js.map +1 -1
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -1
  46. package/dist/integrations/base.d.ts +0 -11
  47. package/dist/integrations/base.d.ts.map +1 -1
  48. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  49. package/dist/integrations/linear/agent-tools.js +1 -1
  50. package/dist/integrations/linear/agent-tools.js.map +1 -1
  51. package/dist/integrations/slack/integration.d.ts +0 -2
  52. package/dist/integrations/slack/integration.d.ts.map +1 -1
  53. package/dist/integrations/slack/integration.js +0 -5
  54. package/dist/integrations/slack/integration.js.map +1 -1
  55. package/dist/integrations/slack/run-error-card.js +1 -0
  56. package/dist/integrations/slack/run-error-card.js.map +1 -1
  57. package/dist/integrations/slack/slack.d.ts +3 -18
  58. package/dist/integrations/slack/slack.d.ts.map +1 -1
  59. package/dist/integrations/slack/slack.js +3 -74
  60. package/dist/integrations/slack/slack.js.map +1 -1
  61. package/dist/links.d.ts +1 -2
  62. package/dist/links.d.ts.map +1 -1
  63. package/dist/links.js +1 -2
  64. package/dist/links.js.map +1 -1
  65. package/dist/provider-display-name.d.ts.map +1 -1
  66. package/dist/provider-display-name.js +1 -0
  67. package/dist/provider-display-name.js.map +1 -1
  68. package/dist/routes/attention-providers.d.ts +0 -25
  69. package/dist/routes/attention-providers.d.ts.map +1 -1
  70. package/dist/routes/attention-providers.js +2 -150
  71. package/dist/routes/attention-providers.js.map +1 -1
  72. package/dist/routes/attention.d.ts +0 -2
  73. package/dist/routes/attention.d.ts.map +1 -1
  74. package/dist/routes/attention.js +2 -13
  75. package/dist/routes/attention.js.map +1 -1
  76. package/dist/routes/config.d.ts +7 -1
  77. package/dist/routes/config.d.ts.map +1 -1
  78. package/dist/routes/config.js +105 -22
  79. package/dist/routes/config.js.map +1 -1
  80. package/dist/routes/contracts.d.ts +6 -14
  81. package/dist/routes/contracts.d.ts.map +1 -1
  82. package/dist/routes/contracts.js +4 -2
  83. package/dist/routes/contracts.js.map +1 -1
  84. package/dist/routes/feed-events.d.ts +15 -0
  85. package/dist/routes/feed-events.d.ts.map +1 -0
  86. package/dist/routes/feed-events.js +68 -0
  87. package/dist/routes/feed-events.js.map +1 -0
  88. package/dist/routes/knowledge.js +1 -1
  89. package/dist/routes/mastra-gateway.d.ts +19 -0
  90. package/dist/routes/mastra-gateway.d.ts.map +1 -0
  91. package/dist/routes/mastra-gateway.js +120 -0
  92. package/dist/routes/mastra-gateway.js.map +1 -0
  93. package/dist/routes/projects.d.ts +1 -1
  94. package/dist/routes/projects.d.ts.map +1 -1
  95. package/dist/routes/projects.js +1 -1
  96. package/dist/routes/projects.js.map +1 -1
  97. package/dist/routes/provider-credentials.d.ts +6 -1
  98. package/dist/routes/provider-credentials.d.ts.map +1 -1
  99. package/dist/routes/provider-credentials.js +32 -2
  100. package/dist/routes/provider-credentials.js.map +1 -1
  101. package/dist/routes/route.d.ts +6 -0
  102. package/dist/routes/route.d.ts.map +1 -1
  103. package/dist/routes/route.js.map +1 -1
  104. package/dist/routes/surface.d.ts +0 -7
  105. package/dist/routes/surface.d.ts.map +1 -1
  106. package/dist/routes/surface.js +1 -5
  107. package/dist/routes/surface.js.map +1 -1
  108. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  109. package/dist/routes/tenant-credentials.js +5 -1
  110. package/dist/routes/tenant-credentials.js.map +1 -1
  111. package/dist/routes/work-items.d.ts +0 -3
  112. package/dist/routes/work-items.d.ts.map +1 -1
  113. package/dist/routes/work-items.js +0 -1
  114. package/dist/routes/work-items.js.map +1 -1
  115. package/dist/rules/dispatcher.d.ts +0 -3
  116. package/dist/rules/dispatcher.d.ts.map +1 -1
  117. package/dist/rules/dispatcher.js +5 -7
  118. package/dist/rules/dispatcher.js.map +1 -1
  119. package/dist/run-error.d.ts +1 -1
  120. package/dist/run-error.d.ts.map +1 -1
  121. package/dist/run-error.js +38 -5
  122. package/dist/run-error.js.map +1 -1
  123. package/dist/session/live-sessions.d.ts +11 -4
  124. package/dist/session/live-sessions.d.ts.map +1 -1
  125. package/dist/session/live-sessions.js +31 -10
  126. package/dist/session/live-sessions.js.map +1 -1
  127. package/dist/storage/domains/audit/actions.d.ts +1 -1
  128. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  129. package/dist/storage/domains/audit/actions.js +0 -4
  130. package/dist/storage/domains/audit/actions.js.map +1 -1
  131. package/dist/storage/domains/boards/base.d.ts +15 -1
  132. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  133. package/dist/storage/domains/boards/base.js +21 -5
  134. package/dist/storage/domains/boards/base.js.map +1 -1
  135. package/dist/storage/domains/channel-identity/base.d.ts +0 -4
  136. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  137. package/dist/storage/domains/channel-identity/base.js +0 -7
  138. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  139. package/dist/storage/domains/work-items/base.d.ts +12 -17
  140. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  141. package/dist/storage/domains/work-items/base.js +42 -117
  142. package/dist/storage/domains/work-items/base.js.map +1 -1
  143. package/dist/storage/domains/work-items/board-version.d.ts +6 -2
  144. package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
  145. package/dist/storage/domains/work-items/board-version.js +20 -9
  146. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  147. package/dist/storage/domains/work-items/cards.d.ts +3 -3
  148. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  149. package/dist/storage/domains/work-items/cards.js +10 -10
  150. package/dist/storage/domains/work-items/cards.js.map +1 -1
  151. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -2
  152. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  153. package/dist/storage/domains/work-items/work-item-schema.js +8 -8
  154. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  155. package/dist/tools/read-tools.d.ts +0 -2
  156. package/dist/tools/read-tools.d.ts.map +1 -1
  157. package/dist/tools/read-tools.js +3 -14
  158. package/dist/tools/read-tools.js.map +1 -1
  159. package/dist/tools/work-item-tools.d.ts +0 -3
  160. package/dist/tools/work-item-tools.d.ts.map +1 -1
  161. package/dist/tools/work-item-tools.js +8 -18
  162. package/dist/tools/work-item-tools.js.map +1 -1
  163. package/dist/work-items/create-work-item.d.ts.map +1 -1
  164. package/dist/work-items/create-work-item.js +3 -2
  165. package/dist/work-items/create-work-item.js.map +1 -1
  166. package/dist/work-items/description-context.d.ts +5 -0
  167. package/dist/work-items/description-context.d.ts.map +1 -0
  168. package/dist/work-items/description-context.js +17 -0
  169. package/dist/work-items/description-context.js.map +1 -0
  170. package/dist/work-items/split-migration.d.ts.map +1 -1
  171. package/dist/work-items/split-migration.js +1 -6
  172. package/dist/work-items/split-migration.js.map +1 -1
  173. package/factory-skills/configure-factory-rules/SKILL.md +3 -3
  174. package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
  175. package/factory-skills/factory-gitlab-review/SKILL.md +5 -5
  176. package/factory-skills/factory-rereview/SKILL.md +70 -24
  177. package/factory-skills/factory-review/SKILL.md +70 -24
  178. package/factory-skills/factory-self-review/SKILL.md +5 -6
  179. package/factory-skills/factory-triage/SKILL.md +11 -22
  180. package/package.json +8 -8
  181. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
  182. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
  183. package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
  184. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
  185. package/dist/integrations/slack/emoji.d.ts +0 -3
  186. package/dist/integrations/slack/emoji.d.ts.map +0 -1
  187. package/dist/integrations/slack/emoji.js +0 -11
  188. package/dist/integrations/slack/emoji.js.map +0 -1
  189. package/dist/integrations/slack/feed-publisher.d.ts +0 -26
  190. package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
  191. package/dist/integrations/slack/feed-publisher.js +0 -43
  192. package/dist/integrations/slack/feed-publisher.js.map +0 -1
  193. package/dist/routes/attention-activity.d.ts +0 -23
  194. package/dist/routes/attention-activity.d.ts.map +0 -1
  195. package/dist/routes/attention-activity.js +0 -154
  196. package/dist/routes/attention-activity.js.map +0 -1
  197. package/dist/storage/domains/comments/activity.d.ts +0 -40
  198. package/dist/storage/domains/comments/activity.d.ts.map +0 -1
  199. package/dist/storage/domains/comments/activity.js +0 -93
  200. package/dist/storage/domains/comments/activity.js.map +0 -1
  201. package/dist/storage/domains/comments/actor.d.ts +0 -51
  202. package/dist/storage/domains/comments/actor.d.ts.map +0 -1
  203. package/dist/storage/domains/comments/actor.js +0 -37
  204. package/dist/storage/domains/comments/actor.js.map +0 -1
  205. package/dist/storage/domains/comments/base.d.ts +0 -245
  206. package/dist/storage/domains/comments/base.d.ts.map +0 -1
  207. package/dist/storage/domains/comments/base.js +0 -539
  208. package/dist/storage/domains/comments/base.js.map +0 -1
  209. package/dist/storage/domains/comments/domain.d.ts +0 -135
  210. package/dist/storage/domains/comments/domain.d.ts.map +0 -1
  211. package/dist/storage/domains/comments/domain.js +0 -284
  212. package/dist/storage/domains/comments/domain.js.map +0 -1
  213. package/dist/storage/domains/comments/feed-context.d.ts +0 -22
  214. package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
  215. package/dist/storage/domains/comments/feed-context.js +0 -88
  216. package/dist/storage/domains/comments/feed-context.js.map +0 -1
  217. package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
  218. package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
  219. package/dist/storage/domains/comments/feed-sync.js +0 -1
  220. package/dist/storage/domains/comments/parse.d.ts +0 -23
  221. package/dist/storage/domains/comments/parse.d.ts.map +0 -1
  222. package/dist/storage/domains/comments/parse.js +0 -89
  223. package/dist/storage/domains/comments/parse.js.map +0 -1
  224. package/dist/storage/domains/comments/routes.d.ts +0 -24
  225. package/dist/storage/domains/comments/routes.d.ts.map +0 -1
  226. package/dist/storage/domains/comments/routes.js +0 -299
  227. package/dist/storage/domains/comments/routes.js.map +0 -1
  228. package/dist/storage/domains/comments/schema.d.ts +0 -5
  229. package/dist/storage/domains/comments/schema.d.ts.map +0 -1
  230. package/dist/storage/domains/comments/schema.js +0 -178
  231. package/dist/storage/domains/comments/schema.js.map +0 -1
  232. package/dist/storage/domains/comments/wire.d.ts +0 -40
  233. package/dist/storage/domains/comments/wire.d.ts.map +0 -1
  234. package/dist/storage/domains/comments/wire.js +0 -36
  235. package/dist/storage/domains/comments/wire.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"split-migration.d.ts","sourceRoot":"","sources":["../../src/work-items/split-migration.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAmB,cAAc,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAG/F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AAY3E,OAAO,KAAK,EACV,iBAAiB,EACjB,gBAAgB,EAChB,sBAAsB,EACvB,MAAM,mDAAmD,CAAC;AAmC3D,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,IAAI,CAAC;IAChB,qBAAqB,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC;AAED,MAAM,WAAW,iBAAiB;IAChC,6FAA6F;IAC7F,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,MAAM,EAAE,sBAAsB,GAAG,IAAI,CAAC;IACtC,SAAS,EAAE,iBAAiB,CAAC;CAC9B;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,iBAAiB,EAAE,CAAC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,2BAA2B;IAC1C,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,GAAG,CAAC,EAAE,iBAAiB,CAAC;IACxB,0DAA0D;IAC1D,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,qDAAqD;IACrD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+EAA+E;IAC/E,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,aAAa,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7D,uFAAuF;IACvF,KAAK,CAAC,EAAE,eAAe,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,mFAAmF;AACnF,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,KAAK,GAAG,iBAAiB,CAAC,EACxD,EACE,MAAc,EACd,GAAiB,EACjB,GAAG,EACH,OAAO,EACP,KAAK,EACL,QAAoB,EACpB,MAAM,EACN,KAAK,EACL,kBAA6C,EAC7C,GAAc,GACf,GAAE,2BAAgC,GAClC,OAAO,CAAC,mBAAmB,CAAC,CAqH9B"}
@@ -70,6 +70,7 @@ function splitLegacyWorkItem(row, { workItemId, revision }) {
70
70
  org_id: row.org_id,
71
71
  factory_project_id: String(row.factory_project_id),
72
72
  title: row.title,
73
+ description: row.description ?? null,
73
74
  parent_work_item_id: null,
74
75
  revision: 1,
75
76
  created_at: row.created_at,
@@ -113,8 +114,6 @@ function splitLegacyWorkItem(row, { workItemId, revision }) {
113
114
  accepted_at: row.accepted_at ?? null,
114
115
  autonomy_armed_at: row.autonomy_armed_at ?? null,
115
116
  plans_preapproved_at: row.plans_preapproved_at ?? null,
116
- comment_count: row.comment_count ?? 0,
117
- feed_activity_at: null,
118
117
  revision: revision ?? row.revision,
119
118
  created_by: row.created_by,
120
119
  created_at: row.created_at,
@@ -202,10 +201,6 @@ async function writeCard(ops, card, recopy) {
202
201
  baseline = time(current.migrated_from_updated_at);
203
202
  return {
204
203
  ...card.boardItem,
205
- ...current.feed_activity_at ? {
206
- comment_count: current.comment_count,
207
- feed_activity_at: current.feed_activity_at
208
- } : {},
209
204
  revision: Math.max(current.revision, card.boardItem.revision) + 1
210
205
  };
211
206
  });
@@ -1 +1 @@
1
- {"version":3,"file":"split-migration.js","names":[],"sources":["../../src/work-items/split-migration.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionValue, FactoryStorage, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { factoryDecisionHash } from '../storage/domains/work-items/base.js';\nimport type { WorkItemDbRow } from '../storage/domains/work-items/base.js';\nimport { bumpBoardVersions } from '../storage/domains/work-items/board-version.js';\nimport type { BoardScope } from '../storage/domains/work-items/board-version.js';\nimport {\n WORK_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport type {\n BoardItemDbRecord,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport { splitCardMetadata, workItemProviderAdapter } from './providers/index.js';\n\nconst LEGACY = WORK_ITEMS_SCHEMA.name;\nconst WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;\nconst SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;\nconst BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;\nconst PAGE_SIZE = 200;\nconst LOGGED_SKIPS = 10;\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nconst fmt = (value: number) => value.toLocaleString('en-US');\n\n/** One line: skips repeat while an older replica keeps writing, so only a sample is named. */\nfunction summaryLine(title: string, report: WorkItemSplitReport): string {\n const counts = [\n `${fmt(report.cards)} cards checked`,\n `${fmt(report.workItems)} copied`,\n `${fmt(report.recopied)} recopied`,\n `${fmt(report.unchanged)} unchanged`,\n `${fmt(report.deferred)} deferred`,\n `${fmt(report.skipped.length)} skipped`,\n ];\n if (report.aborted) counts.push('stopped early');\n let line = `${title}: ${counts.join(', ')}`;\n if (report.skipped.length) {\n const sample = report.skipped\n .slice(0, LOGGED_SKIPS)\n .map(skip => `${skip.id} (${skip.reason.replace(/\\s+/g, ' ')})`);\n const more = report.skipped.length - sample.length;\n line += ` — ${sample.join('; ')}${more ? `; and ${fmt(more)} more` : ''}`;\n }\n return line;\n}\n\nexport interface MigratedBoardItem {\n workItemId: string;\n revision: number;\n updatedAt: Date;\n migratedFromUpdatedAt: Date | null;\n migratedFromHash: string | null;\n}\n\nexport interface WorkItemSplitCard {\n /** Fingerprint observed when planning; rejects a stale migration plan under the row lock. */\n previousHash?: string | null;\n workItem: WorkItemDbRecord;\n source: WorkItemSourceDbRecord | null;\n boardItem: BoardItemDbRecord;\n}\n\nexport interface WorkItemSplitSkip {\n id: string;\n reason: string;\n}\n\nexport interface WorkItemSplitPlan {\n inserts: WorkItemSplitCard[];\n recopies: WorkItemSplitCard[];\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n}\n\nexport interface WorkItemSplitReport {\n dryRun: boolean;\n projects: number;\n cards: number;\n /** Rows the `include` filter left for a later pass. */\n deferred: number;\n workItems: number;\n sources: number;\n boardItems: number;\n recopied: number;\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n aborted: boolean;\n}\n\nfunction time(value: Date | string | null | undefined): number {\n return value ? new Date(value).getTime() : Number.NEGATIVE_INFINITY;\n}\n\nfunction legacyHash(row: WorkItemDbRow): string {\n const copied = {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: row.factory_project_id,\n board: row.board,\n external_source: row.external_source,\n parent_work_item_id: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triage_type: row.triage_type,\n accepted_at: row.accepted_at,\n autonomy_armed_at: row.autonomy_armed_at,\n plans_preapproved_at: row.plans_preapproved_at,\n revision: row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n // stableJson does not invoke Date.toJSON; normalize before hashing.\n return factoryDecisionHash(JSON.parse(JSON.stringify(copied)));\n}\n\nexport function splitLegacyWorkItem(\n row: WorkItemDbRow,\n { workItemId, revision }: { workItemId: string; revision?: number },\n): WorkItemSplitCard {\n const adapter = workItemProviderAdapter(row.external_source ?? null);\n const provider = adapter.toSource(row.external_source ?? null, row.metadata);\n const metadata = splitCardMetadata(row.metadata, adapter.providerMetadataKeys);\n return {\n workItem: {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n title: row.title,\n parent_work_item_id: null,\n revision: 1,\n created_at: row.created_at,\n updated_at: row.updated_at,\n },\n source: provider\n ? {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n provider: provider.provider,\n integration_id: provider.integrationId,\n source_type: provider.sourceType,\n workspace_id: provider.workspaceId,\n external_id: provider.externalId,\n source_key: provider.sourceKey,\n url: provider.url,\n key: provider.key,\n state: provider.state,\n labels: provider.labels,\n author: provider.author,\n metadata: metadata.provider,\n role: 'origin',\n revision: 1,\n synced_at: null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n }\n : null,\n boardItem: {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n board: row.board ?? null,\n parent_board_item_id: row.parent_work_item_id ?? null,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: metadata.board,\n triage_type: row.triage_type ?? null,\n accepted_at: row.accepted_at ?? null,\n autonomy_armed_at: row.autonomy_armed_at ?? null,\n plans_preapproved_at: row.plans_preapproved_at ?? null,\n comment_count: row.comment_count ?? 0,\n // The first recount must be able to correct a copied legacy count.\n feed_activity_at: null,\n revision: revision ?? row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n migrated_from_updated_at: row.updated_at,\n migrated_from_hash: legacyHash(row),\n },\n };\n}\n\nexport function planWorkItemSplit(\n rows: readonly WorkItemDbRow[],\n migrated: ReadonlyMap<string, MigratedBoardItem> = new Map(),\n newId: () => string = randomUUID,\n): WorkItemSplitPlan {\n const plan: WorkItemSplitPlan = { inserts: [], recopies: [], unchanged: 0, skipped: [] };\n for (const row of rows) {\n const existing = migrated.get(row.id);\n if (existing?.migratedFromHash === legacyHash(row)) {\n plan.unchanged += 1;\n continue;\n }\n if (existing && time(existing.updatedAt) > time(existing.migratedFromUpdatedAt)) {\n plan.skipped.push({ id: row.id, reason: 'Split board item changed after migration' });\n continue;\n }\n try {\n const card = splitLegacyWorkItem(row, {\n workItemId: existing?.workItemId ?? newId(),\n ...(existing ? { revision: Math.max(existing.revision, row.revision) + 1 } : {}),\n });\n if (existing) card.previousHash = existing.migratedFromHash;\n (existing ? plan.recopies : plan.inserts).push(card);\n } catch (error) {\n plan.skipped.push({ id: row.id, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return plan;\n}\n\nasync function migratedBoardItems(\n ops: FactoryStorageOps,\n ids: readonly string[],\n): Promise<Map<string, MigratedBoardItem>> {\n if (!ids.length) return new Map();\n const rows = await ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, { id: { in: [...ids] } });\n return new Map(\n rows.map(row => [\n row.id,\n {\n workItemId: row.work_item_id,\n revision: row.revision,\n updatedAt: row.updated_at,\n migratedFromUpdatedAt: row.migrated_from_updated_at,\n migratedFromHash: row.migrated_from_hash,\n },\n ]),\n );\n}\n\nclass MigrationConflict extends Error {}\n\nasync function writeCard(ops: FactoryStorageOps, card: WorkItemSplitCard, recopy: boolean): Promise<boolean> {\n if (!recopy) {\n // Both paths take this card-specific lock before any card rows. A project-wide\n // lock here would invert the row-lock order of parent/child and bulk deletions.\n const guard = await ops.updateAtomic(\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name,\n { id: card.boardItem.id },\n () => null,\n );\n if (!guard)\n await ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, {\n id: card.boardItem.id,\n org_id: card.boardItem.org_id,\n factory_project_id: card.boardItem.factory_project_id,\n });\n if (await ops.findOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, { id: card.boardItem.id })) return false;\n const existing = await ops.findOne<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id });\n if (existing) {\n if (existing.migrated_from_hash === card.boardItem.migrated_from_hash) return false;\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n await ops.insertOne<WorkItemDbRecord>(WORK_ITEMS, card.workItem);\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n await ops.insertOne<BoardItemDbRecord>(BOARD_ITEMS, card.boardItem);\n return true;\n }\n // updateAtomic locks the board row until this transaction commits, so a new\n // transition cannot land between the overwrite guard and the copy.\n let unchanged = false;\n let baseline = Number.NEGATIVE_INFINITY;\n const board = await ops.updateAtomic<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id }, current => {\n if (current.migrated_from_hash === card.boardItem.migrated_from_hash) {\n unchanged = true;\n return null;\n }\n if (current.migrated_from_hash !== card.previousHash) {\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n if (time(current.updated_at) > time(current.migrated_from_updated_at)) {\n throw new MigrationConflict('Split board item changed after migration');\n }\n baseline = time(current.migrated_from_updated_at);\n return {\n ...card.boardItem,\n ...(current.feed_activity_at\n ? { comment_count: current.comment_count, feed_activity_at: current.feed_activity_at }\n : {}),\n revision: Math.max(current.revision, card.boardItem.revision) + 1,\n };\n });\n if (unchanged) return false;\n if (!board) throw new MigrationConflict('Split board item disappeared during migration');\n await ops.updateAtomic<WorkItemDbRecord>(WORK_ITEMS, { id: card.workItem.id }, current => {\n if (time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split work item changed after migration');\n }\n return { ...card.workItem, revision: current.revision + 1 };\n });\n const sources = await ops.findMany<WorkItemSourceDbRecord>(SOURCES, { work_item_id: card.workItem.id });\n if (sources.some(source => source.id !== card.workItem.id)) {\n throw new MigrationConflict('Split source set changed after migration');\n }\n for (const source of sources) {\n await ops.updateAtomic<WorkItemSourceDbRecord>(SOURCES, { id: source.id }, current => {\n if (current.synced_at != null || time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split source changed after migration');\n }\n return null;\n });\n }\n if (sources.length) await ops.deleteMany(SOURCES, { id: { in: sources.map(source => source.id) } });\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n return true;\n}\n\nexport interface LegacyWatermark {\n updatedAt: Date;\n id: string;\n}\n\nexport interface WorkItemSplitMarker {\n /** Newest legacy row when the finished pass began; null when the legacy table was empty. */\n watermark: LegacyWatermark | null;\n completedAt: Date;\n}\n\nconst SPLIT_STATE = FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA.name;\nconst SPLIT_MARKER_ID = 'work_item_split';\n\n/** The newest legacy write, by `(updated_at, id)`; one indexed row. */\nexport async function readLegacyWatermark(ops: FactoryStorageOps): Promise<LegacyWatermark | null> {\n const [row] = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: 1,\n },\n );\n return row ? { updatedAt: row.updated_at, id: row.id } : null;\n}\n\nexport async function readWorkItemSplitMarker(ops: FactoryStorageOps): Promise<WorkItemSplitMarker | null> {\n const row = await ops.findOne<{ legacy_updated_at: Date | null; legacy_id: string | null; completed_at: Date }>(\n SPLIT_STATE,\n { id: SPLIT_MARKER_ID },\n );\n if (!row) return null;\n return {\n watermark: row.legacy_updated_at && row.legacy_id ? { updatedAt: row.legacy_updated_at, id: row.legacy_id } : null,\n completedAt: row.completed_at,\n };\n}\n\n/** Marks every legacy row up to `watermark` as copied. */\nexport async function recordWorkItemSplitComplete(\n ops: FactoryStorageOps,\n watermark: LegacyWatermark | null,\n): Promise<void> {\n await ops.upsertOne(SPLIT_STATE, ['id'], {\n id: SPLIT_MARKER_ID,\n legacy_updated_at: watermark?.updatedAt ?? null,\n legacy_id: watermark?.id ?? null,\n completed_at: new Date(),\n });\n}\n\n/**\n * Copies legacy cards that have no split rows yet, inside the caller's\n * transaction. Tombstoned cards and cards whose source another card already\n * holds are left alone; the source is checked first because a unique violation\n * would abort the caller's Postgres transaction. Returns the copied ids.\n */\nexport async function copyLegacyRows(ops: FactoryStorageOps, rows: readonly WorkItemDbRow[]): Promise<string[]> {\n const copied: string[] = [];\n for (const row of rows) {\n let card: WorkItemSplitCard;\n try {\n card = splitLegacyWorkItem(row, { workItemId: randomUUID() });\n } catch {\n continue;\n }\n if (\n card.source &&\n (await ops.findOne(SOURCES, {\n org_id: card.source.org_id,\n factory_project_id: card.source.factory_project_id,\n provider: card.source.provider,\n external_id: card.source.external_id,\n }))\n ) {\n continue;\n }\n try {\n if (await writeCard(ops, card, false)) copied.push(row.id);\n } catch (error) {\n if (!(error instanceof MigrationConflict)) throw error;\n }\n }\n return copied;\n}\n\nexport interface MigrateWorkItemSplitOptions {\n dryRun?: boolean;\n ops?: FactoryStorageOps;\n /** Receives single-line progress and summary messages. */\n log?: (line: string) => void;\n /** Names the pass in log lines, e.g. `boot pass`. */\n label?: string;\n /** Minimum time between progress lines; a pass shorter than this logs none. */\n progressIntervalMs?: number;\n now?: () => number;\n /** Rows this returns false for are counted as deferred and not looked up. */\n include?: (row: WorkItemDbRow) => boolean | Promise<boolean>;\n /** Scan only legacy rows written after this watermark, in `(updated_at, id)` order. */\n since?: LegacyWatermark | null;\n pageSize?: number;\n /** Checked between cards and pages; an aborted pass reports `aborted`. */\n signal?: AbortSignal;\n}\n\n/** Legacy rows are read-only; each card and all its split rows land atomically. */\nexport async function migrateWorkItemSplit(\n storage: Pick<FactoryStorage, 'ops' | 'withTransaction'>,\n {\n dryRun = false,\n ops = storage.ops,\n log,\n include,\n since,\n pageSize = PAGE_SIZE,\n signal,\n label,\n progressIntervalMs = PROGRESS_LOG_INTERVAL_MS,\n now = Date.now,\n }: MigrateWorkItemSplitOptions = {},\n): Promise<WorkItemSplitReport> {\n const report: WorkItemSplitReport = {\n dryRun,\n projects: 0,\n cards: 0,\n deferred: 0,\n workItems: 0,\n sources: 0,\n boardItems: 0,\n recopied: 0,\n unchanged: 0,\n skipped: [],\n aborted: false,\n };\n const projects = new Set<string>();\n const orderBy: Array<[string, 'asc']> = since\n ? [\n ['updated_at', 'asc'],\n ['id', 'asc'],\n ]\n : [\n ['org_id', 'asc'],\n ['factory_project_id', 'asc'],\n ['created_at', 'asc'],\n ['id', 'asc'],\n ];\n let cursor: CollectionValue[] | undefined = since ? [since.updatedAt, since.id] : undefined;\n const title = `work item split${dryRun ? ' (dry run)' : ''}${label ? ` (${label})` : ''}`;\n let lastProgressAt = now();\n // Counted only once a progress line is due, so a fast pass pays nothing; unknown for a `since` scan.\n let total: number | null | undefined = since ? null : undefined;\n const progress = async () => {\n if (!log || now() - lastProgressAt < progressIntervalMs) return;\n if (total === undefined) total = (await ops.count?.(LEGACY, {})) ?? null;\n lastProgressAt = now();\n const checked = total === null ? fmt(report.cards) : `${fmt(report.cards)}/${fmt(total)}`;\n log(`${title}: ${checked} cards checked, ${fmt(report.workItems)} copied, ${fmt(report.skipped.length)} skipped`);\n };\n while (!signal?.aborted) {\n const page = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n { orderBy, limit: pageSize, ...(cursor ? { cursor: { values: cursor } } : {}) },\n );\n if (!page.length) break;\n const last = page[page.length - 1]!;\n cursor = since ? [last.updated_at, last.id] : [last.org_id, last.factory_project_id, last.created_at, last.id];\n report.cards += page.length;\n const rows: WorkItemDbRow[] = [];\n for (const row of page) {\n projects.add(`${row.org_id}\\u0000${row.factory_project_id}`);\n if (!include || (await include(row))) rows.push(row);\n else report.deferred += 1;\n }\n const written = new Map<string, BoardScope>();\n if (rows.length) {\n const tombstones = await ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, {\n id: { in: rows.map(row => row.id) },\n });\n const deleted = new Set(tombstones.map(row => row.id));\n report.unchanged += deleted.size;\n const plan = planWorkItemSplit(\n rows.filter(row => !deleted.has(row.id)),\n await migratedBoardItems(\n ops,\n rows.map(row => row.id),\n ),\n );\n report.unchanged += plan.unchanged;\n report.skipped.push(...plan.skipped);\n for (const { card, recopy } of [\n ...plan.inserts.map(card => ({ card, recopy: false })),\n ...plan.recopies.map(card => ({ card, recopy: true })),\n ]) {\n if (signal?.aborted) break;\n if (!dryRun) {\n try {\n const changed = await storage.withTransaction(tx => writeCard(tx, card, recopy));\n if (!changed) {\n report.unchanged += 1;\n continue;\n }\n } catch (error) {\n if (!(error instanceof UniqueViolationError) && !(error instanceof MigrationConflict)) throw error;\n const raced = (await migratedBoardItems(ops, [card.boardItem.id])).get(card.boardItem.id);\n if (raced?.migratedFromHash === card.boardItem.migrated_from_hash) report.unchanged += 1;\n else {\n const reason =\n error instanceof UniqueViolationError &&\n (error.collection === SOURCES || error.collection === BOARD_ITEMS)\n ? `Conflicting source: ${error.message}`\n : error.message;\n report.skipped.push({ id: card.boardItem.id, reason });\n }\n continue;\n }\n }\n await progress();\n report.workItems += 1;\n report.sources += card.source ? 1 : 0;\n report.boardItems += 1;\n if (recopy) report.recopied += 1;\n written.set(`${card.boardItem.org_id}\\u0000${card.boardItem.factory_project_id}`, {\n orgId: card.boardItem.org_id,\n factoryProjectId: card.boardItem.factory_project_id,\n });\n }\n }\n // Per page, so cached boards pick up a long pass's cards as they land.\n if (!dryRun && written.size) await bumpBoardVersions(ops, [...written.values()]);\n if (page.length < pageSize) break;\n await progress();\n }\n report.aborted = signal?.aborted ?? false;\n report.projects = projects.size;\n if (log && (report.workItems || report.skipped.length || dryRun)) log(summaryLine(title, report));\n return report;\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,SAAS,kBAAkB;AACjC,MAAM,aAAa,0BAA0B;AAC7C,MAAM,UAAU,iCAAiC;AACjD,MAAM,cAAc,2BAA2B;AAC/C,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,2BAA2B;AAEjC,MAAM,OAAO,UAAkB,MAAM,eAAe,OAAO;;AAG3D,SAAS,YAAY,OAAe,QAAqC;CACvE,MAAM,SAAS;EACb,GAAG,IAAI,OAAO,KAAK,EAAE;EACrB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,QAAQ,MAAM,EAAE;CAChC;CACA,IAAI,OAAO,SAAS,OAAO,KAAK,eAAe;CAC/C,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,KAAK,IAAI;CACxC,IAAI,OAAO,QAAQ,QAAQ;EACzB,MAAM,SAAS,OAAO,QACnB,MAAM,GAAG,YAAY,CAAC,CACtB,KAAI,SAAQ,GAAG,KAAK,GAAG,IAAI,KAAK,OAAO,QAAQ,QAAQ,GAAG,EAAE,EAAE;EACjE,MAAM,OAAO,OAAO,QAAQ,SAAS,OAAO;EAC5C,QAAQ,MAAM,OAAO,KAAK,IAAI,IAAI,OAAO,SAAS,IAAI,IAAI,EAAE,SAAS;CACvE;CACA,OAAO;AACT;AA6CA,SAAS,KAAK,OAAiD;CAC7D,OAAO,QAAQ,IAAI,KAAK,KAAK,CAAC,CAAC,QAAQ,IAAI,OAAO;AACpD;AAEA,SAAS,WAAW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S;CACjB;CACA,OAAO,UAAU,QAAQ,WAAW;CACpC,OAAO,WAAW,SAAS;CAC3B,IAAI,QAAQ,OAAO,aAAa,OAAO,QAAQ,UAAU,SAAS,IAAI,YAAY,OAAO,MAAM,CAAC;CAChG,OAAO;AACT"}
1
+ {"version":3,"file":"split-migration.js","names":[],"sources":["../../src/work-items/split-migration.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionValue, FactoryStorage, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { factoryDecisionHash } from '../storage/domains/work-items/base.js';\nimport type { WorkItemDbRow } from '../storage/domains/work-items/base.js';\nimport { bumpBoardVersions } from '../storage/domains/work-items/board-version.js';\nimport type { BoardScope } from '../storage/domains/work-items/board-version.js';\nimport {\n WORK_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport type {\n BoardItemDbRecord,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport { splitCardMetadata, workItemProviderAdapter } from './providers/index.js';\n\nconst LEGACY = WORK_ITEMS_SCHEMA.name;\nconst WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;\nconst SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;\nconst BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;\nconst PAGE_SIZE = 200;\nconst LOGGED_SKIPS = 10;\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nconst fmt = (value: number) => value.toLocaleString('en-US');\n\n/** One line: skips repeat while an older replica keeps writing, so only a sample is named. */\nfunction summaryLine(title: string, report: WorkItemSplitReport): string {\n const counts = [\n `${fmt(report.cards)} cards checked`,\n `${fmt(report.workItems)} copied`,\n `${fmt(report.recopied)} recopied`,\n `${fmt(report.unchanged)} unchanged`,\n `${fmt(report.deferred)} deferred`,\n `${fmt(report.skipped.length)} skipped`,\n ];\n if (report.aborted) counts.push('stopped early');\n let line = `${title}: ${counts.join(', ')}`;\n if (report.skipped.length) {\n const sample = report.skipped\n .slice(0, LOGGED_SKIPS)\n .map(skip => `${skip.id} (${skip.reason.replace(/\\s+/g, ' ')})`);\n const more = report.skipped.length - sample.length;\n line += ` — ${sample.join('; ')}${more ? `; and ${fmt(more)} more` : ''}`;\n }\n return line;\n}\n\nexport interface MigratedBoardItem {\n workItemId: string;\n revision: number;\n updatedAt: Date;\n migratedFromUpdatedAt: Date | null;\n migratedFromHash: string | null;\n}\n\nexport interface WorkItemSplitCard {\n /** Fingerprint observed when planning; rejects a stale migration plan under the row lock. */\n previousHash?: string | null;\n workItem: WorkItemDbRecord;\n source: WorkItemSourceDbRecord | null;\n boardItem: BoardItemDbRecord;\n}\n\nexport interface WorkItemSplitSkip {\n id: string;\n reason: string;\n}\n\nexport interface WorkItemSplitPlan {\n inserts: WorkItemSplitCard[];\n recopies: WorkItemSplitCard[];\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n}\n\nexport interface WorkItemSplitReport {\n dryRun: boolean;\n projects: number;\n cards: number;\n /** Rows the `include` filter left for a later pass. */\n deferred: number;\n workItems: number;\n sources: number;\n boardItems: number;\n recopied: number;\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n aborted: boolean;\n}\n\nfunction time(value: Date | string | null | undefined): number {\n return value ? new Date(value).getTime() : Number.NEGATIVE_INFINITY;\n}\n\nfunction legacyHash(row: WorkItemDbRow): string {\n const copied = {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: row.factory_project_id,\n board: row.board,\n external_source: row.external_source,\n parent_work_item_id: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triage_type: row.triage_type,\n accepted_at: row.accepted_at,\n autonomy_armed_at: row.autonomy_armed_at,\n plans_preapproved_at: row.plans_preapproved_at,\n revision: row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n // stableJson does not invoke Date.toJSON; normalize before hashing.\n return factoryDecisionHash(JSON.parse(JSON.stringify(copied)));\n}\n\nexport function splitLegacyWorkItem(\n row: WorkItemDbRow,\n { workItemId, revision }: { workItemId: string; revision?: number },\n): WorkItemSplitCard {\n const adapter = workItemProviderAdapter(row.external_source ?? null);\n const provider = adapter.toSource(row.external_source ?? null, row.metadata);\n const metadata = splitCardMetadata(row.metadata, adapter.providerMetadataKeys);\n return {\n workItem: {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n title: row.title,\n description: row.description ?? null,\n parent_work_item_id: null,\n revision: 1,\n created_at: row.created_at,\n updated_at: row.updated_at,\n },\n source: provider\n ? {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n provider: provider.provider,\n integration_id: provider.integrationId,\n source_type: provider.sourceType,\n workspace_id: provider.workspaceId,\n external_id: provider.externalId,\n source_key: provider.sourceKey,\n url: provider.url,\n key: provider.key,\n state: provider.state,\n labels: provider.labels,\n author: provider.author,\n metadata: metadata.provider,\n role: 'origin',\n revision: 1,\n synced_at: null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n }\n : null,\n boardItem: {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n board: row.board ?? null,\n parent_board_item_id: row.parent_work_item_id ?? null,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: metadata.board,\n triage_type: row.triage_type ?? null,\n accepted_at: row.accepted_at ?? null,\n autonomy_armed_at: row.autonomy_armed_at ?? null,\n plans_preapproved_at: row.plans_preapproved_at ?? null,\n revision: revision ?? row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n migrated_from_updated_at: row.updated_at,\n migrated_from_hash: legacyHash(row),\n },\n };\n}\n\nexport function planWorkItemSplit(\n rows: readonly WorkItemDbRow[],\n migrated: ReadonlyMap<string, MigratedBoardItem> = new Map(),\n newId: () => string = randomUUID,\n): WorkItemSplitPlan {\n const plan: WorkItemSplitPlan = { inserts: [], recopies: [], unchanged: 0, skipped: [] };\n for (const row of rows) {\n const existing = migrated.get(row.id);\n if (existing?.migratedFromHash === legacyHash(row)) {\n plan.unchanged += 1;\n continue;\n }\n if (existing && time(existing.updatedAt) > time(existing.migratedFromUpdatedAt)) {\n plan.skipped.push({ id: row.id, reason: 'Split board item changed after migration' });\n continue;\n }\n try {\n const card = splitLegacyWorkItem(row, {\n workItemId: existing?.workItemId ?? newId(),\n ...(existing ? { revision: Math.max(existing.revision, row.revision) + 1 } : {}),\n });\n if (existing) card.previousHash = existing.migratedFromHash;\n (existing ? plan.recopies : plan.inserts).push(card);\n } catch (error) {\n plan.skipped.push({ id: row.id, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return plan;\n}\n\nasync function migratedBoardItems(\n ops: FactoryStorageOps,\n ids: readonly string[],\n): Promise<Map<string, MigratedBoardItem>> {\n if (!ids.length) return new Map();\n const rows = await ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, { id: { in: [...ids] } });\n return new Map(\n rows.map(row => [\n row.id,\n {\n workItemId: row.work_item_id,\n revision: row.revision,\n updatedAt: row.updated_at,\n migratedFromUpdatedAt: row.migrated_from_updated_at,\n migratedFromHash: row.migrated_from_hash,\n },\n ]),\n );\n}\n\nclass MigrationConflict extends Error {}\n\nasync function writeCard(ops: FactoryStorageOps, card: WorkItemSplitCard, recopy: boolean): Promise<boolean> {\n if (!recopy) {\n // Both paths take this card-specific lock before any card rows. A project-wide\n // lock here would invert the row-lock order of parent/child and bulk deletions.\n const guard = await ops.updateAtomic(\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name,\n { id: card.boardItem.id },\n () => null,\n );\n if (!guard)\n await ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, {\n id: card.boardItem.id,\n org_id: card.boardItem.org_id,\n factory_project_id: card.boardItem.factory_project_id,\n });\n if (await ops.findOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, { id: card.boardItem.id })) return false;\n const existing = await ops.findOne<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id });\n if (existing) {\n if (existing.migrated_from_hash === card.boardItem.migrated_from_hash) return false;\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n await ops.insertOne<WorkItemDbRecord>(WORK_ITEMS, card.workItem);\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n await ops.insertOne<BoardItemDbRecord>(BOARD_ITEMS, card.boardItem);\n return true;\n }\n // updateAtomic locks the board row until this transaction commits, so a new\n // transition cannot land between the overwrite guard and the copy.\n let unchanged = false;\n let baseline = Number.NEGATIVE_INFINITY;\n const board = await ops.updateAtomic<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id }, current => {\n if (current.migrated_from_hash === card.boardItem.migrated_from_hash) {\n unchanged = true;\n return null;\n }\n if (current.migrated_from_hash !== card.previousHash) {\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n if (time(current.updated_at) > time(current.migrated_from_updated_at)) {\n throw new MigrationConflict('Split board item changed after migration');\n }\n baseline = time(current.migrated_from_updated_at);\n return {\n ...card.boardItem,\n revision: Math.max(current.revision, card.boardItem.revision) + 1,\n };\n });\n if (unchanged) return false;\n if (!board) throw new MigrationConflict('Split board item disappeared during migration');\n await ops.updateAtomic<WorkItemDbRecord>(WORK_ITEMS, { id: card.workItem.id }, current => {\n if (time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split work item changed after migration');\n }\n return { ...card.workItem, revision: current.revision + 1 };\n });\n const sources = await ops.findMany<WorkItemSourceDbRecord>(SOURCES, { work_item_id: card.workItem.id });\n if (sources.some(source => source.id !== card.workItem.id)) {\n throw new MigrationConflict('Split source set changed after migration');\n }\n for (const source of sources) {\n await ops.updateAtomic<WorkItemSourceDbRecord>(SOURCES, { id: source.id }, current => {\n if (current.synced_at != null || time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split source changed after migration');\n }\n return null;\n });\n }\n if (sources.length) await ops.deleteMany(SOURCES, { id: { in: sources.map(source => source.id) } });\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n return true;\n}\n\nexport interface LegacyWatermark {\n updatedAt: Date;\n id: string;\n}\n\nexport interface WorkItemSplitMarker {\n /** Newest legacy row when the finished pass began; null when the legacy table was empty. */\n watermark: LegacyWatermark | null;\n completedAt: Date;\n}\n\nconst SPLIT_STATE = FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA.name;\nconst SPLIT_MARKER_ID = 'work_item_split';\n\n/** The newest legacy write, by `(updated_at, id)`; one indexed row. */\nexport async function readLegacyWatermark(ops: FactoryStorageOps): Promise<LegacyWatermark | null> {\n const [row] = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: 1,\n },\n );\n return row ? { updatedAt: row.updated_at, id: row.id } : null;\n}\n\nexport async function readWorkItemSplitMarker(ops: FactoryStorageOps): Promise<WorkItemSplitMarker | null> {\n const row = await ops.findOne<{ legacy_updated_at: Date | null; legacy_id: string | null; completed_at: Date }>(\n SPLIT_STATE,\n { id: SPLIT_MARKER_ID },\n );\n if (!row) return null;\n return {\n watermark: row.legacy_updated_at && row.legacy_id ? { updatedAt: row.legacy_updated_at, id: row.legacy_id } : null,\n completedAt: row.completed_at,\n };\n}\n\n/** Marks every legacy row up to `watermark` as copied. */\nexport async function recordWorkItemSplitComplete(\n ops: FactoryStorageOps,\n watermark: LegacyWatermark | null,\n): Promise<void> {\n await ops.upsertOne(SPLIT_STATE, ['id'], {\n id: SPLIT_MARKER_ID,\n legacy_updated_at: watermark?.updatedAt ?? null,\n legacy_id: watermark?.id ?? null,\n completed_at: new Date(),\n });\n}\n\n/**\n * Copies legacy cards that have no split rows yet, inside the caller's\n * transaction. Tombstoned cards and cards whose source another card already\n * holds are left alone; the source is checked first because a unique violation\n * would abort the caller's Postgres transaction. Returns the copied ids.\n */\nexport async function copyLegacyRows(ops: FactoryStorageOps, rows: readonly WorkItemDbRow[]): Promise<string[]> {\n const copied: string[] = [];\n for (const row of rows) {\n let card: WorkItemSplitCard;\n try {\n card = splitLegacyWorkItem(row, { workItemId: randomUUID() });\n } catch {\n continue;\n }\n if (\n card.source &&\n (await ops.findOne(SOURCES, {\n org_id: card.source.org_id,\n factory_project_id: card.source.factory_project_id,\n provider: card.source.provider,\n external_id: card.source.external_id,\n }))\n ) {\n continue;\n }\n try {\n if (await writeCard(ops, card, false)) copied.push(row.id);\n } catch (error) {\n if (!(error instanceof MigrationConflict)) throw error;\n }\n }\n return copied;\n}\n\nexport interface MigrateWorkItemSplitOptions {\n dryRun?: boolean;\n ops?: FactoryStorageOps;\n /** Receives single-line progress and summary messages. */\n log?: (line: string) => void;\n /** Names the pass in log lines, e.g. `boot pass`. */\n label?: string;\n /** Minimum time between progress lines; a pass shorter than this logs none. */\n progressIntervalMs?: number;\n now?: () => number;\n /** Rows this returns false for are counted as deferred and not looked up. */\n include?: (row: WorkItemDbRow) => boolean | Promise<boolean>;\n /** Scan only legacy rows written after this watermark, in `(updated_at, id)` order. */\n since?: LegacyWatermark | null;\n pageSize?: number;\n /** Checked between cards and pages; an aborted pass reports `aborted`. */\n signal?: AbortSignal;\n}\n\n/** Legacy rows are read-only; each card and all its split rows land atomically. */\nexport async function migrateWorkItemSplit(\n storage: Pick<FactoryStorage, 'ops' | 'withTransaction'>,\n {\n dryRun = false,\n ops = storage.ops,\n log,\n include,\n since,\n pageSize = PAGE_SIZE,\n signal,\n label,\n progressIntervalMs = PROGRESS_LOG_INTERVAL_MS,\n now = Date.now,\n }: MigrateWorkItemSplitOptions = {},\n): Promise<WorkItemSplitReport> {\n const report: WorkItemSplitReport = {\n dryRun,\n projects: 0,\n cards: 0,\n deferred: 0,\n workItems: 0,\n sources: 0,\n boardItems: 0,\n recopied: 0,\n unchanged: 0,\n skipped: [],\n aborted: false,\n };\n const projects = new Set<string>();\n const orderBy: Array<[string, 'asc']> = since\n ? [\n ['updated_at', 'asc'],\n ['id', 'asc'],\n ]\n : [\n ['org_id', 'asc'],\n ['factory_project_id', 'asc'],\n ['created_at', 'asc'],\n ['id', 'asc'],\n ];\n let cursor: CollectionValue[] | undefined = since ? [since.updatedAt, since.id] : undefined;\n const title = `work item split${dryRun ? ' (dry run)' : ''}${label ? ` (${label})` : ''}`;\n let lastProgressAt = now();\n // Counted only once a progress line is due, so a fast pass pays nothing; unknown for a `since` scan.\n let total: number | null | undefined = since ? null : undefined;\n const progress = async () => {\n if (!log || now() - lastProgressAt < progressIntervalMs) return;\n if (total === undefined) total = (await ops.count?.(LEGACY, {})) ?? null;\n lastProgressAt = now();\n const checked = total === null ? fmt(report.cards) : `${fmt(report.cards)}/${fmt(total)}`;\n log(`${title}: ${checked} cards checked, ${fmt(report.workItems)} copied, ${fmt(report.skipped.length)} skipped`);\n };\n while (!signal?.aborted) {\n const page = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n { orderBy, limit: pageSize, ...(cursor ? { cursor: { values: cursor } } : {}) },\n );\n if (!page.length) break;\n const last = page[page.length - 1]!;\n cursor = since ? [last.updated_at, last.id] : [last.org_id, last.factory_project_id, last.created_at, last.id];\n report.cards += page.length;\n const rows: WorkItemDbRow[] = [];\n for (const row of page) {\n projects.add(`${row.org_id}\\u0000${row.factory_project_id}`);\n if (!include || (await include(row))) rows.push(row);\n else report.deferred += 1;\n }\n const written = new Map<string, BoardScope>();\n if (rows.length) {\n const tombstones = await ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, {\n id: { in: rows.map(row => row.id) },\n });\n const deleted = new Set(tombstones.map(row => row.id));\n report.unchanged += deleted.size;\n const plan = planWorkItemSplit(\n rows.filter(row => !deleted.has(row.id)),\n await migratedBoardItems(\n ops,\n rows.map(row => row.id),\n ),\n );\n report.unchanged += plan.unchanged;\n report.skipped.push(...plan.skipped);\n for (const { card, recopy } of [\n ...plan.inserts.map(card => ({ card, recopy: false })),\n ...plan.recopies.map(card => ({ card, recopy: true })),\n ]) {\n if (signal?.aborted) break;\n if (!dryRun) {\n try {\n const changed = await storage.withTransaction(tx => writeCard(tx, card, recopy));\n if (!changed) {\n report.unchanged += 1;\n continue;\n }\n } catch (error) {\n if (!(error instanceof UniqueViolationError) && !(error instanceof MigrationConflict)) throw error;\n const raced = (await migratedBoardItems(ops, [card.boardItem.id])).get(card.boardItem.id);\n if (raced?.migratedFromHash === card.boardItem.migrated_from_hash) report.unchanged += 1;\n else {\n const reason =\n error instanceof UniqueViolationError &&\n (error.collection === SOURCES || error.collection === BOARD_ITEMS)\n ? `Conflicting source: ${error.message}`\n : error.message;\n report.skipped.push({ id: card.boardItem.id, reason });\n }\n continue;\n }\n }\n await progress();\n report.workItems += 1;\n report.sources += card.source ? 1 : 0;\n report.boardItems += 1;\n if (recopy) report.recopied += 1;\n written.set(`${card.boardItem.org_id}\\u0000${card.boardItem.factory_project_id}`, {\n orgId: card.boardItem.org_id,\n factoryProjectId: card.boardItem.factory_project_id,\n });\n }\n }\n // Per page, so cached boards pick up a long pass's cards as they land.\n if (!dryRun && written.size) await bumpBoardVersions(ops, [...written.values()]);\n if (page.length < pageSize) break;\n await progress();\n }\n report.aborted = signal?.aborted ?? false;\n report.projects = projects.size;\n if (log && (report.workItems || report.skipped.length || dryRun)) log(summaryLine(title, report));\n return report;\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,SAAS,kBAAkB;AACjC,MAAM,aAAa,0BAA0B;AAC7C,MAAM,UAAU,iCAA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OAAO,aAAa;MACpB;KACF;IACF,SAAS,OAAO;KACd,IAAI,EAAE,iBAAiB,yBAAyB,EAAE,iBAAiB,oBAAoB,MAAM;KAE7F,KADe,MAAM,mBAAmB,KAAK,CAAC,KAAK,UAAU,EAAE,CAAC,EAAA,CAAG,IAAI,KAAK,UAAU,EAC9E,CAAC,EAAE,qBAAqB,KAAK,UAAU,oBAAoB,OAAO,aAAa;UAClF;MACH,MAAM,SACJ,iBAAiB,yBAChB,MAAM,eAAe,WAAW,MAAM,eAAe,eAClD,uBAAuB,MAAM,YAC7B,MAAM;MACZ,OAAO,QAAQ,KAAK;OAAE,IAAI,KAAK,UAAU;OAAI;MAAO,CAAC;KACvD;KACA;IACF;IAEF,MAAM,SAAS;IACf,OAAO,aAAa;IACpB,OAAO,WAAW,KAAK,SAAS,IAAI;IACpC,OAAO,cAAc;IACrB,IAAI,QAAQ,OAAO,YAAY;IAC/B,QAAQ,IAAI,GAAG,KAAK,UAAU,OAAO,QAAQ,KAAK,UAAU,sBAAsB;KAChF,OAAO,KAAK,UAAU;KACtB,kBAAkB,KAAK,UAAU;IACnC,CAAC;GACH;EACF;EAEA,IAAI,CAAC,UAAU,QAAQ,MAAM,MAAM,kBAAkB,KAAK,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC;EAC/E,IAAI,KAAK,SAAS,UAAU;EAC5B,MAAM,SAAS;CACjB;CACA,OAAO,UAAU,QAAQ,WAAW;CACpC,OAAO,WAAW,SAAS;CAC3B,IAAI,QAAQ,OAAO,aAAa,OAAO,QAAQ,UAAU,SAAS,IAAI,YAAY,OAAO,MAAM,CAAC;CAChG,OAAO;AACT"}
@@ -9,7 +9,7 @@ Help the user change Factory policy in the typed deployment configuration. Facto
9
9
 
10
10
  ## Find the configuration
11
11
 
12
- 1. Search for `new MastraFactory`, its `boards` and `includeDefaultBoards` options, `defineBoard`, `configVersion`, and the installed `GithubIntegration`, `PlatformGithubIntegration`, `LinearIntegration`, or `PlatformLinearIntegration` constructors and their `rules` options.
12
+ 1. Search for `new MastraFactory`, its `boards` option, `factory.upsertBoard` calls, `defineBoard`, `configVersion`, and the installed `GithubIntegration`, `PlatformGithubIntegration`, `LinearIntegration`, or `PlatformLinearIntegration` constructors and their `rules` options.
13
13
  2. Read the existing rule configuration and its tests before editing.
14
14
  3. Import rule helpers and types from the same local Factory module used by the deployment.
15
15
  4. For custom-board handlers or phase semantics (`kind`, `role`), edit the installed `defineBoard()` definition. For tool-result rules, add `tools: { <toolName>: { onResult } }` to the installed `defineBoard()` definition of the board whose seat produces the result. For GitHub or Linear rules, configure the installed integration constructor directly.
@@ -18,9 +18,9 @@ Do not guess a file path. Factory deployments can assemble `MastraFactory` from
18
18
 
19
19
  ## Preserve the public shape
20
20
 
21
- A phase starts its work only through its stored `runner` (`skill`, `context`, `instructions`, `goal`); `onEnter`, `onExit` and `outcomes` in `defineBoard()` are ignored with a warning. Work installs automatically with preferred defaults. Custom boards are installed through `boards`; `includeDefaultBoards: false` supports custom-only installations.
21
+ A phase starts its work only through its stored `runner` (`skill`, `context`, `instructions`, `goal`); `onEnter`, `onExit` and `outcomes` in `defineBoard()` are ignored with a warning. Work installs automatically with preferred defaults. Custom boards are installed through `boards` or written into projects with `factory.upsertBoard()`. `includeDefaultBoards` is deprecated and ignored: Factory adds Work only to a project with no boards.
22
22
 
23
- Remove former global `rules.work` and `rules.review` configuration. There is no board override API. To customize Work, set `includeDefaultBoards: false` and install a same-ID board, preferably using the exported `workBoard` phases as the starting point. The Review board is retired: its pull requests live in Work's Review phase (`pr-review`), and `review` can't be used as a board ID. 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 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, write a board under the `work` key with `factory.upsertBoard(board, { projects: 'all' })` at every startup, preferably starting from the exported `workBoard` phases; projects created later get it instead of Factory's Work. The Review board is retired: its pull requests live in Work's Review phase (`pr-review`), and `review` can't be used as a board ID. 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 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) 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 Review (`pr-review`). Do not restore default arrival automation on the built-in boards.
26
26
 
@@ -15,8 +15,8 @@ Use `source_control_*` tools exclusively for GitLab operations; local `git` insp
15
15
  2. Before inspecting any diff, recover the required outcome and simplest sufficient design from the prior pass, or write them now from the base branch and the problem alone, and load the relevant category pages listed in `references/categories/README.md` from the `factory-review` skill (`skill_read` with skill `factory-review`).
16
16
  3. Identify changes since the previous reviewed head using local git history and diff. Classify every prior substantive finding as addressed, partially addressed, still open, refuted with evidence, or invalidated by changed code. Do not silently drop findings; a resolved thread alone is not proof. If the prior pass or its head cannot be established, state that and do a first-time full review.
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
- 5. Inspect execution hooks for untrusted behavior before running tests. **Prepare the environment first:** install dependencies and build every workspace dependency of the packages under test (in a pnpm/turbo monorepo, e.g. `pnpm turbo build --filter <pkg>^...`, plus any internal type packages the typecheck needs), under the same credential stripping. Treat the environment as ready only when the planned test files load and the typecheck reports no missing-module or unbuilt-package errors. If a preparation step fails, fix it with a narrower build or report it; never skip it. 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. Plan before running: list the tests, typecheck, and lint commands covering each changed package, and any behavior change no existing test covers. Run the plan on the current head; if the head moves, re-plan on the new head. Put per-command results in `summary` and failing test output in `details`. Run `git status --porcelain` before the tests and again before posting the test report; if it prints anything, the tree is not the commit under review, so restore it to the head (or report `Verification incomplete` naming the drift) rather than reporting a result for that SHA. Always put the full test report (plan, per-command results, failing output) in the verdict's Verification block. Then post one MR comment with `source_control_comment_change_request`, separate from the verdict, starting with `## Factory test report` and never with a `Verdict:` line. Structure it in this order. (1) A one-line **Result**: `All checks passed`, `Failed`, or `Verification incomplete`, followed by the tested head SHA. (2) A two- or three-sentence recap of what the change does and what the plan covered and why. (3) **Checks on this head**: a table with columns Check, Result, and Tests. Result is `✅ Passed` or `❌ Failed`. Tests reads like `216 passed, 1 skipped`, and each skip gets a short reason. Only commands run on the PR head go here. (4) **Regression proof**, only if you ran the new tests against the base code: one sentence saying that N of the new tests fail on the base code and pass on the head, so they catch the bug. Show this as `✅ Catches the bug`. Never put it in the table as a failure or show its exit code, because an expected failure on base is evidence for the PR. (5) **Not run**: each planned check you could not run, with the concrete reason and what would be needed to run it. Say whether this blocked approval. Omit the section when it is empty. Do not show raw exit codes or `x/y/z` counts. A reader should see a green table only when everything on the head passed. Approve only if every planned command ran and passed on the current head. A command that exited non-zero, a test file that failed to load, or a typecheck error blocks approval even when you attribute it to the environment or external CI is green. If it cannot be fixed, request changes and say plainly that verification could not be completed, naming the blocker. An environment failure is not a pass: any test file that fails to load, any missing build output, or any typecheck error, including ones outside the changed files, makes the command a failure in the table. Rebuild the missing dependency and run the command again. If it still cannot run, list it under **Not run** with the blocker named. Post a new report for each tested head, and reference it from the verdict.
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`. 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.
18
+ 5. Inspect execution hooks for untrusted behavior before running tests. **Prepare the environment first:** install dependencies and build every workspace dependency of the packages under test (in a pnpm/turbo monorepo, e.g. `pnpm turbo build --filter <pkg>^...`, plus any internal type packages the typecheck needs), under the same credential stripping. Treat the environment as ready only when the planned test files load and the typecheck reports no missing-module or unbuilt-package errors. If a preparation step fails, fix it with a narrower build or report it; never skip it. 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. Plan before running: list the tests, typecheck, and lint commands covering each changed package, and any behavior change no existing test covers. Run the plan on the current head; if the head moves, re-plan on the new head. Put per-command results in `summary` and failing test output in `details`. Run `git status --porcelain` before the tests and again before posting the test report; if it prints anything, the tree is not the commit under review, so restore it to the head (or report `Verification incomplete` naming the drift) rather than reporting a result for that SHA. Always put the full test report (plan, per-command results, failing output) in the session handoff. Then post one MR comment with `source_control_comment_change_request`, separate from the verdict, starting with `## Factory test report` and never with a `Verdict:` line. Structure it like this. The line right after the `## Factory test report` heading is the result, `✅ All checks passed`, `❌ Failed`, or `⚠️ Verification incomplete`, followed by the full tested head SHA. Then a table with columns Check, Result, and Tests: Result is `✅ Passed` or `❌ Failed`, and Tests reads like `216 passed, 1 skipped`, with a short reason for each skip. Only commands run on this head go in the table. When the PR fixes a bug and the tests meant to reproduce it were also run against the base code, add a `New tests on base code` row whose Result is `✅ Catches the bug` when they fail there for the expected reason and pass on head, or `❌ Does not catch the bug` when they pass there. Add a **Not run:** line only when a planned check could not run, naming the reason and whether it blocked approval. No recap paragraph. Do not show raw exit codes or `x/y/z` counts. A reader should see a green table only when everything on the head passed. Approve only if every planned command ran and passed on the current head. A command that exited non-zero, a test file that failed to load, or a typecheck error blocks approval even when you attribute it to the environment or external CI is green. If it cannot be fixed, request changes and say plainly that verification could not be completed, naming the blocker. An environment failure is not a pass: any test file that fails to load, any missing build output, or any typecheck error, including ones outside the changed files, makes the command a failure in the table. Rebuild the missing dependency and run the command again. If it still cannot run, list it under **Not run** with the blocker named. Post a new report for each tested head, and reference it from the verdict.
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, end every published body with the footer `<sub>[Factory session](<sessionUrl>)</sub>`, the only routing fact published (approve, request-changes comment, and the approval-fallback comment).
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. The body is short: every line has to earn its place, with plain words, no jargon, no restating the diff, and no praise. Line 1 is `## Verdict: approve` or `## Verdict: request changes` and nothing else; line 2 is `Reviewed head: <full SHA>` equal to the current MR head, the `commitId`, and the `reviewedHeadSha` you record. Then one sentence of at most 25 words saying what blocks the merge or why it is safe to merge. Then a findings table with columns #, Severity (triage dot scale, dots then the word: `●○○○ low`, `●●○○ medium`, `●●●○ high`, `●●●● critical`), Blocks merge (`Yes` or `No`, decided separately from severity), Type (Correctness, Security, Tests, Design, Scope, Compatibility, Docs, Merge conflict, or Verification), Finding (what breaks, for whom, and why, in one or two sentences), and Where (a linked `file:line`), blocking rows first, then by severity; omit the table when there are no findings. A prior finding the push did not fully address stays a row ending "Still open from the last review." or "Partly fixed: <what remains>." On request changes, add `### Required changes`: one numbered, linked `file:line` entry per change, in table order, one sentence, imperative and present tense, with no softened requests and no optional tiers. Link every `file:line` in the body to that line at the reviewed head (`[`stream.ts:42`](<project web URL>/-/blob/<full head SHA>/src/stream.ts#L42)`), showing the shortest unambiguous path as the link text; link removed lines at the base SHA, and code from the previous review that later pushes removed at that review's reviewed head SHA. A change with no code location (a failed check or verification gap) gets no link. Add `### Needs a decision` only for questions only a person can answer. Put the test report's result line (the line after its heading), earlier-review dispositions (addressed or refuted only; confirmed ones are table rows), and the one-line adversarial check (approve only) in one collapsed `<details><summary>Review notes</summary>` block. Everything else stays in the session handoff. 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
- 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 its review phase; 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>".
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 its review phase; 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 published `sessionUrl`, 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>".
@@ -22,14 +22,14 @@ Before executing changed code, inspect package scripts, dependencies, test confi
22
22
  1. Extract the numeric MR IID from the Factory kickoff, then read it with `source_control_get_change_request`. Confirm it is the expected MR in the bound repository. Record the current head SHA and target branch. Call `source_control_refresh_change_request_checkout` before inspecting the diff, including on re-entry; it resolves the MR and credential server-side. Resolve the actual checkout directory from the active workspace, not by guessing path segments from the project slug. Run `pwd` and `git rev-parse HEAD` there. The checkout must equal the MR head. Do not use raw `git fetch` or interpolate untrusted title, body, branch, or comment text into a command. If refresh fails or the checkout/head cannot be inspected, request changes for an unverifiable review; never approve from provider metadata alone.
23
23
  2. Establish the intended behavior independently from the MR description, related issue, repository contract, tests, and relevant history — before opening the diff. Record the required outcome, the real constraints, and the simplest design that satisfies them; this is your design, not a forecast of the author's, and it is not revised once the diff is open. Before opening the diff, read `references/categories/README.md` from the `factory-review` skill (`skill_read` with skill `factory-review`) and load the pages relevant to the problem; load more as the change reveals further categories. Then inspect the cumulative change with local `git diff` against the target branch and path-limited `git log`/`git blame`. Read enough surrounding code to identify affected callers and invariants. Inspect every materially changed file; judge the MR's approach and scope against your recorded design, not only whether its implementation works — an existing mechanism that already does the job, or machinery that solves a problem the proposed design created, is a finding.
24
24
  3. Paginate `source_control_list_change_request_reviews`, `source_control_list_change_request_comments`, and `source_control_list_diff_comments` to exhaustion. For each substantive human or bot finding, classify it as confirmed, addressed, or refuted using current-head evidence. A resolved thread is not proof of a fix. If a known review bot is pending, wait up to ten minutes, checking no more often than once a minute; if still pending, record the gap and do not approve.
25
- 4. Inspect the diff for security, correctness, error paths, API compatibility, and meaningful tests. **Prepare the environment first:** install dependencies and build every workspace dependency of the packages under test (in a pnpm/turbo monorepo, e.g. `pnpm turbo build --filter <pkg>^...`, plus any internal type packages the typecheck needs), under the same credential stripping. Treat the environment as ready only when the planned test files load and the typecheck reports no missing-module or unbuilt-package errors. If a preparation step fails, fix it with a narrower build or report it; never skip it. Execute the narrowest relevant verification and typecheck when applicable and safe. A non-code-only change with no application test harness may be verified with exact content, diff-integrity, and current-head checks; do not invent an inapplicable test requirement. Record exact commands, result, and current head SHA. CI status is advisory; a confirmed defect or failed local verification is not. If a direct run is impossible, provide a concrete source-path or recorded-response substitute and explain the limitation. Plan before running: list the tests, typecheck, and lint commands covering each changed package, and any behavior change no existing test covers. Run the plan on the current head; if the head moves, re-plan on the new head. Put per-command results in `summary` and failing test output in `details`. Run `git status --porcelain` before the tests and again before posting the test report; if it prints anything, the tree is not the commit under review, so restore it to the head (or report `Verification incomplete` naming the drift) rather than reporting a result for that SHA. Always put the full test report (plan, per-command results, failing output) in the verdict's Verification block. Then post one MR comment with `source_control_comment_change_request`, separate from the verdict, starting with `## Factory test report` and never with a `Verdict:` line. Structure it in this order. (1) A one-line **Result**: `All checks passed`, `Failed`, or `Verification incomplete`, followed by the tested head SHA. (2) A two- or three-sentence recap of what the change does and what the plan covered and why. (3) **Checks on this head**: a table with columns Check, Result, and Tests. Result is `✅ Passed` or `❌ Failed`. Tests reads like `216 passed, 1 skipped`, and each skip gets a short reason. Only commands run on the PR head go here. (4) **Regression proof**, only if you ran the new tests against the base code: one sentence saying that N of the new tests fail on the base code and pass on the head, so they catch the bug. Show this as `✅ Catches the bug`. Never put it in the table as a failure or show its exit code, because an expected failure on base is evidence for the PR. (5) **Not run**: each planned check you could not run, with the concrete reason and what would be needed to run it. Say whether this blocked approval. Omit the section when it is empty. Do not show raw exit codes or `x/y/z` counts. A reader should see a green table only when everything on the head passed. Approve only if every planned command ran and passed on the current head. A command that exited non-zero, a test file that failed to load, or a typecheck error blocks approval even when you attribute it to the environment or external CI is green. If it cannot be fixed, request changes and say plainly that verification could not be completed, naming the blocker. An environment failure is not a pass: any test file that fails to load, any missing build output, or any typecheck error, including ones outside the changed files, makes the command a failure in the table. Rebuild the missing dependency and run the command again. If it still cannot run, list it under **Not run** with the blocker named. Post a new report for each tested head, and reference it from the verdict.
25
+ 4. Inspect the diff for security, correctness, error paths, API compatibility, and meaningful tests. **Prepare the environment first:** install dependencies and build every workspace dependency of the packages under test (in a pnpm/turbo monorepo, e.g. `pnpm turbo build --filter <pkg>^...`, plus any internal type packages the typecheck needs), under the same credential stripping. Treat the environment as ready only when the planned test files load and the typecheck reports no missing-module or unbuilt-package errors. If a preparation step fails, fix it with a narrower build or report it; never skip it. Execute the narrowest relevant verification and typecheck when applicable and safe. A non-code-only change with no application test harness may be verified with exact content, diff-integrity, and current-head checks; do not invent an inapplicable test requirement. Record exact commands, result, and current head SHA. CI status is advisory; a confirmed defect or failed local verification is not. If a direct run is impossible, provide a concrete source-path or recorded-response substitute and explain the limitation. Plan before running: list the tests, typecheck, and lint commands covering each changed package, and any behavior change no existing test covers. Run the plan on the current head; if the head moves, re-plan on the new head. Put per-command results in `summary` and failing test output in `details`. Run `git status --porcelain` before the tests and again before posting the test report; if it prints anything, the tree is not the commit under review, so restore it to the head (or report `Verification incomplete` naming the drift) rather than reporting a result for that SHA. Always put the full test report (plan, per-command results, failing output) in the session handoff. Then post one MR comment with `source_control_comment_change_request`, separate from the verdict, starting with `## Factory test report` and never with a `Verdict:` line. Structure it like this. The line right after the `## Factory test report` heading is the result, `✅ All checks passed`, `❌ Failed`, or `⚠️ Verification incomplete`, followed by the full tested head SHA. Then a table with columns Check, Result, and Tests: Result is `✅ Passed` or `❌ Failed`, and Tests reads like `216 passed, 1 skipped`, with a short reason for each skip. Only commands run on this head go in the table. When the PR fixes a bug and the tests meant to reproduce it were also run against the base code, add a `New tests on base code` row whose Result is `✅ Catches the bug` when they fail there for the expected reason and pass on head, or `❌ Does not catch the bug` when they pass there. Add a **Not run:** line only when a planned check could not run, naming the reason and whether it blocked approval. No recap paragraph. Do not show raw exit codes or `x/y/z` counts. A reader should see a green table only when everything on the head passed. Approve only if every planned command ran and passed on the current head. A command that exited non-zero, a test file that failed to load, or a typecheck error blocks approval even when you attribute it to the environment or external CI is green. If it cannot be fixed, request changes and say plainly that verification could not be completed, naming the blocker. An environment failure is not a pass: any test file that fails to load, any missing build output, or any typecheck error, including ones outside the changed files, makes the command a failure in the table. Rebuild the missing dependency and run the command again. If it still cannot run, list it under **Not run** with the blocker named. Post a new report for each tested head, and reference it from the verdict.
26
26
  5. Before any verdict, scrutinize your own requested changes as critically as the MR: establish why each belongs in this MR, assume the author follows them exactly as written, and trace the result through affected callers and contracts — it must satisfy the required outcome without introducing another failure or unnecessary change. Where a probe's ability to detect the claimed failure is uncertain, run a broken control that isolates it, in a disposable worktree, and capture the command's own exit status. Before approval, challenge the strongest plausible failure case. Approval requires affirmative evidence that the checkout equals the current MR head, behavior is established, applicable local verification passed, prior and current reviewer findings are dispositioned, no known bot review is pending, behavior is meaningfully verified for this change, and the adversarial check did not reveal a blocker. A failed sandbox start, inaccessible checkout, missing diff, or unrun applicable tests fails this gate and requires changes. Never treat an inability to inspect as evidence that there are no defects. An assumption never resolves a confirmed finding. A request-changes verdict must name an actionable defect or verification gap; an inapplicable test suite or provider rejection of approval is not itself a defect in the MR.
27
27
 
28
28
  ## Verdict and handoff
29
29
 
30
30
  Before publishing the verdict, call `factory_review_source` (no arguments) once. It returns four fields, every one derived server-side from the bound work item:
31
31
 
32
- - `sessionUrl` — the Factory session URL that produced this review. This is the **only** field published on the MR (see the `Factory Session` block below).
32
+ - `sessionUrl` — the Factory session URL that produced this review. This is the **only** field published on the MR (see the footer below).
33
33
  - `triggeredBy` — the MR author recorded on the review card at intake. Do not publish this; it is an in-run cross-check input and a session-handoff entry only.
34
34
  - `reviewTarget` — the review card's own `{ integrationId, type, externalId, url }`. Do not publish this; it is an in-run cross-check input and a session-handoff entry only.
35
35
  - `boundRepository` — the project identity stamped on the review card at intake (`{ provider: 'gitlab', host, projectId }` here), or `null` when intake recorded none. Do not publish this; record it verbatim in the session handoff.
@@ -41,8 +41,8 @@ Otherwise, run the in-run cross-check:
41
41
  1. Compare `triggeredBy` with the MR author you already read (the GitLab username field). A mismatch means the session is bound to a different MR than the one being reviewed.
42
42
  2. Compare `reviewTarget.url` with the MR URL you read from `source_control_get_change_request`. Intake records the MR URL for every card (`gitlab/rules.ts:481` writes `url: mergeRequest.url ?? web_url ?? <constructed>`), so `reviewTarget.url` covers the normal case. If `reviewTarget.url` is `null` — a card stored without a URL — 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` (`{ provider: 'gitlab', host, projectId }`), and the MR fetch is already binding-scoped (`session/source-control-tools.ts` resolves the repository from the session record, so `source_control_get_change_request` cannot return another project's MR). What is missing is a fetch-side value to compare it against: the normalized change-request result carries no numeric project id or intake identifier, 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.
43
43
 
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.
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, end every published body with the footer `<sub>[Factory session](<sessionUrl>)</sub>`, the only routing fact published (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. 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.
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. The body is short: every line has to earn its place, with plain words, no jargon, no restating the diff, and no praise. Line 1 is `## Verdict: approve` or `## Verdict: request changes` and nothing else; line 2 is `Reviewed head: <full SHA>` equal to the current MR head, the `commitId`, and the `reviewedHeadSha` you record. Then one sentence of at most 25 words saying what blocks the merge or why it is safe to merge. Then a findings table with columns #, Severity (triage dot scale, dots then the word: `●○○○ low`, `●●○○ medium`, `●●●○ high`, `●●●● critical`), Blocks merge (`Yes` or `No`, decided separately from severity), Type (Correctness, Security, Tests, Design, Scope, Compatibility, Docs, Merge conflict, or Verification), Finding (what breaks, for whom, and why, in one or two sentences), and Where (a linked `file:line`), blocking rows first, then by severity; omit the table when there are no findings. On request changes, add `### Required changes`: one numbered, linked `file:line` entry per change, in table order, one sentence, imperative and present tense, with no softened requests and no optional tiers. Link every `file:line` in the body to that line at the reviewed head (`[`stream.ts:42`](<project web URL>/-/blob/<full head SHA>/src/stream.ts#L42)`), showing the shortest unambiguous path as the link text; link removed lines at the base SHA. A change with no code location (a failed check or verification gap) gets no link. Add `### Needs a decision` only for questions only a person can answer. Put the test report's result line (the line after its heading), earlier-review dispositions (addressed or refuted only; confirmed ones are table rows), and the one-line adversarial check (approve only) in one collapsed `<details><summary>Review notes</summary>` block. Everything else stays in the session handoff. 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
- After the review publication attempt, call `factory_record_review_verdict` with the published `verdict` and the verified `reviewedHeadSha`. The card stays in its review phase; 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>".
48
+ After the review publication attempt, call `factory_record_review_verdict` with the published `verdict` and the verified `reviewedHeadSha`. The card stays in its review phase; 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 published `sessionUrl`, 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>".
@@ -11,7 +11,7 @@ Re-review the pull request behind this Factory work item after new commits were
11
11
 
12
12
  You are working in a bound Factory session. Complete the full re-review in one pass, then make `factory_record_review_verdict` your terminal step — one call, repeated only if it is rejected and only with the rejection reason addressed. Never wait for or solicit human input mid-run; every judgment call is yours to resolve.
13
13
 
14
- **Decision rule:** at every fork — did the push actually address a prior finding, is a new pattern deviation deliberate, is the incremental scope creep — pick the answer the history and codebase conventions best support, proceed, and **record the decision as an assumption** for the terminal handoff. Requested changes and decisions a human must make go in the handoff's open questions.
14
+ **Decision rule:** at every fork — did the push actually address a prior finding, is a new pattern deviation deliberate, is the incremental scope creep — pick the answer the history and codebase conventions best support, proceed, and **record the decision as an assumption** for the terminal handoff. Changes the author must make go under **Required changes**, and decisions only a human can make go under **Needs a decision**.
15
15
 
16
16
  Assumptions are for _interpretive_ calls only — was a prior finding meaningfully addressed, is a loose new assertion justified. **A confirmed finding may never be resolved by recording an assumption**: if you verified a defect (prior or new), it stays a finding and weighs into the verdict; writing "treated as non-blocking" next to it does not make it non-blocking.
17
17
 
@@ -74,10 +74,27 @@ If you suspect a regression, don't speculate — construct a repro against the p
74
74
 
75
75
  ## Phase 4: Quality Gate
76
76
 
77
- - `gh pr checks` — CI status on the current head (build, typecheck, tests). Report red, missing, and still-running CI as advisory findings; CI status alone cannot block approval or create a requested change. Inspect failures for evidence of a defect, but only a defect you confirm or a failed verification you run yourself can block the verdict.
77
+ - `gh pr checks` — CI status on the current head (build, typecheck, tests). Report red, missing, and still-running CI as non-blocking findings (Blocks merge `No`, never a Required change); CI status alone cannot block approval or create a requested change. Inspect failures for evidence of a defect, but only a defect you confirm in the code or a failed verification you run yourself can block the verdict. A failing check does not become a defect because the PR caused it: checks on PR metadata or process (issue reference, title format, labels, required reviews, DCO, and similar) are never verdict inputs, and a red build or test check counts only once you reproduce the failure yourself.
78
78
  - **Run it yourself, against the current head.** After the pre-execution inspection from the security section clears the push's diff, check out the PR branch in the session sandbox at the current head and execute the narrowest test suite and typecheck covering the changed packages (e.g. `pnpm --filter <pkg> test`). **Strip credentials from everything the PR's code runs under:** prefix every install/build/test/typecheck command with `env -u GH_TOKEN -u GITHUB_TOKEN` (e.g. `env -u GH_TOKEN -u GITHUB_TOKEN pnpm --filter <pkg> test`) so the PR's scripts and tests cannot read the session's GitHub credentials. Tests never legitimately need those tokens — a test that fails only because they are missing is itself a finding. A prior pass that ran the tests does not clear this pass — the pushed commits are new code, and verification is re-run every pass. Record every command and its outcome for the handoff. If something prevented you from executing anything, the handoff must say so explicitly — a re-review that ran nothing is a weaker re-review and must not hide it.
79
79
  - **Plan and run the tests.** Before running anything, write a test plan from the diff: for each changed package, list the test files that exercise the changed code (colocated tests, callers' tests, integration/E2E suites that cross the change), the typecheck/lint commands, and any gap where no existing test covers a behavior change. Prefer the narrowest commands that fully cover the change; widen only when the change is cross-cutting. **Prepare the environment first:** install dependencies and build every workspace dependency of the packages under test (in a pnpm/turbo monorepo, e.g. `pnpm turbo build --filter <pkg>^...`, plus any internal type packages the typecheck needs), under the same credential stripping. Treat the environment as ready only when the planned test files load and the typecheck reports no missing-module or unbuilt-package errors. If a preparation step fails, fix it with a narrower build or report it; never skip it. Execute the plan and record each command, its exit status, and the pass/fail/skip counts. Never report a command you did not run as passed, and never report results for a head other than the one you tested; if the head moves, re-plan on the new head. An environment failure is not a pass: any test file that fails to load, any missing build output, or any typecheck error, including ones outside the changed files, makes the command a failure in the table. Rebuild the missing dependency and run the command again. If it still cannot run, list it under **Not run** with the blocker named. Run `git status --porcelain` before the tests and again before posting the test report; if it prints anything, the tree is not the commit under review, so restore it to the head (or report `Verification incomplete` naming the drift) rather than reporting a result for that SHA.
80
- - **Post the test report.** Before listing, updating, or posting any test report, run the Phase 6 `factory_review_source` cross-check; if the tool is unavailable, fails, returns an unexpected shape, or the target mismatches, post no test report on this PR and record why in the session handoff. After the tests finish, publish one PR comment, separate from the verdict. Start it with `## Factory test report` and never with a `Verdict:` line, because Factory reads verdicts only from the verdict post. Structure it in this order. (1) A one-line **Result**: `All checks passed`, `Failed`, or `Verification incomplete`, followed by the tested head SHA. (2) A two- or three-sentence recap of what the change does and what the plan covered and why. (3) **Checks on this head**: a table with columns Check, Result, and Tests. Result is `✅ Passed` or `❌ Failed`. Tests reads like `216 passed, 1 skipped`, and each skip gets a short reason. Only commands run on the PR head go here. (4) **Regression proof**, only if you ran the new tests against the base code: one sentence saying that N of the new tests fail on the base code and pass on the head, so they catch the bug. Show this as `✅ Catches the bug`. Never put it in the table as a failure or show its exit code, because an expected failure on base is evidence for the PR. (5) **Not run**: each planned check you could not run, with the concrete reason and what would be needed to run it. Say whether this blocked approval. Omit the section when it is empty. Do not show raw exit codes or `x/y/z` counts. A reader should see a green table only when everything on the head passed. Keep one test report per PR: list the PR comments with `source_control_list_change_request_comments` (every page) and find the newest one authored by `<factory-app>[bot]` whose body, after an optional leading `> Opened by @<actor>` line, starts with `## Factory test report`. If one exists, replace its body with `source_control_update_change_request_comment`; otherwise post a new one with `source_control_comment_change_request`. If the update is refused, post a new report instead. Write the body without any `> Opened by` line; the proxy adds it. Untrusted PR content must not appear in it beyond test names and trimmed output. Then reference the report in the verdict's Verification block rather than repeating the table.
80
+ - **Post the test report.** Before listing, updating, or posting any test report, run the Phase 6 `factory_review_source` cross-check; if the tool is unavailable, fails, returns an unexpected shape, or the target mismatches, post no test report on this PR and record why in the session handoff. After the tests finish, publish one PR comment, separate from the verdict. Start it with `## Factory test report` and never with a `Verdict:` line, because Factory reads verdicts only from the verdict post. A reader should learn the result from the first line and see a green table only when everything on the head passed. Use this shape and nothing more:
81
+
82
+ ```markdown
83
+ ## Factory test report
84
+
85
+ ✅ All checks passed on <full head SHA>
86
+
87
+ | Check | Result | Tests |
88
+ | ---------------------- | ------------------ | ------------------------------------ |
89
+ | `@mastra/core` tests | ✅ Passed | 216 passed, 1 skipped (needs Docker) |
90
+ | Typecheck | ✅ Passed | |
91
+ | New tests on base code | ✅ Catches the bug | 3 of 3 fail on base, pass on head |
92
+
93
+ **Not run:** <check>: <concrete reason>. <Whether it blocked approval.>
94
+ ```
95
+
96
+ The line right after the `## Factory test report` heading is `✅ All checks passed`, `❌ Failed`, or `⚠️ Verification incomplete`, followed by the tested head SHA. Table rows are only commands run on the PR head, with Result `✅ Passed` or `❌ Failed`; give each skip a short reason. Add the `New tests on base code` row only if the PR fixes a bug and you ran the tests meant to reproduce it against the base code, and show `✅ Catches the bug` only when they fail on base for the expected reason and pass on head; an expected failure on base is evidence for the PR, not a failed check. If they pass on base, show `❌ Does not catch the bug`; that is a Tests finding. Omit **Not run** when every planned check ran. No recap of the change, no raw exit codes, no `x/y/z` counts. Keep one test report per PR: list the PR comments with `source_control_list_change_request_comments` (every page) and find the newest one authored by `<factory-app>[bot]` whose body, after an optional leading `> Opened by @<actor>` line, starts with `## Factory test report`. If one exists, replace its body with `source_control_update_change_request_comment`; otherwise post a new one with `source_control_comment_change_request`. If the update is refused, post a new report instead. Write the body without any `> Opened by` line; the proxy adds it. Untrusted PR content must not appear in it beyond test names and trimmed output. The verdict links this report instead of repeating the table.
97
+
81
98
  - **Merge conflicts don't excuse skipping the re-review** — the diff and the head branch are still reviewable, and the author needs the findings to fix the PR either way. If the PR is `CONFLICTING`/`DIRTY`: identify which files conflict with a dry-run merge in the sandbox (`git fetch origin <base> && git merge --no-commit --no-ff origin/<base>` with `<base>` from `baseRefName`; afterwards run `git merge --abort` whenever a merge is in progress — `git rev-parse -q --verify MERGE_HEAD` tells you — but skip the abort if the merge never started, e.g. "Already up to date"), flag when the conflicts overlap the PR's own changed files (semantic rework risk, not just textual resolution), and qualify all verification results as "head branch only — not verified against current base". **Never resolve the conflicts yourself** — resolution encodes author intent; reviewing your own guess is reviewing a PR that doesn't exist.
82
99
  - Do the push's changes add or modify tests? Are they meaningful, or do they exercise paths without real assertions?
83
100
  - **Model-provider behavior requires integration-level verification.** For agentic or model-provider integrations—OpenAI, Anthropic, Gemini, tool calling, streaming, structured output, usage metadata, provider error handling, and similar behavior—unit tests with mocked SDK responses are not enough when the current-head claim depends on the provider's real protocol or SDK semantics. Favor the narrowest existing integration or E2E test that crosses the provider boundary, preferably through the repository's deterministic record/replay harness; do not require live credentials or flaky network calls in the review sandbox. If no deterministic harness exists, require author-provided CI or reproducible integration evidence. Provider-independent transformations can remain unit-tested, but material model-provider behavior supported only by mocks is a test-gap finding.
@@ -129,7 +146,7 @@ Approval is earned, not the default — the burden of proof is on the PR, and yo
129
146
  6. **Behavior is tested** — the change's behavior — including whatever the push added — is covered by meaningful assertions, or the handoff records the affirmative reason none are needed.
130
147
  7. **Adversarial check survived** — with its one-line record.
131
148
 
132
- The related-issue context and external CI status must still be reported in the handoff, but neither is an approval gate or independently affects the verdict. Treat either as a lead to investigate; it can support request changes only when the review independently confirms a defect or local verification fails.
149
+ The related-issue context and external CI status must still be reported in the handoff, but neither is an approval gate or independently affects the verdict. Treat either as a lead to investigate; it can support request changes only when the review independently confirms a defect in the code or local verification fails. Never request changes to satisfy a CI check, merge policy, or PR-metadata requirement — if those are the only issues, approve and list them as non-blocking findings.
133
150
 
134
151
  If any gate fails, the verdict is request changes. This is the concrete meaning of "the PR earns the approval": the reviewer never grants what the evidence didn't establish.
135
152
 
@@ -139,7 +156,7 @@ Do not hedge between the two — pick the verdict the evidence supports. When ge
139
156
 
140
157
  Before composing the handoff, call `factory_review_source` (no arguments) once. It returns four fields, every one derived server-side from the bound work item:
141
158
 
142
- - `sessionUrl` — the Factory session URL that produced this re-review. This is the **only** field published on the PR (see the Factory Session block below).
159
+ - `sessionUrl` — the Factory session URL that produced this re-review. This is the **only** field published on the PR (see the published body's footer below).
143
160
  - `triggeredBy` — the PR author recorded on the review card at intake. Do not publish this; it is an in-run cross-check input and a session-handoff entry only.
144
161
  - `reviewTarget` — the review card's own `{ integrationId, type, externalId, url }`. Do not publish this; it is an in-run cross-check input and a session-handoff entry only.
145
162
  - `boundRepository` — the repository identity stamped on the review card at intake (`{ provider: 'github', repositoryId }` here), or `null` when intake recorded none. Do not publish this; it is the binding-side input to the null-`url` fallback below.
@@ -155,23 +172,52 @@ On any mismatch, stop and record it as a blocking security finding with both val
155
172
 
156
173
  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.
157
174
 
158
- 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:
175
+ The **published body** (what `gh pr review --body-file` receives) is what the author reads, often from a notification. Every line has to earn its place: plain words, no jargon, no restating the diff, no praise, nothing about the author. The verdict comes first and the findings come next; anything a reader does not need in order to act or to trust the verdict stays in the session handoff. Use this shape, dropping each optional part that would be empty:
176
+
177
+ ```markdown
178
+ ## Verdict: request changes
179
+
180
+ Reviewed head: <full 40-character SHA>
181
+
182
+ <One sentence: what blocks the merge, or why it is safe to merge.>
183
+
184
+ | # | Severity | Blocks merge | Type | Finding | Where |
185
+ | --- | --------- | ------------ | ----------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------- |
186
+ | 1 | ●●●○ high | Yes | Correctness | <What breaks, for whom, and why.> | [`stream.ts:42`](https://github.com/<owner>/<repo>/blob/<headSha>/src/stream.ts#L42) |
187
+ | 2 | ●○○○ low | No | Tests | <What is missing and what it would catch.> | [`stream.test.ts:10`](https://github.com/<owner>/<repo>/blob/<headSha>/src/stream.test.ts#L10) |
188
+
189
+ ### Required changes
190
+
191
+ 1. [`stream.ts:42`](https://github.com/<owner>/<repo>/blob/<headSha>/src/stream.ts#L42): <Imperative change.>
192
+
193
+ ### Needs a decision
194
+
195
+ - <Question only a person can answer, and the answer this re-review assumed.>
196
+
197
+ <details>
198
+ <summary>Review notes</summary>
199
+
200
+ - **Tests:** <The test report's result line (the line after its heading), linked to the report.>
201
+ - **Last review:** <Each prior-pass finding the push addressed, refuted, or made obsolete, by subject and `file:line`, with the commit or evidence in a few words.>
202
+ - **Earlier reviews:** <Reviewer, subject, `file:line`: addressed or refuted, with the evidence in a few words.>
203
+ - **Why approve:** <The strongest case for request changes, and why it fails.>
204
+
205
+ </details>
159
206
 
160
- - **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.
161
- - **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.
162
- - **Approach** — the required outcome and the simplest sufficient design from your Phase 1 record (recovered or rewritten), and whether the PR's approach and scope — with the push folded in — are justified against it. Agreement stated in one line; disagreement with the evidence that supports the alternative.
163
- - **Issue and intent** — the authorizing issue, current PR classification, current approval-label state, and whether the cumulative implementation and scope match the independently established contract and approved discussion. State what changed from the prior issue/intent understanding, if anything.
164
- - **Verification** — every command you executed against the current head (tests, typecheck, repros) with its outcome, including base-versus-current-head evidence for affected behavior-changing claims and prior-head-versus-current-head evidence for push regressions, or an explicit statement that something could not be executed and the substitute evidence used. Verification the prior pass ran is not restated here — only what this pass ran counts.
165
- - **Other-reviewer disposition** — any substantive finding posted by another reviewer (bot or human) since the prior pass, with its classification: confirmed, addressed, or refuted with evidence. A major bot comment must never be silently dropped. Name each by subject and `file:line`, and remember the body lands as GitHub markdown — `#1` publishes as a link to issue 1.
166
- - **Adversarial check** (approve only) — the one-line record of why the strongest request-changes case fails.
167
- - **Requested changes** — one entry per change (for a request-changes verdict), imperative and present tense: the file and line, the change, and the consequence or evidence in one or two sentences. Prior-pass changes that remain open reappear here so the author has one current list, not two. Put the change that most affects correctness first; group changes that must land together or state their dependencies. No softened requests ("consider", "you might want to"), no optional or follow-up tiers, no pleasantries, nothing about the author. Preserve qualifications that express real limits of evidence — "the contract does not guarantee this field" must not become "servers never return this field".
168
- - **Assumptions** — every recorded judgment call from this run.
169
- - **Open questions** — any decision that genuinely needs a human.
170
- - **Factory Session** — `sessionUrl` from `factory_review_source`, verbatim, as a link. **Nothing else in this block.** `triggeredBy` and `reviewTarget` are cross-check inputs for the run and go in the session handoff below; they are never published on the PR. This section is required for every verdict and every fallback (approve, request changes, comment fallback) so a suspicious re-review can always be traced back to the run that produced it.
207
+ <sub>[Factory session](sessionUrl) · Review runtime: <model>, reasoning setting: <reasoning>.</sub>
208
+ ```
171
209
 
172
- End the published body with `Review runtime: <model>, reasoning setting: <reasoning>.`, copying both values verbatim from the current `factory-phase` signal.
210
+ - **Verdict.** Line 1 is exactly `## Verdict: approve` or `## Verdict: request changes`, and line 2 is `Reviewed head: <full 40-character SHA>` naming the exact head you verified. Factory parses both lines, so add nothing else to them.
211
+ - **Summary.** One sentence of at most 25 words. On request changes, name what blocks the merge; on approve, say why it is safe to merge. Never "LGTM" or a description of the PR.
212
+ - **Findings table.** One row per finding, ranked: blocking rows first, then by severity. Severity uses the triage dot scale, dots then the word: `●○○○ low`, `●●○○ medium`, `●●●○ high`, `●●●● critical`. Blocks merge is `Yes` or `No`; severity and blocking are separate calls (a missing regression test can be medium and still block). Type is one of Correctness, Security, Tests, Design, Scope, Compatibility, Docs, Merge conflict, or Verification (the review could not complete verification; name the blocker and do not present it as a defect in the author's code). Finding states the problem and its consequence in at most 25 words; keep the evidence for the session handoff unless one clause of it is needed to believe the row. Where is a linked `file:line` (see **Link every code reference**), or `—` when the finding has no single location. A confirmed finding from another reviewer is a row too, crediting them: "(raised by coderabbitai)". A non-blocking row fixed by the follow-up PR ends with "Fixed in the follow-up PR." A design or scope disagreement with your Phase 1 record is a Design or Scope row, not a separate section. A prior-pass finding the push did not fully address stays a row, and its Finding ends with "Still open from the last review." or "Partly fixed: <what remains>." With no findings, write `No findings.` instead of the table.
213
+ - **Required changes** (request changes only). One numbered entry per change, in table order: the linked `file:line`, then one sentence, imperative and present tense. The table already carries the consequence, so don't repeat it. Put changes that must land together in one entry. For a conflicting PR, one entry is "Resolve merge conflicts against `<base>`.", noting when the conflicts overlap the PR's own files. No softened requests ("consider", "you might want to"), no optional or follow-up tiers, no pleasantries. Preserve qualifications that express real limits of evidence: "the contract does not guarantee this field" must not become "servers never return this field".
214
+ - **Needs a decision.** Only questions that genuinely need a person. Omit the section otherwise.
215
+ - **Review notes.** Collapsed, and only what a reader may need to trust the verdict. **Tests** is always present. **Last review** lists only prior-pass findings the push addressed, refuted, or invalidated; findings still open are table rows. Omit it when there are none. **Earlier reviews** lists only findings other reviewers (bots included) posted since the prior pass that are addressed or refuted; confirmed ones are table rows. Omit it when there are none. **Why approve** is the one-line adversarial check record, approve only. Nothing else goes here.
216
+ - **Link every code reference.** Each `file:line` in the published body is a link to that line at the reviewed head: `[`stream.ts:42`](https://github.com/<owner>/<repo>/blob/<headSha>/src/stream.ts#L42)`, with `#L40-L44` for a range. Use the full head SHA in the URL, never a branch name, so the link still shows what you reviewed after more pushes. Show the shortest path that is unambiguous in the PR (usually the file name) as the link text; the link carries the full path. A reference to a removed line links to the base SHA instead, and code from an earlier review that the latest pushes removed links to that review's reviewed head SHA. A change with no code location (an unpushed branch, a failed check, a verification gap) gets no link: state the change in one sentence. A reference to another reviewer's comment links to that comment.
217
+ - **GitHub markdown.** `#1` publishes as a link to issue 1, so name findings by subject and `file:line`, never by `#n`.
218
+ - **Footer.** `sessionUrl` from `factory_review_source`, verbatim, as the Factory session link. It is the only routing fact published: `triggeredBy`, `reviewTarget`, and `boundRepository` are cross-check inputs for the run and are never published on the PR. The footer is required on every verdict and every fallback (approve, request changes, comment fallback), so a suspicious re-review — one that lands on the wrong PR, or approves and requests changes at once — can always be traced back to the run that produced it. Copy both runtime values verbatim from the current `factory-phase` signal.
173
219
 
174
- The **session handoff** (posted as the final conversation message after the verdict is recorded) mirrors the published body and additionally records the routing facts that must not appear on the PR: append a **Factory routing** block with `triggeredBy` verbatim, `reviewTarget` verbatim (`integrationId`, `type`, `externalId`, `url`), `boundRepository` verbatim, and the cross-check outcome — "matched" with the compared value from Phase 1, or "mismatch: <blocking-finding-ref>" if the check produced the blocking security finding above.
220
+ The **session handoff** (posted as the final conversation message after the verdict is recorded) is the full record. It is the published body followed by a **Run record** with: **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, with the commit or `file:line` proving each call), **Approach** (the required outcome and simplest sufficient design from your Phase 1 record, and whether the PR's approach and scope are justified against it), **Issue and intent** (the authorizing issue, PR classification, current approval-label state, and whether the implemented behavior and scope match the independently established contract and approved discussion), **Findings evidence** (the mechanism and evidence behind each table row, grounded in the history you traced), Label each finding `[push]` or `[fresh]` here so the record is honest about where it came from. **Verification** (every command you executed against the current head with its outcome, including base-versus-current-head evidence for affected behavior-changing claims and prior-head-versus-current-head evidence for push regressions, or what could not be executed and the substitute evidence used; verification the prior pass ran does not count; plus how the verdict was published: new review, edit, or comment fallback), **Other-reviewer disposition** (every substantive finding another reviewer, bot or human, posted since the prior pass, classified confirmed, addressed, or refuted with evidence), and **Assumptions** (every recorded judgment call from the run). Then append a **Factory routing** block with `triggeredBy` verbatim, `reviewTarget` verbatim (`integrationId`, `type`, `externalId`, `url`), `boundRepository` verbatim, and the cross-check outcome — "matched" with the compared value from Phase 1, or "mismatch: <blocking-finding-ref>" if the check produced the blocking security finding above.
175
221
 
176
222
  **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.
177
223
 
@@ -179,10 +225,10 @@ Next, publish the re-review on the PR itself — this is part of every pass, not
179
225
 
180
226
  **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:
181
227
 
182
- 1. `head -n1 <file>` is exactly `Verdict: approve` when you will use `--approve`, or exactly `Verdict: request changes` when you will use `--request-changes`.
228
+ 1. `head -n1 <file>` is exactly `## Verdict: approve` when you will use `--approve`, or exactly `## Verdict: request changes` when you will use `--request-changes`.
183
229
  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`.
184
230
 
185
- **Update your earlier verdict instead of stacking a new one.** Before posting, find your latest verdict post on this PR. List `gh api repos/<owner>/<repo>/pulls/<number>/reviews --paginate` and `gh api repos/<owner>/<repo>/issues/<number>/comments --paginate`, keep entries whose `.user.login` is `<factory-app>[bot]` and whose body (after an optional leading `> Opened by @<actor>` line) starts with `Verdict:`, drop reviews in state `DISMISSED`, and take the newest. Then:
231
+ **Update your earlier verdict instead of stacking a new one.** Before posting, find your latest verdict post on this PR. List `gh api repos/<owner>/<repo>/pulls/<number>/reviews --paginate` and `gh api repos/<owner>/<repo>/issues/<number>/comments --paginate`, keep entries whose `.user.login` is `<factory-app>[bot]` and whose body (after an optional leading `> Opened by @<actor>` line) starts with `Verdict:` or `## Verdict:`, drop reviews in state `DISMISSED`, and take the newest. Then:
186
232
 
187
233
  - Your verdict is request changes and the PR author (REST `.user.login`) is not `<factory-app>[bot]`: post a new verdict. Edits send no notification and do not complete a pending re-review request, so a human author would never learn the pass finished.
188
234
  - The latest is a PR comment and you are publishing as a comment (misconfiguration or fallback below): edit it with `gh api -X PATCH repos/<owner>/<repo>/issues/comments/<id> -F body=@<file>`.
@@ -199,7 +245,7 @@ When you are not editing, submit a PR review matching the verdict:
199
245
 
200
246
  **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 author login from the REST lookup in the in-run cross-check (`.user.login`, never `gh pr view`'s `.author.login`, which formats App authors as `app/<slug>` and would hide a match). When they match:
201
247
 
202
- 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.`
248
+ 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 a review or count it toward branch protection. Configure a separate reviewer token for Factory reviews.`
203
249
  2. Publish with `gh pr comment <number> --body-file <file>`. Keep the verdict line first, as above: Factory wakes the author on a request-changes verdict only from a comment, or from a `COMMENTED` review Factory posted on its own PR, whose first line (after the proxy's `> Opened by` line) is the verdict.
204
250
  3. Report the misconfiguration and the publish method under **Verification** and in the **Factory routing** block of the handoff.
205
251
 
@@ -214,13 +260,13 @@ After publishing, reconcile the verdict label: approve adds `status:auto-approve
214
260
  1. Branch from the reviewed PR's current head: `git fetch origin pull/<number>/head && git checkout -b factory/rereview-followups-pr-<number> FETCH_HEAD`.
215
261
  2. Apply the fixes, run the narrowest tests covering them, and commit. **Credit the human whose work these commits build on.** The reviewed PR's `author` (from the Phase 1 `gh pr view --json` call) tells you who: when `is_bot` is false, add a `Co-Authored-By: <login> <ID+<login>@users.noreply.github.com>` trailer to every commit, resolving `ID` with `gh api users/<login> --jq .id`. When the author is a bot — the Factory's own pull requests are — credit the reporter of the issue the PR closes instead, if it links one. Credit nobody rather than guess at an identity: a trailer naming the wrong account is worse than no trailer.
216
262
  3. Push the branch and open a follow-up PR with `gh pr create`: target the reviewed PR's head branch when it lives in this repository, so the author can merge the follow-ups into their PR with one click; when the reviewed PR comes from a fork, target its base branch instead and state in the body that it lands after PR <number>.
217
- 4. Write the follow-up body to `.artifacts/factory-rereview/follow-up-pr-<number>.md`; it links the re-review and lists each finding it addresses, and the handoff links the follow-up PR.
263
+ 4. Write the follow-up body to `.artifacts/factory-rereview/follow-up-pr-<number>.md`; it links the re-review and lists each finding it addresses in one line each, with no other sections, and the handoff links the follow-up PR.
218
264
 
219
265
  Keep it strictly non-blocking and low-risk. A fix that demands design judgment, changes behavior, or grows beyond the mechanical stays a recorded finding — don't ship your own guess. **Never mix blocking findings into a follow-up PR**: those are requested changes on the reviewed PR, and implementing them yourself would review your own code. If tests fail on a follow-up fix, drop that fix and keep it a finding. If there are no such findings, skip this step entirely.
220
266
 
221
267
  Then make your terminal `factory_record_review_verdict` call with the published `verdict` (`approve` or `request changes`) and `reviewedHeadSha`, the head SHA you verified. The card stays in its review phase with the verdict shown on it; the merge moves it to a terminal phase, so never request a stage transition to end the re-review. The next push re-reviews it automatically.
222
268
 
223
- If the call is rejected, read the stated reason, address it (re-examine contested findings, re-review if the PR changed again mid-run), and retry once corrected. Once the verdict is recorded, post the **session handoff** (the published body plus the `Factory routing` block) as your final conversation message — including how the verdict was published — and stop.
269
+ If the call is rejected, read the stated reason, address it (re-examine contested findings, re-review if the PR changed again mid-run), and retry once corrected. Once the verdict is recorded, post the **session handoff** (the published body, the Run record, and the `Factory routing` block) as your final conversation message — including how the verdict was published — and stop.
224
270
 
225
271
  ## Behavior Rules
226
272