@mastra/factory 0.28.0-alpha.5 → 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.
- package/README.md +52 -28
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +5 -5
- package/dist/auth.js.map +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +6 -7
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/index.d.ts +1 -1
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +2 -2
- package/dist/boards/project-boards.d.ts +30 -4
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +71 -19
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/boards/registry.d.ts +7 -1
- package/dist/boards/registry.d.ts.map +1 -1
- package/dist/boards/registry.js +16 -3
- package/dist/boards/registry.js.map +1 -1
- package/dist/boards/semantics.d.ts +5 -4
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +5 -4
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-migrations.d.ts +4 -3
- package/dist/boards/work-migrations.d.ts.map +1 -1
- package/dist/boards/work-migrations.js +6 -5
- package/dist/boards/work-migrations.js.map +1 -1
- package/dist/boards/work-seeds.d.ts +9 -0
- package/dist/boards/work-seeds.d.ts.map +1 -0
- package/dist/boards/work-seeds.js +56 -0
- package/dist/boards/work-seeds.js.map +1 -0
- package/dist/boards/work.d.ts +2 -2
- package/dist/boards/work.d.ts.map +1 -1
- package/dist/boards/work.js +0 -16
- package/dist/boards/work.js.map +1 -1
- package/dist/factory.d.ts +8 -4
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +30 -58
- package/dist/factory.js.map +1 -1
- package/dist/feed-events.d.ts +2 -3
- package/dist/feed-events.d.ts.map +1 -1
- package/dist/feed-events.js +4 -5
- package/dist/feed-events.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/integrations/base.d.ts +0 -11
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
- package/dist/integrations/linear/agent-tools.js +1 -1
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/slack/integration.d.ts +0 -2
- package/dist/integrations/slack/integration.d.ts.map +1 -1
- package/dist/integrations/slack/integration.js +0 -5
- package/dist/integrations/slack/integration.js.map +1 -1
- package/dist/integrations/slack/slack.d.ts +3 -18
- package/dist/integrations/slack/slack.d.ts.map +1 -1
- package/dist/integrations/slack/slack.js +3 -74
- package/dist/integrations/slack/slack.js.map +1 -1
- package/dist/links.d.ts +1 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +1 -2
- package/dist/links.js.map +1 -1
- package/dist/routes/attention-providers.d.ts +0 -25
- package/dist/routes/attention-providers.d.ts.map +1 -1
- package/dist/routes/attention-providers.js +2 -150
- package/dist/routes/attention-providers.js.map +1 -1
- package/dist/routes/attention.d.ts +0 -2
- package/dist/routes/attention.d.ts.map +1 -1
- package/dist/routes/attention.js +2 -13
- package/dist/routes/attention.js.map +1 -1
- package/dist/routes/contracts.d.ts +6 -14
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +4 -2
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/feed-events.d.ts +15 -0
- package/dist/routes/feed-events.d.ts.map +1 -0
- package/dist/routes/feed-events.js +68 -0
- package/dist/routes/feed-events.js.map +1 -0
- package/dist/routes/knowledge.js +1 -1
- package/dist/routes/projects.d.ts +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +1 -1
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/surface.d.ts +0 -7
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -5
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts +0 -3
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +0 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +0 -3
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +5 -7
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +0 -4
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +15 -1
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +21 -5
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.d.ts +0 -4
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
- package/dist/storage/domains/channel-identity/base.js +0 -7
- package/dist/storage/domains/channel-identity/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +6 -8
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +9 -84
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +3 -3
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +10 -10
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -2
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +8 -8
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/tools/read-tools.d.ts +0 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +3 -14
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +0 -3
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +8 -18
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +3 -2
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/description-context.d.ts +5 -0
- package/dist/work-items/description-context.d.ts.map +1 -0
- package/dist/work-items/description-context.js +17 -0
- package/dist/work-items/description-context.js.map +1 -0
- package/dist/work-items/split-migration.d.ts.map +1 -1
- package/dist/work-items/split-migration.js +1 -6
- package/dist/work-items/split-migration.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +3 -3
- package/factory-skills/factory-rereview/SKILL.md +2 -2
- package/factory-skills/factory-review/SKILL.md +2 -2
- package/factory-skills/factory-triage/SKILL.md +3 -2
- package/package.json +6 -6
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
- package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
- package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
- package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
- package/dist/integrations/slack/emoji.d.ts +0 -3
- package/dist/integrations/slack/emoji.d.ts.map +0 -1
- package/dist/integrations/slack/emoji.js +0 -11
- package/dist/integrations/slack/emoji.js.map +0 -1
- package/dist/integrations/slack/feed-publisher.d.ts +0 -26
- package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
- package/dist/integrations/slack/feed-publisher.js +0 -43
- package/dist/integrations/slack/feed-publisher.js.map +0 -1
- package/dist/routes/attention-activity.d.ts +0 -23
- package/dist/routes/attention-activity.d.ts.map +0 -1
- package/dist/routes/attention-activity.js +0 -154
- package/dist/routes/attention-activity.js.map +0 -1
- package/dist/storage/domains/comments/activity.d.ts +0 -40
- package/dist/storage/domains/comments/activity.d.ts.map +0 -1
- package/dist/storage/domains/comments/activity.js +0 -93
- package/dist/storage/domains/comments/activity.js.map +0 -1
- package/dist/storage/domains/comments/actor.d.ts +0 -51
- package/dist/storage/domains/comments/actor.d.ts.map +0 -1
- package/dist/storage/domains/comments/actor.js +0 -37
- package/dist/storage/domains/comments/actor.js.map +0 -1
- package/dist/storage/domains/comments/base.d.ts +0 -245
- package/dist/storage/domains/comments/base.d.ts.map +0 -1
- package/dist/storage/domains/comments/base.js +0 -539
- package/dist/storage/domains/comments/base.js.map +0 -1
- package/dist/storage/domains/comments/domain.d.ts +0 -135
- package/dist/storage/domains/comments/domain.d.ts.map +0 -1
- package/dist/storage/domains/comments/domain.js +0 -284
- package/dist/storage/domains/comments/domain.js.map +0 -1
- package/dist/storage/domains/comments/feed-context.d.ts +0 -22
- package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-context.js +0 -88
- package/dist/storage/domains/comments/feed-context.js.map +0 -1
- package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
- package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
- package/dist/storage/domains/comments/feed-sync.js +0 -1
- package/dist/storage/domains/comments/parse.d.ts +0 -23
- package/dist/storage/domains/comments/parse.d.ts.map +0 -1
- package/dist/storage/domains/comments/parse.js +0 -89
- package/dist/storage/domains/comments/parse.js.map +0 -1
- package/dist/storage/domains/comments/routes.d.ts +0 -24
- package/dist/storage/domains/comments/routes.d.ts.map +0 -1
- package/dist/storage/domains/comments/routes.js +0 -301
- package/dist/storage/domains/comments/routes.js.map +0 -1
- package/dist/storage/domains/comments/schema.d.ts +0 -5
- package/dist/storage/domains/comments/schema.d.ts.map +0 -1
- package/dist/storage/domains/comments/schema.js +0 -178
- package/dist/storage/domains/comments/schema.js.map +0 -1
- package/dist/storage/domains/comments/wire.d.ts +0 -40
- package/dist/storage/domains/comments/wire.d.ts.map +0 -1
- package/dist/storage/domains/comments/wire.js +0 -36
- package/dist/storage/domains/comments/wire.js.map +0 -1
|
@@ -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,OAA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E,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"}
|
|
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,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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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`
|
|
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
|
|
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,
|
|
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
|
|
|
@@ -74,7 +74,7 @@ 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
|
|
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
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:
|
|
@@ -146,7 +146,7 @@ Approval is earned, not the default — the burden of proof is on the PR, and yo
|
|
|
146
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.
|
|
147
147
|
7. **Adversarial check survived** — with its one-line record.
|
|
148
148
|
|
|
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 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.
|
|
150
150
|
|
|
151
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.
|
|
152
152
|
|
|
@@ -80,7 +80,7 @@ Bots have false positives — verify, don't rubber-stamp. But a major finding fr
|
|
|
80
80
|
|
|
81
81
|
## Phase 3: Quality Gate
|
|
82
82
|
|
|
83
|
-
- `gh pr checks` — CI status (build, typecheck, tests). Report red, missing, and still-running CI as
|
|
83
|
+
- `gh pr checks` — CI status (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.
|
|
84
84
|
- **Run it yourself.** After the pre-execution inspection from the security section clears the diff, check out the PR branch in the session sandbox 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. CI green is corroboration, not a substitute — reading code predicts behavior, running it proves behavior. Record every command and its outcome for the handoff. If something prevented you from executing anything, the handoff must say so explicitly — a review that ran nothing is a weaker review and must not hide it.
|
|
85
85
|
- **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.
|
|
86
86
|
- **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:
|
|
@@ -149,7 +149,7 @@ Approval is earned, not the default — the burden of proof is on the PR, and yo
|
|
|
149
149
|
5. **Behavior is tested** — the change's behavior is covered by meaningful assertions, or the handoff records the affirmative reason none are needed.
|
|
150
150
|
6. **Adversarial check survived** — with its one-line record.
|
|
151
151
|
|
|
152
|
-
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.
|
|
152
|
+
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.
|
|
153
153
|
|
|
154
154
|
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.
|
|
155
155
|
|
|
@@ -33,7 +33,7 @@ Gauge the people involved: the author's merged-PR/issue counts (`gh pr list --au
|
|
|
33
33
|
|
|
34
34
|
If the issue is vague, do not stop to ask for clarification. Investigate the most plausible reading of it, record that reading as an assumption, and note what extra information from the reporter would firm it up as an open question.
|
|
35
35
|
|
|
36
|
-
At the end of this phase, publish a small summary to the source issue as stated below. For GitHub issues, call `github_upsert_factory_triage_comment` with the issue number and the marker-prefixed pending summary; it updates Factory’s canonical marked comment or creates it when absent. For Linear issues,
|
|
36
|
+
At the end of this phase, publish a small summary to the source issue as stated below. For GitHub issues, call `github_upsert_factory_triage_comment` with the issue number and the marker-prefixed pending summary; it updates Factory’s canonical marked comment or creates it when absent. For Linear issues, post the pending summary with `linear_create_comment`, leaving out the `<!-- mastra-factory-triage -->` marker line: Linear does not render HTML and would show it as text. For Jira issues, post a plain-text `Triage in progress: <one or two sentences>` with `jira_create_comment`; Jira renders comments as plain text, so omit the HTML marker. incident.io has no writeback tool and GitLab has no issue-comment tool, so skip the pending summary for those sources; the handoff lives in this conversation.
|
|
37
37
|
|
|
38
38
|
```markdown
|
|
39
39
|
<!-- mastra-factory-triage -->
|
|
@@ -153,6 +153,7 @@ Fill the placeholders as follows:
|
|
|
153
153
|
- Keep everything else in the one collapsed **Details** block. Only the ratings table, the summary, the next step, and open questions stay visible. Every line in Details has to earn its place: cut anything a planner would not act on.
|
|
154
154
|
- On GitHub, link every file or `file:line` reference to the code at the commit you investigated: `[`stream.ts:42`](https://github.com/<owner>/<repo>/blob/<full SHA>/src/stream.ts#L42)`. Use the full SHA, not a branch name, so the link keeps pointing at the code you read. Link issues, PRs, and commits you mention too.
|
|
155
155
|
- Use no alerts or emoji, and no tables other than the ratings table.
|
|
156
|
+
- On Linear, which renders Markdown but no HTML, adapt the template: leave out the `<!-- mastra-factory-triage -->` marker line, and write the collapsed block in Linear's own syntax — a `+++ Details` line opens it and a lone `+++` line closes it, each with a blank line around it — in place of the `<details>`, `<summary>` and `</details>` lines. Everything else stays the same.
|
|
156
157
|
|
|
157
158
|
Severity guide:
|
|
158
159
|
|
|
@@ -207,7 +208,7 @@ Apply only these label mutations. Do not remove `status: needs approval` merely
|
|
|
207
208
|
|
|
208
209
|
For non-GitHub sources, use the same structured handoff without attempting GitHub publication or label mutations:
|
|
209
210
|
|
|
210
|
-
- Linear issues →
|
|
211
|
+
- Linear issues → post the handoff as a new comment with `linear_create_comment`, in the Linear form the output contract describes (no marker line, `+++ Details` … `+++` instead of `<details>`).
|
|
211
212
|
- Jira issues → post a new plain-text comment with `jira_create_comment` (Jira has no marked-comment upsert and shows Markdown tables and HTML literally). The Jira audience may not have access to the target repository, so post only a reporter-safe summary: type, severity, route, and a few sentences on the conclusion and next step. Keep file paths, code, reproduction steps, and repository history out of it; the full handoff stays in this conversation.
|
|
212
213
|
- incident.io follow-ups and GitLab issues → no external publication; the final conversation message is the handoff.
|
|
213
214
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/factory",
|
|
3
|
-
"version": "0.28.0-alpha.
|
|
3
|
+
"version": "0.28.0-alpha.6",
|
|
4
4
|
"description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -60,10 +60,10 @@
|
|
|
60
60
|
"zod": "^4.6.7",
|
|
61
61
|
"@mastra/auth-studio": "1.4.0-alpha.1",
|
|
62
62
|
"@mastra/auth-workos": "1.6.8",
|
|
63
|
-
"@mastra/code-sdk": "1.19.0-alpha.
|
|
63
|
+
"@mastra/code-sdk": "1.19.0-alpha.6",
|
|
64
64
|
"@mastra/connect": "1.3.2-alpha.2",
|
|
65
|
-
"@mastra/core": "1.83.0-alpha.
|
|
66
|
-
"@mastra/mcp": "2.9.0-alpha.
|
|
65
|
+
"@mastra/core": "1.83.0-alpha.6",
|
|
66
|
+
"@mastra/mcp": "2.9.0-alpha.3",
|
|
67
67
|
"@mastra/platform-workspace": "1.13.0-alpha.0",
|
|
68
68
|
"@mastra/slack": "1.9.0-alpha.0"
|
|
69
69
|
},
|
|
@@ -76,10 +76,10 @@
|
|
|
76
76
|
"@internal/lint": "0.0.148",
|
|
77
77
|
"@internal/types-builder": "0.0.123",
|
|
78
78
|
"@internal/workspace": "0.0.20",
|
|
79
|
-
"@mastra/deployer": "1.83.0-alpha.
|
|
79
|
+
"@mastra/deployer": "1.83.0-alpha.6",
|
|
80
80
|
"@mastra/libsql": "1.30.0-alpha.2",
|
|
81
81
|
"@mastra/pg": "1.36.0-alpha.2",
|
|
82
|
-
"@mastra/server": "1.83.0-alpha.
|
|
82
|
+
"@mastra/server": "1.83.0-alpha.6"
|
|
83
83
|
},
|
|
84
84
|
"engines": {
|
|
85
85
|
"node": ">=22.19.0"
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
|
|
3
|
-
*
|
|
4
|
-
* Source: https://raw.githubusercontent.com/iamcal/emoji-data/097705020bcf82331c9ef10df3425aad15f5043c/emoji.json
|
|
5
|
-
* Regenerate: node scripts/generate-slack-emoji.mjs (from mastracode/factory)
|
|
6
|
-
*/
|
|
7
|
-
export declare const emojiByShortcode: Record<string, string>;
|
|
8
|
-
//# sourceMappingURL=emoji-shortcodes.generated.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"emoji-shortcodes.generated.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/emoji-shortcodes.generated.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAq7DnD,CAAC"}
|