@mastra/factory 0.12.0-alpha.9 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +35 -10
  2. package/dist/factory.d.ts +8 -0
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +4 -3
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/integrations/github/acceptance-labels.d.ts +17 -0
  9. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -0
  10. package/dist/integrations/github/acceptance-labels.js +55 -0
  11. package/dist/integrations/github/acceptance-labels.js.map +1 -0
  12. package/dist/integrations/github/integration.d.ts.map +1 -1
  13. package/dist/integrations/github/integration.js +47 -10
  14. package/dist/integrations/github/integration.js.map +1 -1
  15. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  16. package/dist/integrations/github/reconcile-worker.js +2 -2
  17. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  18. package/dist/integrations/github/sandbox.d.ts +10 -13
  19. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  20. package/dist/integrations/github/sandbox.js +74 -65
  21. package/dist/integrations/github/sandbox.js.map +1 -1
  22. package/dist/integrations/github/settle-or-abort.d.ts +7 -0
  23. package/dist/integrations/github/settle-or-abort.d.ts.map +1 -0
  24. package/dist/integrations/github/settle-or-abort.js +25 -0
  25. package/dist/integrations/github/settle-or-abort.js.map +1 -0
  26. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  27. package/dist/integrations/platform/github/event-worker.js +3 -3
  28. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  29. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  30. package/dist/integrations/platform/github/integration.js +37 -5
  31. package/dist/integrations/platform/github/integration.js.map +1 -1
  32. package/dist/packages/_internals/workspace/dist/index.js +35 -0
  33. package/dist/packages/_internals/workspace/dist/index.js.map +1 -0
  34. package/dist/routes/config.d.ts.map +1 -1
  35. package/dist/routes/config.js +6 -0
  36. package/dist/routes/config.js.map +1 -1
  37. package/dist/routes/oauth.d.ts +3 -0
  38. package/dist/routes/oauth.d.ts.map +1 -1
  39. package/dist/routes/oauth.js +10 -2
  40. package/dist/routes/oauth.js.map +1 -1
  41. package/dist/routes/om-seed.d.ts +22 -0
  42. package/dist/routes/om-seed.d.ts.map +1 -0
  43. package/dist/routes/om-seed.js +40 -0
  44. package/dist/routes/om-seed.js.map +1 -0
  45. package/dist/routes/surface.d.ts +1 -1
  46. package/dist/routes/surface.d.ts.map +1 -1
  47. package/dist/routes/surface.js +4 -1
  48. package/dist/routes/surface.js.map +1 -1
  49. package/dist/routes/work-items.d.ts.map +1 -1
  50. package/dist/routes/work-items.js +7 -0
  51. package/dist/routes/work-items.js.map +1 -1
  52. package/dist/rules/defaults.d.ts.map +1 -1
  53. package/dist/rules/defaults.js +3 -0
  54. package/dist/rules/defaults.js.map +1 -1
  55. package/dist/rules/dispatcher.d.ts.map +1 -1
  56. package/dist/rules/dispatcher.js +16 -1
  57. package/dist/rules/dispatcher.js.map +1 -1
  58. package/dist/rules/tools.d.ts.map +1 -1
  59. package/dist/rules/tools.js +1 -23
  60. package/dist/rules/tools.js.map +1 -1
  61. package/dist/rules/transition-service.d.ts +12 -1
  62. package/dist/rules/transition-service.d.ts.map +1 -1
  63. package/dist/rules/transition-service.js +28 -3
  64. package/dist/rules/transition-service.js.map +1 -1
  65. package/dist/sandbox/session-sandbox.d.ts +22 -8
  66. package/dist/sandbox/session-sandbox.d.ts.map +1 -1
  67. package/dist/sandbox/session-sandbox.js +36 -37
  68. package/dist/sandbox/session-sandbox.js.map +1 -1
  69. package/dist/session/factory-session.js.map +1 -1
  70. package/dist/session/memory-settings-hydration.d.ts +3 -3
  71. package/dist/session/memory-settings-hydration.js +3 -3
  72. package/dist/session/memory-settings-hydration.js.map +1 -1
  73. package/dist/session/org-seed.d.ts +5 -5
  74. package/dist/session/org-seed.js +2 -2
  75. package/dist/session/org-seed.js.map +1 -1
  76. package/dist/storage/domains/work-items/base.d.ts +8 -0
  77. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  78. package/dist/storage/domains/work-items/base.js +10 -1
  79. package/dist/storage/domains/work-items/base.js.map +1 -1
  80. package/dist/workspace.d.ts +8 -0
  81. package/dist/workspace.d.ts.map +1 -1
  82. package/dist/workspace.js +21 -6
  83. package/dist/workspace.js.map +1 -1
  84. package/package.json +11 -10
  85. package/dist/session/checkpoint-capture.d.ts +0 -18
  86. package/dist/session/checkpoint-capture.d.ts.map +0 -1
  87. package/dist/session/checkpoint-capture.js +0 -27
  88. package/dist/session/checkpoint-capture.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"work-items.js","names":["#resolveTenant","#resolveProject","#auditWorkItemPatch","#proposalRoute"],"sources":["../../src/routes/work-items.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for Factory work items (the kanban board).\n *\n * Registered alongside the other `/web/*` routes behind the host auth gate.\n * The board is org-wide: every route re-resolves the caller's `(orgId, userId)`\n * tenant and scopes reads/writes by `orgId`, so any org member sees and moves\n * the same cards while `created_by` / stage history record who acted.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport type {\n FactoryStartCoordinator,\n FactoryStartPreparedResult,\n FactoryStartRequest,\n} from '../rules/start-coordinator.js';\nimport { FactoryStartTransitionError } from '../rules/start-coordinator.js';\nimport { roleForStage } from '../rules/transition-service.js';\nimport type { FactoryTransitionRequest, FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRuleBoard } from '../rules/types.js';\nimport { FACTORY_RULE_BOARDS, isFactoryRuleStage } from '../rules/types.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport { thresholdsOrDefault } from '../storage/domains/queue-health/base.js';\nimport type {\n CreateWorkItemInput,\n ExternalWorkItemSource,\n FactoryDeferredDecisionRecord,\n FactoryDispatchStatus,\n UpdateWorkItemInput,\n WorkItemPriorState,\n WorkItemRow,\n WorkItemSessionInput,\n WorkItemStage,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport {\n FACTORY_PULL_REQUEST_RECONCILIATION_KEY,\n FACTORY_RULE_MATERIALIZATION_KEY,\n WorkItemRelationError,\n} from '../storage/domains/work-items/base.js';\nimport { computeFactoryMetrics, parseMetricsRange } from '../storage/domains/work-items/metrics.js';\nimport { buildAttentionRoutes, factoryDecisionType } from './attention.js';\nimport type { RouteDependencies } from './route.js';\nimport { Route } from './route.js';\n\nexport interface WorkItemRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Factory projects domain — validates the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Work-items domain backing the kanban board. */\n workItems: WorkItemsStorage;\n /** Comments domain — backs the mention attention provider. */\n comments: WorkItemCommentsStorage;\n /** Per-project queue-health threshold config. */\n queueHealth: QueueHealthStorage;\n /** Governed stage-transition service. Stage moves 503 when absent. */\n transitionService?: Pick<FactoryTransitionService, 'transition' | 'ruleSetVersion'>;\n /** Coordinator that binds a Factory run before dispatching its kickoff. */\n startCoordinator?: Pick<FactoryStartCoordinator, 'prepare'>;\n /** Materialized sessions, read to report which of the listed cards are being worked. */\n liveSessions: Pick<LiveSessions, 'isRunning'>;\n}\n\n/** The card as clients see it, without the dispatcher's internal bookkeeping. */\nfunction toWireWorkItem(item: WorkItemRow): WorkItemRow {\n if (\n !item.metadata ||\n (!(FACTORY_RULE_MATERIALIZATION_KEY in item.metadata) &&\n !(FACTORY_PULL_REQUEST_RECONCILIATION_KEY in item.metadata))\n ) {\n return item;\n }\n return { ...item, metadata: publicWorkItemMetadata(item.metadata) ?? {} };\n}\n\n/** Session ids of the listed cards whose agent run is in flight. */\nfunction runningSessionIds(items: WorkItemRow[], liveSessions: Pick<LiveSessions, 'isRunning'>): string[] {\n const running = new Set<string>();\n for (const item of items) {\n for (const { sessionId } of Object.values(item.sessions)) {\n if (liveSessions.isRunning(sessionId)) running.add(sessionId);\n }\n }\n return [...running];\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst MAX_STAGES = 16;\nconst MAX_STAGE_LENGTH = 64;\nconst MAX_METADATA_BYTES = 16 * 1024;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validStages(value: unknown): value is WorkItemStage[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.length <= MAX_STAGES &&\n value.every(\n stage => typeof stage === 'string' && stage.length <= MAX_STAGE_LENGTH && /^[a-z0-9][a-z0-9_-]*$/i.test(stage),\n ) &&\n new Set(value).size === value.length\n );\n}\n\nfunction validMetadata(value: unknown): value is Record<string, unknown> | null {\n if (value === null) return true;\n if (!isRecord(value)) return false;\n try {\n return JSON.stringify(value).length <= MAX_METADATA_BYTES;\n } catch {\n return false;\n }\n}\n\nfunction publicWorkItemMetadata(value: Record<string, unknown> | null): Record<string, unknown> | null {\n if (value === null) return null;\n const {\n [FACTORY_RULE_MATERIALIZATION_KEY]: _materialization,\n [FACTORY_PULL_REQUEST_RECONCILIATION_KEY]: _reconciliation,\n ...metadata\n } = value;\n return metadata;\n}\n\nfunction parseExternalSource(value: unknown): ExternalWorkItemSource | null | undefined {\n if (value === undefined || value === null) return value;\n if (!isRecord(value)) return undefined;\n const { integrationId, type, externalId, url } = value;\n if (typeof integrationId !== 'string' || integrationId.length === 0 || integrationId.length > 128) return undefined;\n if (typeof type !== 'string' || type.length === 0 || type.length > 128) return undefined;\n if (typeof externalId !== 'string' || externalId.length === 0 || externalId.length > 512) return undefined;\n if (url !== undefined && (typeof url !== 'string' || url.length > 2048)) return undefined;\n return { integrationId, type, externalId, ...(url !== undefined ? { url } : {}) };\n}\n\nfunction parseParentWorkItemId(value: unknown): string | null | undefined {\n if (value === null) return null;\n if (typeof value !== 'string' || !UUID_RE.test(value)) return undefined;\n return value;\n}\n\nfunction parseSessions(value: unknown): Record<string, WorkItemSessionInput> | undefined {\n if (!isRecord(value)) return undefined;\n const out: Record<string, WorkItemSessionInput> = {};\n for (const [role, session] of Object.entries(value)) {\n if (!role || role.length > 64 || !isRecord(session)) return undefined;\n const { sessionId, branch, threadId } = session;\n if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 512) return undefined;\n if (typeof branch !== 'string' || branch.length === 0 || branch.length > 512) return undefined;\n if (typeof threadId !== 'string' || threadId.length === 0 || threadId.length > 512) return undefined;\n out[role] = { sessionId, branch, threadId };\n }\n return out;\n}\n\n/** Validate an untrusted create body. Unknown keys are dropped. */\nexport function parseCreateWorkItem(body: unknown): CreateWorkItemInput | null {\n if (!isRecord(body)) return null;\n const { externalSource, title, stages, sessions, metadata } = body;\n if (typeof title !== 'string' || title.trim().length === 0 || title.length > 500) return null;\n\n const hasParentWorkItemId = 'parentWorkItemId' in body;\n const parentWorkItemId = hasParentWorkItemId ? parseParentWorkItemId(body.parentWorkItemId) : undefined;\n if (hasParentWorkItemId && parentWorkItemId === undefined) return null;\n const parsedSource = parseExternalSource(externalSource);\n if (externalSource !== undefined && parsedSource === undefined) return null;\n if (stages !== undefined && !validStages(stages)) return null;\n const parsedSessions = sessions === undefined ? undefined : parseSessions(sessions);\n if (sessions !== undefined && parsedSessions === undefined) return null;\n let parsedMetadata: Record<string, unknown> | null | undefined;\n if (metadata !== undefined) {\n if (!validMetadata(metadata)) return null;\n parsedMetadata = publicWorkItemMetadata(metadata);\n }\n\n return {\n title: title.trim(),\n ...(parsedSource !== undefined ? { externalSource: parsedSource } : {}),\n ...(hasParentWorkItemId ? { parentWorkItemId: parentWorkItemId ?? null } : {}),\n ...(stages !== undefined ? { stages } : {}),\n ...(parsedSessions !== undefined ? { sessions: parsedSessions } : {}),\n ...(parsedMetadata !== undefined ? { metadata: parsedMetadata } : {}),\n };\n}\n\n/** Validate an untrusted patch body. Unknown keys are dropped. */\nexport function parseUpdateWorkItem(body: unknown): UpdateWorkItemInput | null {\n if (!isRecord(body)) return null;\n const { title, stages, sessions, metadata } = body;\n const hasParentWorkItemId = 'parentWorkItemId' in body;\n if (\n title === undefined &&\n stages === undefined &&\n sessions === undefined &&\n metadata === undefined &&\n !hasParentWorkItemId\n )\n return null;\n const parentWorkItemId = hasParentWorkItemId ? parseParentWorkItemId(body.parentWorkItemId) : undefined;\n if (hasParentWorkItemId && parentWorkItemId === undefined) return null;\n if (title !== undefined && (typeof title !== 'string' || title.trim().length === 0 || title.length > 500))\n return null;\n if (stages !== undefined && !validStages(stages)) return null;\n const parsedSessions = sessions === undefined ? undefined : parseSessions(sessions);\n if (sessions !== undefined && parsedSessions === undefined) return null;\n let parsedMetadata: Record<string, unknown> | null | undefined;\n if (metadata !== undefined) {\n if (!validMetadata(metadata)) return null;\n parsedMetadata = publicWorkItemMetadata(metadata);\n }\n\n return {\n ...(hasParentWorkItemId ? { parentWorkItemId: parentWorkItemId ?? null } : {}),\n ...(title !== undefined ? { title: title.trim() } : {}),\n ...(stages !== undefined ? { stages } : {}),\n ...(parsedSessions !== undefined ? { sessions: parsedSessions } : {}),\n ...(parsedMetadata !== undefined ? { metadata: parsedMetadata } : {}),\n };\n}\n\nasync function readJson(c: Context): Promise<unknown | undefined> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\n/** Fields a PATCH touched, for the bounded `updated` event summary. */\nfunction patchedFields(patch: Record<string, unknown>): string[] {\n return Object.keys(patch).filter(key => patch[key] !== undefined);\n}\n\nfunction boundedText(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= max ? normalized : undefined;\n}\n\nfunction parseTransitionBody(\n body: unknown,\n): Omit<FactoryTransitionRequest, 'orgId' | 'factoryProjectId' | 'workItemId' | 'actor'> | null {\n if (!isRecord(body)) return null;\n const board = FACTORY_RULE_BOARDS.includes(body.board as FactoryRuleBoard)\n ? (body.board as FactoryRuleBoard)\n : undefined;\n const stage = isFactoryRuleStage(body.stage) ? body.stage : undefined;\n const requestId = boundedText(body.requestId, 256);\n const cause = boundedText(body.cause, 256);\n if (\n !board ||\n !stage ||\n !requestId ||\n !UUID_RE.test(requestId) ||\n !cause ||\n !Number.isInteger(body.expectedRevision) ||\n Number(body.expectedRevision) < 1\n ) {\n return null;\n }\n return {\n board,\n stage,\n expectedRevision: Number(body.expectedRevision),\n ingress: { type: 'human', identity: requestId },\n cause,\n };\n}\n\nfunction parseInvocation(value: unknown): FactoryStartRequest['invocation'] | undefined | null {\n if (value === undefined) return undefined;\n if (!isRecord(value)) return null;\n if (value.type === 'prompt') {\n const prompt = boundedText(value.prompt, 16_384);\n return prompt ? { type: 'prompt', prompt } : null;\n }\n if (value.type === 'skill') {\n const skillName = boundedText(value.skillName, 64);\n const args = typeof value.arguments === 'string' && value.arguments.length <= 16_384 ? value.arguments : undefined;\n return skillName && args !== undefined ? { type: 'skill', skillName, arguments: args } : null;\n }\n return null;\n}\n\nfunction parseStartBody(\n body: unknown,\n tenant: { orgId: string; userId: string },\n factoryProjectId: string,\n): FactoryStartRequest | null {\n if (!isRecord(body) || !isRecord(body.workItem)) return null;\n const input = parseCreateWorkItem(body.workItem.input);\n const sessionId = boundedText(body.sessionId, 256);\n const threadTitle = boundedText(body.threadTitle, 512);\n const kickoffKey = boundedText(body.kickoffKey, 256);\n const invocation = parseInvocation(body.invocation);\n const destinationStage = isFactoryRuleStage(body.destinationStage) ? body.destinationStage : undefined;\n const role = boundedText(body.workItem.role, 32);\n const id = body.workItem.id === undefined ? undefined : boundedText(body.workItem.id, 64);\n if (body.workItem.id !== undefined && (!id || !UUID_RE.test(id))) return null;\n if (\n !input ||\n !sessionId ||\n !UUID_RE.test(sessionId) ||\n !threadTitle ||\n !kickoffKey ||\n !UUID_RE.test(kickoffKey) ||\n invocation === null ||\n !destinationStage ||\n !role\n ) {\n return null;\n }\n const threadTags = isRecord(body.threadTags)\n ? Object.fromEntries(\n Object.entries(body.threadTags)\n .filter(\n (entry): entry is [string, string] =>\n boundedText(entry[0], 64) !== undefined && boundedText(entry[1], 256) !== undefined,\n )\n .map(([key, value]) => [key, value.trim()]),\n )\n : undefined;\n return {\n ...tenant,\n factoryProjectId,\n sessionId,\n threadTitle,\n threadTags,\n kickoffKey,\n preapprovePlans: body.preapprovePlans === true,\n invocation,\n destinationStage,\n workItem: { id, role, input },\n };\n}\n\nconst DECISION_STATUSES = new Set<FactoryDispatchStatus>([\n 'pending',\n 'proposed',\n 'dismissed',\n 'superseded',\n 'leased',\n 'retry',\n 'succeeded',\n 'failed',\n]);\nconst DEFAULT_DECISION_PAGE_SIZE = 25;\nconst MAX_DECISION_PAGE_SIZE = 50;\n\nfunction parseDecisionStatuses(raw: string | undefined): FactoryDispatchStatus[] | undefined {\n if (!raw) return undefined;\n const statuses = [...new Set(raw.split(',').map(status => status.trim()))].filter(\n (status): status is FactoryDispatchStatus => DECISION_STATUSES.has(status as FactoryDispatchStatus),\n );\n return statuses.length > 0 ? statuses : undefined;\n}\n\nfunction parseDecisionLimit(raw: string | undefined): number {\n const parsed = raw ? Number.parseInt(raw, 10) : DEFAULT_DECISION_PAGE_SIZE;\n if (!Number.isFinite(parsed)) return DEFAULT_DECISION_PAGE_SIZE;\n return Math.max(1, Math.min(MAX_DECISION_PAGE_SIZE, parsed));\n}\n\nfunction encodeDecisionCursor(decision: FactoryDeferredDecisionRecord): string {\n return Buffer.from(JSON.stringify([decision.createdAt.toISOString(), decision.id]), 'utf8').toString('base64url');\n}\n\nfunction parseDecisionCursor(raw: string | undefined): { createdAt: Date; id: string } | undefined {\n if (!raw) return undefined;\n try {\n const decoded = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8')) as unknown;\n if (\n !Array.isArray(decoded) ||\n decoded.length !== 2 ||\n typeof decoded[0] !== 'string' ||\n typeof decoded[1] !== 'string'\n ) {\n return undefined;\n }\n const createdAt = new Date(decoded[0]);\n if (Number.isNaN(createdAt.getTime()) || !UUID_RE.test(decoded[1])) return undefined;\n return { createdAt, id: decoded[1] };\n } catch {\n return undefined;\n }\n}\n\n/** A proposed transition names the seat its lane addresses, so the card can label what approving starts. */\nfunction summaryRole(decision: Record<string, unknown>): string | null {\n if (typeof decision.role === 'string') return decision.role.slice(0, 32);\n if (decision.type !== 'transition') return null;\n const board = decision.board;\n const stage = decision.stage;\n if ((board !== 'work' && board !== 'review') || !isFactoryRuleStage(stage)) return null;\n return roleForStage(board, stage);\n}\n\nfunction decisionSummary(decision: FactoryDeferredDecisionRecord) {\n return {\n id: decision.id,\n evaluationId: decision.evaluationId,\n workItemId: decision.workItemId,\n type: factoryDecisionType(decision),\n role: summaryRole(decision.decision),\n status: decision.status,\n attempts: decision.attempts,\n failureOccurrence: decision.failureOccurrence,\n failureCode: decision.failureCode,\n canRetry: factoryDispatchFailureMetadata(decision.failureCode).canRetry,\n lastError: decision.lastError?.slice(0, 512) ?? null,\n createdAt: decision.createdAt.toISOString(),\n updatedAt: decision.updatedAt.toISOString(),\n completedAt: decision.completedAt?.toISOString() ?? null,\n };\n}\n\nexport class WorkItemRoutes extends Route<WorkItemRoutesDeps> {\n /** Resolve the `(orgId, userId)` tenant or a ready-to-return error response. */\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'The Factory board requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n /**\n * Resolve the tenant AND the org-owned project from the `:id` param. Work\n * items hang off a project, so listing/creating requires the project to\n * exist in the caller's org.\n */\n async #resolveProject(\n c: Context,\n ): Promise<\n { orgId: string; userId: string; factoryProjectId: string; defaultModelId: string | null } | { response: Response }\n > {\n const tenant = await this.#resolveTenant(c);\n if ('response' in tenant) return tenant;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n const { projects } = this.deps;\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n return { ...tenant, factoryProjectId: projectId, defaultModelId: project.defaultModelId };\n }\n\n /**\n * Emit the audit events a successful work-item PATCH implies: always\n * `updated`, plus `stage_moved` when the stages actually changed and one\n * `run.started` per session role the patch introduced.\n */\n async #auditWorkItemPatch({\n context,\n item,\n previous,\n patch,\n }: {\n context: Context;\n item: WorkItemRow;\n previous: WorkItemPriorState;\n patch: Record<string, unknown>;\n }): Promise<void> {\n const { audit } = this.deps;\n const target = { type: 'work_item', id: item.id, name: item.title };\n await audit.emit({\n context,\n input: {\n action: 'factory.work_item.updated',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: { fields: patchedFields(patch) },\n },\n });\n\n const stagesChanged =\n patch.stages !== undefined &&\n (previous.stages.length !== item.stages.length || previous.stages.some((s, i) => s !== item.stages[i]));\n if (stagesChanged) {\n await audit.emit({\n context,\n input: {\n action: 'factory.work_item.stage_moved',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: { from: previous.stages, to: item.stages },\n },\n });\n }\n\n const newRoles = Object.keys(item.sessions).filter(role => !previous.sessionRoles.includes(role));\n for (const role of newRoles) {\n const session = item.sessions[role];\n await audit.emit({\n context,\n input: {\n action: 'factory.run.started',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: {\n role,\n branch: session?.branch,\n threadId: session?.threadId,\n sessionId: session?.sessionId,\n },\n },\n });\n }\n }\n\n /** Releasing a parked run and dropping it: same request, opposite outcomes, both audited as consent. */\n #proposalRoute({\n verb,\n settle,\n }: {\n verb: 'approve' | 'dismiss';\n settle: (\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n userId: string,\n ) => Promise<FactoryDeferredDecisionRecord | null>;\n }): ApiRoute {\n const { audit, workItems } = this.deps;\n return registerApiRoute(`/web/factory/projects/:id/decisions/:decisionId/${verb}`, {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const decisionId = context.req.param('decisionId');\n if (!decisionId || !UUID_RE.test(decisionId)) return c.json({ error: 'invalid_decision_id' }, 422);\n await workItems.ensureReady();\n const now = new Date();\n const decision = await settle(resolved.orgId, resolved.factoryProjectId, decisionId, now, resolved.userId);\n if (!decision) return c.json({ error: 'decision_not_proposed' }, 409);\n // Releasing a proposal is a person taking the item on. Approval arms the\n // item's autonomy inside the same storage transaction (see\n // approveDeferredDecision), so follow-up runs no longer wait for approval.\n await audit.emit({\n context,\n input: {\n action: verb === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n factoryProjectId: resolved.factoryProjectId,\n targets: decision.workItemId\n ? [{ type: 'work_item', id: decision.workItemId }]\n : [{ type: 'rule_decision', id: decision.id }],\n metadata: { decisionId: decision.id, effect: factoryDecisionType(decision) },\n },\n });\n return c.json({ decision: decisionSummary(decision) });\n },\n });\n }\n\n /** Build the Factory work-item routes as Mastra `apiRoutes`. */\n routes(): ApiRoute[] {\n const { audit, workItems, queueHealth, transitionService, startCoordinator, liveSessions } = this.deps;\n return [\n // ── List the org's work items for a project, and which are being worked ─\n registerApiRoute('/web/factory/projects/:id/work-items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n await workItems.ensureReady();\n const items = await workItems.list({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n return c.json({\n workItems: items.map(toWireWorkItem),\n runningSessionIds: runningSessionIds(items, liveSessions),\n });\n },\n }),\n\n // ── Flow metrics aggregated over the project's work items ───────────────\n registerApiRoute('/web/factory/projects/:id/metrics', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n const { windowStart, windowEnd } = parseMetricsRange(\n loose(c).req.query('from'),\n loose(c).req.query('to'),\n new Date(),\n );\n await workItems.ensureReady();\n const items = await workItems.list({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n return c.json({ metrics: computeFactoryMetrics(items, { windowStart, windowEnd }) });\n },\n }),\n\n // ── Per-project queue-health age-threshold config (seconds) ─────────────\n registerApiRoute('/web/factory/projects/:id/health/thresholds', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n await queueHealth.ensureReady();\n const stored = await queueHealth.getConfig(resolved.orgId, resolved.factoryProjectId);\n // Validate at the read choke point: `getConfig` round-trips a stored\n // JSONB row, and only `saveConfig` validates on write — a corrupted or\n // hand-edited row (empty / non-ascending) would otherwise flow to the\n // chart and invert bucket colors. Fall back to the default on invalid.\n return c.json({ thresholds: thresholdsOrDefault(stored) });\n },\n }),\n\n // ── Bounded durable rule-decision status ────────────────────────────────\n registerApiRoute('/web/factory/projects/:id/decisions', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n\n const cursorRaw = context.req.query('before');\n const before = parseDecisionCursor(cursorRaw);\n if (cursorRaw && !before) return c.json({ error: 'invalid_cursor' }, 400);\n await workItems.ensureReady();\n const page = await workItems.listDeferredDecisionPage({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n statuses: parseDecisionStatuses(context.req.query('statuses')),\n before,\n limit: parseDecisionLimit(context.req.query('limit')),\n });\n const last = page.decisions.at(-1);\n return c.json({\n decisions: page.decisions.map(decisionSummary),\n ...(page.hasMore && last ? { nextCursor: encodeDecisionCursor(last) } : {}),\n });\n },\n }),\n\n ...buildAttentionRoutes({\n workItems,\n comments: this.deps.comments,\n resolveProject: context => this.#resolveProject(loose(context)),\n }),\n\n this.#proposalRoute({ verb: 'approve', settle: workItems.approveDeferredDecision.bind(workItems) }),\n this.#proposalRoute({ verb: 'dismiss', settle: workItems.dismissDeferredDecision.bind(workItems) }),\n\n registerApiRoute('/web/factory/projects/:id/decisions/:decisionId/retry', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const decisionId = context.req.param('decisionId');\n if (!decisionId || !UUID_RE.test(decisionId)) return c.json({ error: 'invalid_decision_id' }, 422);\n await workItems.ensureReady();\n const current = await workItems.getDeferredDecision(resolved.orgId, resolved.factoryProjectId, decisionId);\n if (\n !current ||\n current.status !== 'failed' ||\n !factoryDispatchFailureMetadata(current.failureCode).canRetry\n ) {\n return c.json({ error: 'decision_not_retryable' }, 409);\n }\n const decision = await workItems.retryDeferredDecision(\n resolved.orgId,\n resolved.factoryProjectId,\n decisionId,\n new Date(),\n );\n if (!decision) return c.json({ error: 'decision_not_retryable' }, 409);\n return c.json({ decision: decisionSummary(decision) });\n },\n }),\n\n // ── Create (upsert on sourceKey) a work item ─────────────────────────────\n registerApiRoute('/web/factory/projects/:id/work-items', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n\n const body = await readJson(loose(c));\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const input = parseCreateWorkItem(body);\n if (!input) return c.json({ error: 'invalid_work_item' }, 400);\n if ((input.stages ?? ['intake']).length !== 1 || (input.stages ?? ['intake'])[0] !== 'intake') {\n return c.json(\n { error: 'governed_transition_required', message: 'New work items must enter through Factory intake.' },\n 409,\n );\n }\n\n await workItems.ensureReady();\n try {\n const result = await workItems.upsert({\n orgId: resolved.orgId,\n userId: resolved.userId,\n factoryProjectId: resolved.factoryProjectId,\n input,\n reuseMode: 'non-stage',\n });\n let item = result.item;\n if (result.created) {\n if (!transitionService) {\n await workItems.delete({ orgId: resolved.orgId, id: item.id });\n return c.json({ error: 'factory_transitions_unavailable' }, 503);\n }\n const entered = await transitionService.transition({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId: item.id,\n board: item.externalSource?.type === 'pull-request' ? 'review' : 'work',\n stage: 'intake',\n expectedRevision: item.revision,\n actor: { type: 'human', id: resolved.userId },\n ingress: { type: 'human', identity: `work-item:${item.id}:initial-entry` },\n cause: 'work_item_created',\n initialEntry: true,\n });\n if (entered.status === 'rejected') {\n await workItems.delete({ orgId: resolved.orgId, id: item.id });\n return c.json({ status: 'rejected', code: entered.code, reason: entered.reason }, 422);\n }\n item = (await workItems.getForProject(resolved.orgId, resolved.factoryProjectId, item.id)) ?? item;\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.work_item.created',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: item.id, name: item.title }],\n metadata: { externalSource: item.externalSource, stages: item.stages },\n },\n });\n } else {\n // Source-key reuse: the POST updated an existing card, so audit it\n // as an update (plus stage/run events) instead of a false creation.\n const { stages: _stages, sessions: _sessions, ...boundedPatch } = input;\n await this.#auditWorkItemPatch({\n context: loose(c),\n item,\n previous: result.previous,\n patch: boundedPatch as unknown as Record<string, unknown>,\n });\n }\n return c.json({ workItem: toWireWorkItem(item) });\n } catch (error) {\n if (error instanceof WorkItemRelationError) {\n return c.json({ error: error.code, message: error.message }, 400);\n }\n throw error;\n }\n },\n }),\n\n // ── Authoritative stage transition ──────────────────────────────────────\n registerApiRoute('/web/factory/projects/:id/work-items/:workItemId/transition', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n const workItemId = loose(c).req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n const parsed = parseTransitionBody(await readJson(loose(c)));\n if (!parsed) return c.json({ error: 'invalid_transition_request' }, 400);\n if (!transitionService) {\n return c.json({ error: 'factory_transition_unavailable' }, 503);\n }\n await workItems.ensureReady();\n const result = await transitionService.transition({\n ...parsed,\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId,\n actor: { type: 'human', id: resolved.userId },\n ingress: {\n ...parsed.ingress,\n identity: `human:${resolved.userId}:${parsed.ingress.identity}`,\n },\n });\n await audit.emit({\n context: loose(c),\n input: {\n action:\n result.status === 'accepted'\n ? 'factory.work_item.stage_moved'\n : 'factory.work_item.transition_rejected',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: workItemId }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: parsed.ingress.type,\n ruleSetVersion: transitionService.ruleSetVersion,\n ...(result.status === 'accepted'\n ? { to: result.stage, revision: result.revision }\n : { code: result.code, reason: result.reason }),\n },\n },\n });\n if (result.status === 'accepted') return c.json({ result });\n return c.json({ result }, result.code === 'stale' ? 409 : 422);\n },\n }),\n\n // ── Bind a Factory run before dispatching its kickoff ────────────────────\n registerApiRoute('/web/factory/projects/:id/runs/start', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n if (!startCoordinator) {\n return c.json({ error: 'factory_start_unavailable' }, 503);\n }\n const input = parseStartBody(await readJson(loose(c)), resolved, resolved.factoryProjectId);\n if (!input) return c.json({ error: 'invalid_factory_start' }, 400);\n input.requestContext = loose(c).get('requestContext');\n input.defaultModelId = resolved.defaultModelId ?? undefined;\n // This route is only reached by a person pressing a run action, so\n // reaching it is the commitment the approval gate is asking for.\n // Arming rides inside prepareRunStart's transaction so a crash can't\n // start the run while leaving its follow-up work waiting on approval.\n input.armAutonomy = true;\n if (\n !input.workItem.id &&\n ((input.workItem.input.stages ?? ['intake']).length !== 1 ||\n (input.workItem.input.stages ?? ['intake'])[0] !== 'intake')\n ) {\n return c.json(\n { error: 'governed_transition_required', message: 'Create the work item in Intake before starting it.' },\n 409,\n );\n }\n await workItems.ensureReady();\n let prepared: FactoryStartPreparedResult;\n try {\n prepared = await startCoordinator.prepare(input);\n } catch (error) {\n if (error instanceof FactoryStartTransitionError) {\n return c.json({ result: error.result }, error.result.code === 'stale' ? 409 : 422);\n }\n throw error;\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.run.started',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: prepared.workItemId }],\n metadata: {\n role: input.workItem.role,\n branch: prepared.branch,\n threadId: prepared.threadId,\n sessionId: prepared.sessionId,\n bindingId: prepared.bindingId,\n },\n },\n });\n return c.json({ prepared }, 202);\n },\n }),\n\n // ── Patch non-stage metadata / sessions / title ──────────────────────────\n registerApiRoute('/web/factory/work-items/:id', {\n method: 'PATCH',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const id = loose(c).req.param('id');\n if (!id || !UUID_RE.test(id)) return c.json({ error: 'Work item not found' }, 404);\n\n const body = await readJson(loose(c));\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const patch = parseUpdateWorkItem(body);\n if (!patch) return c.json({ error: 'invalid_work_item_patch' }, 400);\n if (patch.stages !== undefined) {\n return c.json(\n { error: 'governed_transition_required', message: 'Use the Factory transition endpoint to move stages.' },\n 409,\n );\n }\n\n await workItems.ensureReady();\n try {\n const updated = await workItems.update({ orgId: tenant.orgId, id, userId: tenant.userId, patch });\n if (!updated) return c.json({ error: 'Work item not found' }, 404);\n await this.#auditWorkItemPatch({\n context: loose(c),\n item: updated.item,\n previous: updated.previous,\n patch: patch as Record<string, unknown>,\n });\n return c.json({ workItem: toWireWorkItem(updated.item) });\n } catch (error) {\n if (error instanceof WorkItemRelationError) {\n return c.json({ error: error.code, message: error.message }, 400);\n }\n throw error;\n }\n },\n }),\n\n // ── Remove a work item ───────────────────────────────────────────────────\n registerApiRoute('/web/factory/work-items/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const id = loose(c).req.param('id');\n if (!id || !UUID_RE.test(id)) return c.json({ error: 'Work item not found' }, 404);\n\n await workItems.ensureReady();\n const deleted = await workItems.delete({ orgId: tenant.orgId, id });\n if (!deleted) return c.json({ error: 'Work item not found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.work_item.deleted',\n factoryProjectId: deleted.factoryProjectId,\n targets: [{ type: 'work_item', id: deleted.id, name: deleted.title }],\n },\n });\n return c.json({ ok: true });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAuEA,SAAS,eAAe,MAAgC;CACtD,IACE,CAAC,KAAK,YACL,EAAA,mCAAsC,KAAK,aAC1C,EAAA,sCAA6C,KAAK,WAEpD,OAAO;CAET,OAAO;EAAE,GAAG;EAAM,UAAU,uBAAuB,KAAK,QAAQ,KAAK,CAAC;CAAE;AAC1E;;AAGA,SAAS,kBAAkB,OAAsB,cAAyD;CACxG,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,EAAE,eAAe,OAAO,OAAO,KAAK,QAAQ,GACrD,IAAI,aAAa,UAAU,SAAS,GAAG,QAAQ,IAAI,SAAS;CAGhE,OAAO,CAAC,GAAG,OAAO;AACpB;AAEA,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;AAEA,MAAM,UAAU;AAEhB,MAAM,aAAa;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;MACd,IAAI,iBAAiB,uBACnB,OAAO,EAAE,KAAK;OAAE,OAAO,MAAM;OAAM,SAAS,MAAM;MAAQ,GAAG,GAAG;MAElE,MAAM;KACR;IACF;GACF,CAAC;GAGD,iBAAiB,+BAA+B;IAC9C,QAAQ;IACR,cAAc;IACd,SAAS,OAAM,MAAK;KAClB,MAAM,SAAS,MAAM,KAAKF,eAAe,MAAM,CAAC,CAAC;KACjD,IAAI,cAAc,QAAQ,OAAO,OAAO;KAExC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,MAAM,IAAI;KAClC,IAAI,CAAC,MAAM,CAAC,QAAQ,KAAK,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;KAEjF,MAAM,UAAU,YAAY;KAC5B,MAAM,UAAU,MAAM,UAAU,OAAO;MAAE,OAAO,OAAO;MAAO;KAAG,CAAC;KAClE,IAAI,CAAC,SAAS,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;KACjE,MAAM,MAAM,KAAK;MACf,SAAS,MAAM,CAAC;MAChB,OAAO;OACL,QAAQ;OACR,kBAAkB,QAAQ;OAC1B,SAAS,CAAC;QAAE,MAAM;QAAa,IAAI,QAAQ;QAAI,MAAM,QAAQ;OAAM,CAAC;MACtE;KACF,CAAC;KACD,OAAO,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC;IAC5B;GACF,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"work-items.js","names":["#resolveTenant","#resolveProject","#auditWorkItemPatch","#proposalRoute"],"sources":["../../src/routes/work-items.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for Factory work items (the kanban board).\n *\n * Registered alongside the other `/web/*` routes behind the host auth gate.\n * The board is org-wide: every route re-resolves the caller's `(orgId, userId)`\n * tenant and scopes reads/writes by `orgId`, so any org member sees and moves\n * the same cards while `created_by` / stage history record who acted.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { factoryDispatchFailureMetadata } from '../rules/dispatch-errors.js';\nimport type {\n FactoryStartCoordinator,\n FactoryStartPreparedResult,\n FactoryStartRequest,\n} from '../rules/start-coordinator.js';\nimport { FactoryStartTransitionError } from '../rules/start-coordinator.js';\nimport { roleForStage } from '../rules/transition-service.js';\nimport type { FactoryTransitionRequest, FactoryTransitionService } from '../rules/transition-service.js';\nimport type { FactoryRuleBoard, WorkItemSource } from '../rules/types.js';\nimport { FACTORY_RULE_BOARDS, isFactoryRuleStage } from '../rules/types.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { WorkItemCommentsStorage } from '../storage/domains/comments/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport { thresholdsOrDefault } from '../storage/domains/queue-health/base.js';\nimport type {\n CreateWorkItemInput,\n ExternalWorkItemSource,\n FactoryDeferredDecisionRecord,\n FactoryDispatchStatus,\n UpdateWorkItemInput,\n WorkItemPriorState,\n WorkItemRow,\n WorkItemSessionInput,\n WorkItemStage,\n WorkItemsStorage,\n} from '../storage/domains/work-items/base.js';\nimport {\n FACTORY_PULL_REQUEST_RECONCILIATION_KEY,\n FACTORY_RULE_MATERIALIZATION_KEY,\n WorkItemRelationError,\n} from '../storage/domains/work-items/base.js';\nimport { computeFactoryMetrics, parseMetricsRange } from '../storage/domains/work-items/metrics.js';\nimport { buildAttentionRoutes, factoryDecisionType } from './attention.js';\nimport type { RouteDependencies } from './route.js';\nimport { Route } from './route.js';\n\nexport interface WorkItemRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n /** Factory projects domain — validates the `:id` project belongs to the caller's org. */\n projects: FactoryProjectsStorage;\n /** Work-items domain backing the kanban board. */\n workItems: WorkItemsStorage;\n /** Comments domain — backs the mention attention provider. */\n comments: WorkItemCommentsStorage;\n /** Per-project queue-health threshold config. */\n queueHealth: QueueHealthStorage;\n /** Governed stage-transition service. Stage moves 503 when absent. */\n transitionService?: Pick<FactoryTransitionService, 'transition' | 'ruleSetVersion'>;\n /** Coordinator that binds a Factory run before dispatching its kickoff. */\n startCoordinator?: Pick<FactoryStartCoordinator, 'prepare'>;\n /** Materialized sessions, read to report which of the listed cards are being worked. */\n liveSessions: Pick<LiveSessions, 'isRunning'>;\n}\n\n/** The card as clients see it, without the dispatcher's internal bookkeeping. */\nfunction toWireWorkItem(item: WorkItemRow): WorkItemRow {\n if (\n !item.metadata ||\n (!(FACTORY_RULE_MATERIALIZATION_KEY in item.metadata) &&\n !(FACTORY_PULL_REQUEST_RECONCILIATION_KEY in item.metadata))\n ) {\n return item;\n }\n return { ...item, metadata: publicWorkItemMetadata(item.metadata) ?? {} };\n}\n\n/** Session ids of the listed cards whose agent run is in flight. */\nfunction runningSessionIds(items: WorkItemRow[], liveSessions: Pick<LiveSessions, 'isRunning'>): string[] {\n const running = new Set<string>();\n for (const item of items) {\n for (const { sessionId } of Object.values(item.sessions)) {\n if (liveSessions.isRunning(sessionId)) running.add(sessionId);\n }\n }\n return [...running];\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst MAX_STAGES = 16;\nconst MAX_STAGE_LENGTH = 64;\nconst MAX_METADATA_BYTES = 16 * 1024;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validStages(value: unknown): value is WorkItemStage[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.length <= MAX_STAGES &&\n value.every(\n stage => typeof stage === 'string' && stage.length <= MAX_STAGE_LENGTH && /^[a-z0-9][a-z0-9_-]*$/i.test(stage),\n ) &&\n new Set(value).size === value.length\n );\n}\n\nfunction validMetadata(value: unknown): value is Record<string, unknown> | null {\n if (value === null) return true;\n if (!isRecord(value)) return false;\n try {\n return JSON.stringify(value).length <= MAX_METADATA_BYTES;\n } catch {\n return false;\n }\n}\n\nfunction publicWorkItemMetadata(value: Record<string, unknown> | null): Record<string, unknown> | null {\n if (value === null) return null;\n const {\n [FACTORY_RULE_MATERIALIZATION_KEY]: _materialization,\n [FACTORY_PULL_REQUEST_RECONCILIATION_KEY]: _reconciliation,\n ...metadata\n } = value;\n return metadata;\n}\n\nfunction parseExternalSource(value: unknown): ExternalWorkItemSource | null | undefined {\n if (value === undefined || value === null) return value;\n if (!isRecord(value)) return undefined;\n const { integrationId, type, externalId, url } = value;\n if (typeof integrationId !== 'string' || integrationId.length === 0 || integrationId.length > 128) return undefined;\n if (typeof type !== 'string' || type.length === 0 || type.length > 128) return undefined;\n if (typeof externalId !== 'string' || externalId.length === 0 || externalId.length > 512) return undefined;\n if (url !== undefined && (typeof url !== 'string' || url.length > 2048)) return undefined;\n return { integrationId, type, externalId, ...(url !== undefined ? { url } : {}) };\n}\n\nfunction parseParentWorkItemId(value: unknown): string | null | undefined {\n if (value === null) return null;\n if (typeof value !== 'string' || !UUID_RE.test(value)) return undefined;\n return value;\n}\n\nfunction parseSessions(value: unknown): Record<string, WorkItemSessionInput> | undefined {\n if (!isRecord(value)) return undefined;\n const out: Record<string, WorkItemSessionInput> = {};\n for (const [role, session] of Object.entries(value)) {\n if (!role || role.length > 64 || !isRecord(session)) return undefined;\n const { sessionId, branch, threadId } = session;\n if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 512) return undefined;\n if (typeof branch !== 'string' || branch.length === 0 || branch.length > 512) return undefined;\n if (typeof threadId !== 'string' || threadId.length === 0 || threadId.length > 512) return undefined;\n out[role] = { sessionId, branch, threadId };\n }\n return out;\n}\n\n/** Validate an untrusted create body. Unknown keys are dropped. */\nexport function parseCreateWorkItem(body: unknown): CreateWorkItemInput | null {\n if (!isRecord(body)) return null;\n const { externalSource, title, stages, sessions, metadata } = body;\n if (typeof title !== 'string' || title.trim().length === 0 || title.length > 500) return null;\n\n const hasParentWorkItemId = 'parentWorkItemId' in body;\n const parentWorkItemId = hasParentWorkItemId ? parseParentWorkItemId(body.parentWorkItemId) : undefined;\n if (hasParentWorkItemId && parentWorkItemId === undefined) return null;\n const parsedSource = parseExternalSource(externalSource);\n if (externalSource !== undefined && parsedSource === undefined) return null;\n if (stages !== undefined && !validStages(stages)) return null;\n const parsedSessions = sessions === undefined ? undefined : parseSessions(sessions);\n if (sessions !== undefined && parsedSessions === undefined) return null;\n let parsedMetadata: Record<string, unknown> | null | undefined;\n if (metadata !== undefined) {\n if (!validMetadata(metadata)) return null;\n parsedMetadata = publicWorkItemMetadata(metadata);\n }\n\n return {\n title: title.trim(),\n ...(parsedSource !== undefined ? { externalSource: parsedSource } : {}),\n ...(hasParentWorkItemId ? { parentWorkItemId: parentWorkItemId ?? null } : {}),\n ...(stages !== undefined ? { stages } : {}),\n ...(parsedSessions !== undefined ? { sessions: parsedSessions } : {}),\n ...(parsedMetadata !== undefined ? { metadata: parsedMetadata } : {}),\n };\n}\n\n/** Validate an untrusted patch body. Unknown keys are dropped. */\nexport function parseUpdateWorkItem(body: unknown): UpdateWorkItemInput | null {\n if (!isRecord(body)) return null;\n const { title, stages, sessions, metadata } = body;\n const hasParentWorkItemId = 'parentWorkItemId' in body;\n if (\n title === undefined &&\n stages === undefined &&\n sessions === undefined &&\n metadata === undefined &&\n !hasParentWorkItemId\n )\n return null;\n const parentWorkItemId = hasParentWorkItemId ? parseParentWorkItemId(body.parentWorkItemId) : undefined;\n if (hasParentWorkItemId && parentWorkItemId === undefined) return null;\n if (title !== undefined && (typeof title !== 'string' || title.trim().length === 0 || title.length > 500))\n return null;\n if (stages !== undefined && !validStages(stages)) return null;\n const parsedSessions = sessions === undefined ? undefined : parseSessions(sessions);\n if (sessions !== undefined && parsedSessions === undefined) return null;\n let parsedMetadata: Record<string, unknown> | null | undefined;\n if (metadata !== undefined) {\n if (!validMetadata(metadata)) return null;\n parsedMetadata = publicWorkItemMetadata(metadata);\n }\n\n return {\n ...(hasParentWorkItemId ? { parentWorkItemId: parentWorkItemId ?? null } : {}),\n ...(title !== undefined ? { title: title.trim() } : {}),\n ...(stages !== undefined ? { stages } : {}),\n ...(parsedSessions !== undefined ? { sessions: parsedSessions } : {}),\n ...(parsedMetadata !== undefined ? { metadata: parsedMetadata } : {}),\n };\n}\n\nasync function readJson(c: Context): Promise<unknown | undefined> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\n/** Fields a PATCH touched, for the bounded `updated` event summary. */\nfunction patchedFields(patch: Record<string, unknown>): string[] {\n return Object.keys(patch).filter(key => patch[key] !== undefined);\n}\n\nfunction boundedText(value: unknown, max: number): string | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim();\n return normalized.length > 0 && normalized.length <= max ? normalized : undefined;\n}\n\nfunction parseTransitionBody(\n body: unknown,\n): Omit<FactoryTransitionRequest, 'orgId' | 'factoryProjectId' | 'workItemId' | 'actor'> | null {\n if (!isRecord(body)) return null;\n const board = FACTORY_RULE_BOARDS.includes(body.board as FactoryRuleBoard)\n ? (body.board as FactoryRuleBoard)\n : undefined;\n const stage = isFactoryRuleStage(body.stage) ? body.stage : undefined;\n const requestId = boundedText(body.requestId, 256);\n const cause = boundedText(body.cause, 256);\n if (\n !board ||\n !stage ||\n !requestId ||\n !UUID_RE.test(requestId) ||\n !cause ||\n !Number.isInteger(body.expectedRevision) ||\n Number(body.expectedRevision) < 1\n ) {\n return null;\n }\n return {\n board,\n stage,\n expectedRevision: Number(body.expectedRevision),\n ingress: { type: 'human', identity: requestId },\n cause,\n };\n}\n\nfunction parseInvocation(value: unknown): FactoryStartRequest['invocation'] | undefined | null {\n if (value === undefined) return undefined;\n if (!isRecord(value)) return null;\n if (value.type === 'prompt') {\n const prompt = boundedText(value.prompt, 16_384);\n return prompt ? { type: 'prompt', prompt } : null;\n }\n if (value.type === 'skill') {\n const skillName = boundedText(value.skillName, 64);\n const args = typeof value.arguments === 'string' && value.arguments.length <= 16_384 ? value.arguments : undefined;\n return skillName && args !== undefined ? { type: 'skill', skillName, arguments: args } : null;\n }\n return null;\n}\n\nfunction parseStartBody(\n body: unknown,\n tenant: { orgId: string; userId: string },\n factoryProjectId: string,\n): FactoryStartRequest | null {\n if (!isRecord(body) || !isRecord(body.workItem)) return null;\n const input = parseCreateWorkItem(body.workItem.input);\n const sessionId = boundedText(body.sessionId, 256);\n const threadTitle = boundedText(body.threadTitle, 512);\n const kickoffKey = boundedText(body.kickoffKey, 256);\n const invocation = parseInvocation(body.invocation);\n const destinationStage = isFactoryRuleStage(body.destinationStage) ? body.destinationStage : undefined;\n const role = boundedText(body.workItem.role, 32);\n const id = body.workItem.id === undefined ? undefined : boundedText(body.workItem.id, 64);\n if (body.workItem.id !== undefined && (!id || !UUID_RE.test(id))) return null;\n if (\n !input ||\n !sessionId ||\n !UUID_RE.test(sessionId) ||\n !threadTitle ||\n !kickoffKey ||\n !UUID_RE.test(kickoffKey) ||\n invocation === null ||\n !destinationStage ||\n !role\n ) {\n return null;\n }\n const threadTags = isRecord(body.threadTags)\n ? Object.fromEntries(\n Object.entries(body.threadTags)\n .filter(\n (entry): entry is [string, string] =>\n boundedText(entry[0], 64) !== undefined && boundedText(entry[1], 256) !== undefined,\n )\n .map(([key, value]) => [key, value.trim()]),\n )\n : undefined;\n return {\n ...tenant,\n factoryProjectId,\n sessionId,\n threadTitle,\n threadTags,\n kickoffKey,\n preapprovePlans: body.preapprovePlans === true,\n invocation,\n destinationStage,\n workItem: { id, role, input },\n };\n}\n\nconst DECISION_STATUSES = new Set<FactoryDispatchStatus>([\n 'pending',\n 'proposed',\n 'dismissed',\n 'superseded',\n 'leased',\n 'retry',\n 'succeeded',\n 'failed',\n]);\nconst DEFAULT_DECISION_PAGE_SIZE = 25;\nconst MAX_DECISION_PAGE_SIZE = 50;\n\nfunction parseDecisionStatuses(raw: string | undefined): FactoryDispatchStatus[] | undefined {\n if (!raw) return undefined;\n const statuses = [...new Set(raw.split(',').map(status => status.trim()))].filter(\n (status): status is FactoryDispatchStatus => DECISION_STATUSES.has(status as FactoryDispatchStatus),\n );\n return statuses.length > 0 ? statuses : undefined;\n}\n\nfunction parseDecisionLimit(raw: string | undefined): number {\n const parsed = raw ? Number.parseInt(raw, 10) : DEFAULT_DECISION_PAGE_SIZE;\n if (!Number.isFinite(parsed)) return DEFAULT_DECISION_PAGE_SIZE;\n return Math.max(1, Math.min(MAX_DECISION_PAGE_SIZE, parsed));\n}\n\nfunction encodeDecisionCursor(decision: FactoryDeferredDecisionRecord): string {\n return Buffer.from(JSON.stringify([decision.createdAt.toISOString(), decision.id]), 'utf8').toString('base64url');\n}\n\nfunction parseDecisionCursor(raw: string | undefined): { createdAt: Date; id: string } | undefined {\n if (!raw) return undefined;\n try {\n const decoded = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8')) as unknown;\n if (\n !Array.isArray(decoded) ||\n decoded.length !== 2 ||\n typeof decoded[0] !== 'string' ||\n typeof decoded[1] !== 'string'\n ) {\n return undefined;\n }\n const createdAt = new Date(decoded[0]);\n if (Number.isNaN(createdAt.getTime()) || !UUID_RE.test(decoded[1])) return undefined;\n return { createdAt, id: decoded[1] };\n } catch {\n return undefined;\n }\n}\n\n/** A proposed transition names the seat its lane addresses, so the card can label what approving starts. */\nfunction summaryRole(decision: Record<string, unknown>): string | null {\n if (typeof decision.role === 'string') return decision.role.slice(0, 32);\n if (decision.type !== 'transition') return null;\n const board = decision.board;\n const stage = decision.stage;\n if ((board !== 'work' && board !== 'review') || !isFactoryRuleStage(stage)) return null;\n return roleForStage(board, stage);\n}\n\n/** A linked-card decision names where the card is synced from, so the UI can say \"GitHub\" rather than \"a linked card\". */\nfunction summarySource(decision: Record<string, unknown>): WorkItemSource | null {\n if (decision.type !== 'upsertLinkedWorkItem') return null;\n const source = decision.source;\n return source === 'github-issue' || source === 'github-pr' || source === 'linear-issue' || source === 'manual'\n ? source\n : null;\n}\n\nfunction decisionSummary(decision: FactoryDeferredDecisionRecord) {\n return {\n id: decision.id,\n evaluationId: decision.evaluationId,\n workItemId: decision.workItemId,\n type: factoryDecisionType(decision),\n role: summaryRole(decision.decision),\n source: summarySource(decision.decision),\n status: decision.status,\n attempts: decision.attempts,\n failureOccurrence: decision.failureOccurrence,\n failureCode: decision.failureCode,\n canRetry: factoryDispatchFailureMetadata(decision.failureCode).canRetry,\n lastError: decision.lastError?.slice(0, 512) ?? null,\n createdAt: decision.createdAt.toISOString(),\n updatedAt: decision.updatedAt.toISOString(),\n completedAt: decision.completedAt?.toISOString() ?? null,\n };\n}\n\nexport class WorkItemRoutes extends Route<WorkItemRoutesDeps> {\n /** Resolve the `(orgId, userId)` tenant or a ready-to-return error response. */\n async #resolveTenant(c: Context): Promise<{ orgId: string; userId: string } | { response: Response }> {\n await this.deps.auth.ensureUser(c);\n const tenant = this.deps.auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n { error: 'organization_required', message: 'The Factory board requires an organization.' },\n 403,\n ),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n /**\n * Resolve the tenant AND the org-owned project from the `:id` param. Work\n * items hang off a project, so listing/creating requires the project to\n * exist in the caller's org.\n */\n async #resolveProject(\n c: Context,\n ): Promise<\n { orgId: string; userId: string; factoryProjectId: string; defaultModelId: string | null } | { response: Response }\n > {\n const tenant = await this.#resolveTenant(c);\n if ('response' in tenant) return tenant;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n const { projects } = this.deps;\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) {\n return { response: c.json({ error: 'Project not found' }, 404) };\n }\n return { ...tenant, factoryProjectId: projectId, defaultModelId: project.defaultModelId };\n }\n\n /**\n * Emit the audit events a successful work-item PATCH implies: always\n * `updated`, plus `stage_moved` when the stages actually changed and one\n * `run.started` per session role the patch introduced.\n */\n async #auditWorkItemPatch({\n context,\n item,\n previous,\n patch,\n }: {\n context: Context;\n item: WorkItemRow;\n previous: WorkItemPriorState;\n patch: Record<string, unknown>;\n }): Promise<void> {\n const { audit } = this.deps;\n const target = { type: 'work_item', id: item.id, name: item.title };\n await audit.emit({\n context,\n input: {\n action: 'factory.work_item.updated',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: { fields: patchedFields(patch) },\n },\n });\n\n const stagesChanged =\n patch.stages !== undefined &&\n (previous.stages.length !== item.stages.length || previous.stages.some((s, i) => s !== item.stages[i]));\n if (stagesChanged) {\n await audit.emit({\n context,\n input: {\n action: 'factory.work_item.stage_moved',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: { from: previous.stages, to: item.stages },\n },\n });\n }\n\n const newRoles = Object.keys(item.sessions).filter(role => !previous.sessionRoles.includes(role));\n for (const role of newRoles) {\n const session = item.sessions[role];\n await audit.emit({\n context,\n input: {\n action: 'factory.run.started',\n factoryProjectId: item.factoryProjectId,\n targets: [target],\n metadata: {\n role,\n branch: session?.branch,\n threadId: session?.threadId,\n sessionId: session?.sessionId,\n },\n },\n });\n }\n }\n\n /** Releasing a parked run and dropping it: same request, opposite outcomes, both audited as consent. */\n #proposalRoute({\n verb,\n settle,\n }: {\n verb: 'approve' | 'dismiss';\n settle: (\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n userId: string,\n ) => Promise<FactoryDeferredDecisionRecord | null>;\n }): ApiRoute {\n const { audit, workItems } = this.deps;\n return registerApiRoute(`/web/factory/projects/:id/decisions/:decisionId/${verb}`, {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const decisionId = context.req.param('decisionId');\n if (!decisionId || !UUID_RE.test(decisionId)) return c.json({ error: 'invalid_decision_id' }, 422);\n await workItems.ensureReady();\n const now = new Date();\n const decision = await settle(resolved.orgId, resolved.factoryProjectId, decisionId, now, resolved.userId);\n if (!decision) return c.json({ error: 'decision_not_proposed' }, 409);\n // Releasing a proposal is a person taking the item on. Approval arms the\n // item's autonomy inside the same storage transaction (see\n // approveDeferredDecision), so follow-up runs no longer wait for approval.\n await audit.emit({\n context,\n input: {\n action: verb === 'approve' ? 'factory.run.approved' : 'factory.run.dismissed',\n factoryProjectId: resolved.factoryProjectId,\n targets: decision.workItemId\n ? [{ type: 'work_item', id: decision.workItemId }]\n : [{ type: 'rule_decision', id: decision.id }],\n metadata: { decisionId: decision.id, effect: factoryDecisionType(decision) },\n },\n });\n return c.json({ decision: decisionSummary(decision) });\n },\n });\n }\n\n /** Build the Factory work-item routes as Mastra `apiRoutes`. */\n routes(): ApiRoute[] {\n const { audit, workItems, queueHealth, transitionService, startCoordinator, liveSessions } = this.deps;\n return [\n // ── List the org's work items for a project, and which are being worked ─\n registerApiRoute('/web/factory/projects/:id/work-items', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n await workItems.ensureReady();\n const items = await workItems.list({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n return c.json({\n workItems: items.map(toWireWorkItem),\n runningSessionIds: runningSessionIds(items, liveSessions),\n });\n },\n }),\n\n // ── Flow metrics aggregated over the project's work items ───────────────\n registerApiRoute('/web/factory/projects/:id/metrics', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n const { windowStart, windowEnd } = parseMetricsRange(\n loose(c).req.query('from'),\n loose(c).req.query('to'),\n new Date(),\n );\n await workItems.ensureReady();\n const items = await workItems.list({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n });\n return c.json({ metrics: computeFactoryMetrics(items, { windowStart, windowEnd }) });\n },\n }),\n\n // ── Per-project queue-health age-threshold config (seconds) ─────────────\n registerApiRoute('/web/factory/projects/:id/health/thresholds', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n await queueHealth.ensureReady();\n const stored = await queueHealth.getConfig(resolved.orgId, resolved.factoryProjectId);\n // Validate at the read choke point: `getConfig` round-trips a stored\n // JSONB row, and only `saveConfig` validates on write — a corrupted or\n // hand-edited row (empty / non-ascending) would otherwise flow to the\n // chart and invert bucket colors. Fall back to the default on invalid.\n return c.json({ thresholds: thresholdsOrDefault(stored) });\n },\n }),\n\n // ── Bounded durable rule-decision status ────────────────────────────────\n registerApiRoute('/web/factory/projects/:id/decisions', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n\n const cursorRaw = context.req.query('before');\n const before = parseDecisionCursor(cursorRaw);\n if (cursorRaw && !before) return c.json({ error: 'invalid_cursor' }, 400);\n await workItems.ensureReady();\n const page = await workItems.listDeferredDecisionPage({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n statuses: parseDecisionStatuses(context.req.query('statuses')),\n before,\n limit: parseDecisionLimit(context.req.query('limit')),\n });\n const last = page.decisions.at(-1);\n return c.json({\n decisions: page.decisions.map(decisionSummary),\n ...(page.hasMore && last ? { nextCursor: encodeDecisionCursor(last) } : {}),\n });\n },\n }),\n\n ...buildAttentionRoutes({\n workItems,\n comments: this.deps.comments,\n resolveProject: context => this.#resolveProject(loose(context)),\n }),\n\n this.#proposalRoute({ verb: 'approve', settle: workItems.approveDeferredDecision.bind(workItems) }),\n this.#proposalRoute({ verb: 'dismiss', settle: workItems.dismissDeferredDecision.bind(workItems) }),\n\n registerApiRoute('/web/factory/projects/:id/decisions/:decisionId/retry', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n const resolved = await this.#resolveProject(context);\n if ('response' in resolved) return resolved.response;\n const decisionId = context.req.param('decisionId');\n if (!decisionId || !UUID_RE.test(decisionId)) return c.json({ error: 'invalid_decision_id' }, 422);\n await workItems.ensureReady();\n const current = await workItems.getDeferredDecision(resolved.orgId, resolved.factoryProjectId, decisionId);\n if (\n !current ||\n current.status !== 'failed' ||\n !factoryDispatchFailureMetadata(current.failureCode).canRetry\n ) {\n return c.json({ error: 'decision_not_retryable' }, 409);\n }\n const decision = await workItems.retryDeferredDecision(\n resolved.orgId,\n resolved.factoryProjectId,\n decisionId,\n new Date(),\n );\n if (!decision) return c.json({ error: 'decision_not_retryable' }, 409);\n return c.json({ decision: decisionSummary(decision) });\n },\n }),\n\n // ── Create (upsert on sourceKey) a work item ─────────────────────────────\n registerApiRoute('/web/factory/projects/:id/work-items', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n\n const body = await readJson(loose(c));\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const input = parseCreateWorkItem(body);\n if (!input) return c.json({ error: 'invalid_work_item' }, 400);\n if ((input.stages ?? ['intake']).length !== 1 || (input.stages ?? ['intake'])[0] !== 'intake') {\n return c.json(\n { error: 'governed_transition_required', message: 'New work items must enter through Factory intake.' },\n 409,\n );\n }\n\n await workItems.ensureReady();\n try {\n const result = await workItems.upsert({\n orgId: resolved.orgId,\n userId: resolved.userId,\n factoryProjectId: resolved.factoryProjectId,\n input,\n reuseMode: 'non-stage',\n });\n let item = result.item;\n if (result.created) {\n if (!transitionService) {\n await workItems.delete({ orgId: resolved.orgId, id: item.id });\n return c.json({ error: 'factory_transitions_unavailable' }, 503);\n }\n const entered = await transitionService.transition({\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId: item.id,\n board: item.externalSource?.type === 'pull-request' ? 'review' : 'work',\n stage: 'intake',\n expectedRevision: item.revision,\n actor: { type: 'human', id: resolved.userId },\n ingress: { type: 'human', identity: `work-item:${item.id}:initial-entry` },\n cause: 'work_item_created',\n initialEntry: true,\n });\n if (entered.status === 'rejected') {\n await workItems.delete({ orgId: resolved.orgId, id: item.id });\n return c.json({ status: 'rejected', code: entered.code, reason: entered.reason }, 422);\n }\n item = (await workItems.getForProject(resolved.orgId, resolved.factoryProjectId, item.id)) ?? item;\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.work_item.created',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: item.id, name: item.title }],\n metadata: { externalSource: item.externalSource, stages: item.stages },\n },\n });\n } else {\n // Source-key reuse: the POST updated an existing card, so audit it\n // as an update (plus stage/run events) instead of a false creation.\n const { stages: _stages, sessions: _sessions, ...boundedPatch } = input;\n await this.#auditWorkItemPatch({\n context: loose(c),\n item,\n previous: result.previous,\n patch: boundedPatch as unknown as Record<string, unknown>,\n });\n }\n return c.json({ workItem: toWireWorkItem(item) });\n } catch (error) {\n if (error instanceof WorkItemRelationError) {\n return c.json({ error: error.code, message: error.message }, 400);\n }\n throw error;\n }\n },\n }),\n\n // ── Authoritative stage transition ──────────────────────────────────────\n registerApiRoute('/web/factory/projects/:id/work-items/:workItemId/transition', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n const workItemId = loose(c).req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n const parsed = parseTransitionBody(await readJson(loose(c)));\n if (!parsed) return c.json({ error: 'invalid_transition_request' }, 400);\n if (!transitionService) {\n return c.json({ error: 'factory_transition_unavailable' }, 503);\n }\n await workItems.ensureReady();\n const result = await transitionService.transition({\n ...parsed,\n orgId: resolved.orgId,\n factoryProjectId: resolved.factoryProjectId,\n workItemId,\n actor: { type: 'human', id: resolved.userId },\n ingress: {\n ...parsed.ingress,\n identity: `human:${resolved.userId}:${parsed.ingress.identity}`,\n },\n });\n await audit.emit({\n context: loose(c),\n input: {\n action:\n result.status === 'accepted'\n ? 'factory.work_item.stage_moved'\n : 'factory.work_item.transition_rejected',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: workItemId }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: parsed.ingress.type,\n ruleSetVersion: transitionService.ruleSetVersion,\n ...(result.status === 'accepted'\n ? { to: result.stage, revision: result.revision }\n : { code: result.code, reason: result.reason }),\n },\n },\n });\n if (result.status === 'accepted') return c.json({ result });\n return c.json({ result }, result.code === 'stale' ? 409 : 422);\n },\n }),\n\n // ── Bind a Factory run before dispatching its kickoff ────────────────────\n registerApiRoute('/web/factory/projects/:id/runs/start', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const resolved = await this.#resolveProject(loose(c));\n if ('response' in resolved) return resolved.response;\n if (!startCoordinator) {\n return c.json({ error: 'factory_start_unavailable' }, 503);\n }\n const input = parseStartBody(await readJson(loose(c)), resolved, resolved.factoryProjectId);\n if (!input) return c.json({ error: 'invalid_factory_start' }, 400);\n input.requestContext = loose(c).get('requestContext');\n input.defaultModelId = resolved.defaultModelId ?? undefined;\n // This route is only reached by a person pressing a run action, so\n // reaching it is the commitment the approval gate is asking for.\n // Arming rides inside prepareRunStart's transaction so a crash can't\n // start the run while leaving its follow-up work waiting on approval.\n input.armAutonomy = true;\n if (\n !input.workItem.id &&\n ((input.workItem.input.stages ?? ['intake']).length !== 1 ||\n (input.workItem.input.stages ?? ['intake'])[0] !== 'intake')\n ) {\n return c.json(\n { error: 'governed_transition_required', message: 'Create the work item in Intake before starting it.' },\n 409,\n );\n }\n await workItems.ensureReady();\n let prepared: FactoryStartPreparedResult;\n try {\n prepared = await startCoordinator.prepare(input);\n } catch (error) {\n if (error instanceof FactoryStartTransitionError) {\n return c.json({ result: error.result }, error.result.code === 'stale' ? 409 : 422);\n }\n throw error;\n }\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.run.started',\n factoryProjectId: resolved.factoryProjectId,\n targets: [{ type: 'work_item', id: prepared.workItemId }],\n metadata: {\n role: input.workItem.role,\n branch: prepared.branch,\n threadId: prepared.threadId,\n sessionId: prepared.sessionId,\n bindingId: prepared.bindingId,\n },\n },\n });\n return c.json({ prepared }, 202);\n },\n }),\n\n // ── Patch non-stage metadata / sessions / title ──────────────────────────\n registerApiRoute('/web/factory/work-items/:id', {\n method: 'PATCH',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const id = loose(c).req.param('id');\n if (!id || !UUID_RE.test(id)) return c.json({ error: 'Work item not found' }, 404);\n\n const body = await readJson(loose(c));\n if (body === undefined) return c.json({ error: 'Invalid JSON body' }, 400);\n const patch = parseUpdateWorkItem(body);\n if (!patch) return c.json({ error: 'invalid_work_item_patch' }, 400);\n if (patch.stages !== undefined) {\n return c.json(\n { error: 'governed_transition_required', message: 'Use the Factory transition endpoint to move stages.' },\n 409,\n );\n }\n\n await workItems.ensureReady();\n try {\n const updated = await workItems.update({ orgId: tenant.orgId, id, userId: tenant.userId, patch });\n if (!updated) return c.json({ error: 'Work item not found' }, 404);\n await this.#auditWorkItemPatch({\n context: loose(c),\n item: updated.item,\n previous: updated.previous,\n patch: patch as Record<string, unknown>,\n });\n return c.json({ workItem: toWireWorkItem(updated.item) });\n } catch (error) {\n if (error instanceof WorkItemRelationError) {\n return c.json({ error: error.code, message: error.message }, 400);\n }\n throw error;\n }\n },\n }),\n\n // ── Remove a work item ───────────────────────────────────────────────────\n registerApiRoute('/web/factory/work-items/:id', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n const tenant = await this.#resolveTenant(loose(c));\n if ('response' in tenant) return tenant.response;\n\n const id = loose(c).req.param('id');\n if (!id || !UUID_RE.test(id)) return c.json({ error: 'Work item not found' }, 404);\n\n await workItems.ensureReady();\n const deleted = await workItems.delete({ orgId: tenant.orgId, id });\n if (!deleted) return c.json({ error: 'Work item not found' }, 404);\n await audit.emit({\n context: loose(c),\n input: {\n action: 'factory.work_item.deleted',\n factoryProjectId: deleted.factoryProjectId,\n targets: [{ type: 'work_item', id: deleted.id, name: deleted.title }],\n },\n });\n return c.json({ ok: true });\n },\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAuEA,SAAS,eAAe,MAAgC;CACtD,IACE,CAAC,KAAK,YACL,EAAA,mCAAsC,KAAK,aAC1C,EAAA,sCAA6C,KAAK,WAEpD,OAAO;CAET,OAAO;EAAE,GAAG;EAAM,UAAU,uBAAuB,KAAK,QAAQ,KAAK,CAAC;CAAE;AAC1E;;AAGA,SAAS,kBAAkB,OAAsB,cAAyD;CACxG,MAAM,0BAAU,IAAI,IAAY;CAChC,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,EAAE,eAAe,OAAO,OAAO,KAAK,QAAQ,GACrD,IAAI,aAAa,UAAU,SAAS,GAAG,QAAQ,IAAI,SAAS;CAGhE,OAAO,CAAC,GAAG,OAAO;AACpB;AAEA,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;AAEA,MAAM,UAAU;AAEhB,MAAM,aAAa;AACnB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB,KAAK;AAEhC,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,YAAY,OAA0C;CAC7D,OACE,MAAM,QAAQ,KAAK,KACnB,MAAM,SAAS,KACf,MAAM,UAAU,cAChB,MAAM,OACJ,UAAS,OAAO,UAAU,YAAY,MAAM,UAAU,oBAAoB,yBAAyB,KAAK,KAAK,CAC/G,KACA,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM;AAElC;AAEA,SAAS,cAAc,OAAyD;CAC9E,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,IAAI;EACF,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,UAAU;CACzC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IAAI;KAClC,IAAI,CAAC,MAAM,CAAC,QAAQ,KAAK,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;KAEjF,MAAM,UAAU,YAAY;KAC5B,MAAM,UAAU,MAAM,UAAU,OAAO;MAAE,OAAO,OAAO;MAAO;KAAG,CAAC;KAClE,IAAI,CAAC,SAAS,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;KACjE,MAAM,MAAM,KAAK;MACf,SAAS,MAAM,CAAC;MAChB,OAAO;OACL,QAAQ;OACR,kBAAkB,QAAQ;OAC1B,SAAS,CAAC;QAAE,MAAM;QAAa,IAAI,QAAQ;QAAI,MAAM,QAAQ;OAAM,CAAC;MACtE;KACF,CAAC;KACD,OAAO,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC;IAC5B;GACF,CAAC;EACH;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/rules/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EASV,YAAY,EACZ,qBAAqB,EAMtB,MAAM,YAAY,CAAC;AAGpB,eAAO,MAAM,4BAA4B,uBAAuB,CAAC;AA8mBjE,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,qBAAqB,EAC3B,SAAS,GAAE,qBAA0B,GACpC,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAQ/B;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,qBAAqB,CAAA;CAAE,GAAG,YAAY,CAW/G;AAED,wBAAgB,mBAAmB,IAAI,YAAY,CAElD"}
1
+ {"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/rules/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EASV,YAAY,EACZ,qBAAqB,EAMtB,MAAM,YAAY,CAAC;AAGpB,eAAO,MAAM,4BAA4B,uBAAuB,CAAC;AAinBjE,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,qBAAqB,EAC3B,SAAS,GAAE,qBAA0B,GACpC,IAAI,CAAC,YAAY,EAAE,SAAS,CAAC,CAQ/B;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,qBAAqB,CAAA;CAAE,GAAG,YAAY,CAW/G;AAED,wBAAgB,mBAAmB,IAAI,YAAY,CAElD"}
@@ -141,6 +141,7 @@ function issueOpened(context) {
141
141
  metadata: {
142
142
  githubRepositoryId: context.repository.id,
143
143
  githubIssueNumber: context.issue.number,
144
+ ...context.issue.createdAt ? { sourceCreatedAt: context.issue.createdAt } : {},
144
145
  ...githubActorLogin(context) ? { author: githubActorLogin(context) } : {},
145
146
  authorTrusted: trustedGithubActor(context),
146
147
  autoStartCandidate: trustedGithubActor(context) && createdAfterFactory(context.issue.createdAt, context.factory.createdAt),
@@ -178,6 +179,7 @@ function pullRequestOpened(context) {
178
179
  metadata: {
179
180
  githubRepositoryId: context.repository.id,
180
181
  githubPullRequestNumber: context.pullRequest.number,
182
+ ...context.pullRequest.createdAt ? { sourceCreatedAt: context.pullRequest.createdAt } : {},
181
183
  factoryAuthored,
182
184
  authorTrusted: trustedGithubActor(context),
183
185
  autoStartCandidate,
@@ -302,6 +304,7 @@ function linearIssueObserved(context) {
302
304
  metadata: {
303
305
  linearIssueId: context.issue.id,
304
306
  identifier: context.issue.identifier,
307
+ sourceCreatedAt: context.issue.createdAt,
305
308
  linearState: context.issue.state,
306
309
  linearStateType: context.issue.stateType,
307
310
  linearPriority: context.issue.priorityLabel,
@@ -1 +1 @@
1
- {"version":3,"file":"defaults.js","names":[],"sources":["../../src/rules/defaults.ts"],"sourcesContent":["import type {\n FactoryBoardRuleLeaf,\n FactoryBoardRules,\n FactoryGithubRuleLeaf,\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryLinearEventName,\n FactoryLinearRuleContext,\n FactoryLinearRuleLeaf,\n FactoryRules,\n FactoryRulesOverrides,\n FactoryRuleSource,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryToolResultRuleContext,\n FactoryToolRuleLeaf,\n} from './types.js';\nimport { assertFactoryRules, FactoryRuleValidationError } from './validation.js';\n\nexport const DEFAULT_FACTORY_RULE_VERSION = 'factory-default-v1';\n\nfunction trustedGithubActor(context: Pick<FactoryStageRuleContext, 'actor'>): boolean {\n return context.actor.type === 'github' && context.actor.trusted;\n}\n\nfunction githubActorLogin(context: Pick<FactoryStageRuleContext, 'actor'>): string | undefined {\n return context.actor.type === 'github' ? context.actor.login : undefined;\n}\n\nfunction invokeIssueInvestigation(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: context.item.url ? `GitHub issue (${context.item.url})` : context.item.title,\n } as const;\n}\n\nfunction retriageGithubIssue(context: FactoryGithubRuleContext) {\n if (!context.item || context.item.source !== 'github-issue' || !context.item.url) return;\n if (context.actor.type === 'github' && context.actor.factoryAuthored) return;\n\n const reason =\n context.event === 'issueEdited'\n ? context.issueChange?.title && context.issueChange.body\n ? 'issue title and body edited'\n : context.issueChange?.title\n ? 'issue title edited'\n : 'issue body edited'\n : context.event === 'issueCommentDeleted'\n ? 'comment deleted'\n : context.event === 'issueCommentEdited'\n ? 'comment edited'\n : 'comment created';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: `Re-triage GitHub issue (${context.item.url}) after ${reason}.`,\n } as const;\n}\n\nfunction investigateTriagedLinearIssue(context: FactoryStageRuleContext) {\n const identifier = context.item.sourceKey?.startsWith('linear:')\n ? context.item.sourceKey.slice('linear:'.length)\n : context.item.title;\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage-linear`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: `Linear issue ${identifier}${context.item.url ? ` (${context.item.url})` : ''}`,\n } as const;\n}\n\nfunction planWorkItem(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-plan`,\n role: 'plan',\n skillName: 'factory-plan',\n arguments: context.item.url ? `Work item (${context.item.url})` : context.item.title,\n } as const;\n}\n\n// A GitHub login is alphanumeric with interior hyphens — no underscores, no\n// spaces. Checking the grammar rejects the placeholder the issue poller stamps\n// when the reporter's account is gone (`__unknown__`), which would otherwise\n// become a trailer crediting an account that does not exist.\nconst GITHUB_LOGIN = /^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;\n\n/**\n * The reporter earns a `Co-Authored-By` trailer on the work their report caused.\n * Only a GitHub issue qualifies: Linear stamps a display name and a manual card\n * stamps nothing, and neither resolves to the GitHub identity a trailer needs.\n * Factory's own reports are skipped — crediting ourselves is noise.\n */\nfunction reporterCoAuthor(context: FactoryStageRuleContext) {\n if (context.source !== 'issue') return undefined;\n const author = context.item.metadata?.author;\n if (typeof author !== 'string' || !author) return undefined;\n if (author.endsWith('[bot]') || !GITHUB_LOGIN.test(author)) return undefined;\n return author;\n}\n\n/**\n * Building carries a prompt rather than a skill. The approved plan is already\n * the specification, so there is nothing for a skill document to add, and the\n * handoff a skill would define is unnecessary here: Building ends by opening a\n * pull request, which arrives as its own event and raises the Review card.\n */\nfunction buildWorkItem(context: FactoryStageRuleContext) {\n const subject = context.item.url ? `the approved plan for ${context.item.url}` : 'the approved plan';\n const reporter = reporterCoAuthor(context);\n // The trailer needs the reporter's numeric id, which intake does not stamp, so\n // the agent resolves it from the same issue it is already reading.\n const credit = reporter\n ? ` The work was reported by @${reporter}: credit them on every commit with a ` +\n `\\`Co-Authored-By: ${reporter} <ID+${reporter}@users.noreply.github.com>\\` trailer, ` +\n `resolving ID with \\`gh api users/${reporter} --jq .id\\`.`\n : '';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:build`,\n role: 'work',\n prompt: `Implement ${subject}. Open a pull request when the work is ready for review.${credit}`,\n } as const;\n}\n\nfunction completeIssue(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-complete-issue`,\n role: 'triage',\n skillName: 'factory-complete-issue',\n arguments: context.item.url ? `GitHub issue (${context.item.url})` : context.item.title,\n } as const;\n}\n\nfunction reviewPullRequest(context: FactoryStageRuleContext) {\n // A re-entry into Review (from any post-intake stage) supersedes whichever\n // review pass previously ran on this card: cancel any in-flight run before\n // dispatching a fresh one so we don't burn tokens on the stale pass and race\n // two agents on the same card. Cancellation is safe when nothing is in flight.\n const supersedes = context.fromStage !== 'intake';\n // The re-review skill only applies when a prior review pass actually completed\n // (the card is returning from `done`). A cancelled first-time review that\n // re-enters Review from `review` itself still has no prior pass to reconcile —\n // it gets the regular factory-review skill.\n const priorReviewCompleted = context.fromStage === 'done';\n const skillName = priorReviewCompleted ? 'factory-rereview' : 'factory-review';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:${skillName}`,\n role: 'review',\n skillName,\n arguments: context.item.url ? `GitHub pull request (${context.item.url})` : context.item.title,\n ...(supersedes ? { cancelInFlight: true } : {}),\n } as const;\n}\n\n// Fires only on webhook materialization, so an item filed by hand or re-synced\n// from source never suggests its own run.\nfunction onArrival<Effect>(rule: (context: FactoryStageRuleContext) => Effect) {\n return (context: FactoryStageRuleContext): Effect | undefined => {\n if (context.cause !== 'linked_item_materialized') return;\n if (context.item.metadata?.autoStartCandidate !== true) return;\n return rule(context);\n };\n}\n\nfunction resultContent(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n const content = (value as { content?: unknown }).content;\n return typeof content === 'string' ? content : undefined;\n}\n\n// Interactive-session path only: factory-plan never calls submit_plan — it\n// advances planning → execute via factory_transition_work_item directly.\nfunction advanceApprovedPlan(context: FactoryToolResultRuleContext) {\n if (\n context.result.status !== 'success' ||\n context.board !== 'work' ||\n context.item.stages.length !== 1 ||\n context.item.stages[0] !== 'planning' ||\n context.actor.type !== 'agent' ||\n context.actor.role !== 'plan' ||\n !resultContent(context.result.value)?.startsWith('Plan approved.')\n ) {\n return;\n }\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:approved-plan`,\n board: 'work',\n stage: 'execute',\n } as const;\n}\n\nfunction createdAfterFactory(createdAt: string | undefined, factoryCreatedAt: string): boolean {\n if (!createdAt) return false;\n const sourceCreatedAt = Date.parse(createdAt);\n const projectCreatedAt = Date.parse(factoryCreatedAt);\n return Number.isFinite(sourceCreatedAt) && Number.isFinite(projectCreatedAt) && sourceCreatedAt > projectCreatedAt;\n}\n\nfunction issueOpened(context: FactoryGithubRuleContext) {\n if (!context.issue) return;\n // Everything arrives in Intake; arrival only stamps whether `onArrival` may\n // suggest this card's run without a person.\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-intake`,\n board: 'work',\n source: 'github-issue',\n sourceKey: `github-issue:${context.issue.number}`,\n title: context.issue.title,\n url: context.issue.url,\n stage: 'intake',\n metadata: {\n githubRepositoryId: context.repository.id,\n githubIssueNumber: context.issue.number,\n ...(githubActorLogin(context) ? { author: githubActorLogin(context) } : {}),\n authorTrusted: trustedGithubActor(context),\n autoStartCandidate:\n trustedGithubActor(context) && createdAfterFactory(context.issue.createdAt, context.factory.createdAt),\n assignees: context.issue.assignees ?? [],\n labels: context.issue.labels ?? [],\n },\n } as const;\n}\n\nfunction issueClosed(context: FactoryGithubRuleContext) {\n if (!context.item || context.item.source !== 'github-issue' || !context.issue) return;\n if (context.board !== 'work') return;\n // Already off the board: nothing to reconcile.\n if (context.item.stages.some(stage => stage === 'done' || stage === 'canceled')) return;\n // Issue closure is a repository fact, not third-party input — no actor trust\n // gate. `not_planned` (and `duplicate`) means abandoned, everything else is\n // completed work.\n const canceled = context.issue.stateReason === 'not_planned' || context.issue.stateReason === 'duplicate';\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: 'work',\n stage: canceled ? 'canceled' : 'done',\n message: {\n text:\n `GitHub issue #${context.issue.number} was closed` +\n `${context.issue.stateReason ? ` (${context.issue.stateReason})` : ''}; ` +\n `this Work card was moved to ${canceled ? 'Canceled' : 'Done'}.`,\n },\n } as const;\n}\n\nfunction pullRequestOpened(context: FactoryGithubRuleContext) {\n if (!context.pullRequest) return;\n // A GitHub App bot is never a collaborator, so Factory's own PRs score\n // untrusted; their authorship is the trust signal.\n const factoryAuthored = context.actor.type === 'github' && context.actor.factoryAuthored;\n const autoStartCandidate =\n (trustedGithubActor(context) || factoryAuthored) &&\n createdAfterFactory(context.pullRequest.createdAt, context.factory.createdAt);\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:pull-request-intake`,\n board: 'review',\n source: 'github-pr',\n sourceKey: `github-pr:${context.pullRequest.number}`,\n title: context.pullRequest.title,\n url: context.pullRequest.url,\n stage: 'intake',\n metadata: {\n githubRepositoryId: context.repository.id,\n githubPullRequestNumber: context.pullRequest.number,\n factoryAuthored,\n authorTrusted: trustedGithubActor(context),\n autoStartCandidate,\n state: context.pullRequest.state,\n draft: context.pullRequest.draft,\n merged: context.pullRequest.merged,\n assignees: context.pullRequest.assignees ?? [],\n requestedReviewers: context.pullRequest.requestedReviewers ?? [],\n labels: context.pullRequest.labels ?? [],\n headBranch: context.pullRequest.headBranch,\n baseBranch: context.pullRequest.baseBranch,\n ...(githubActorLogin(context) ? { author: githubActorLogin(context) } : {}),\n },\n } as const;\n}\n\nfunction pullRequestMerged(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest?.merged) return;\n if (context.board === 'review') {\n // The event is bound to the PR's own Review card: a merged PR is finished\n // review work, so always move the card to Done. The message only reaches\n // an active session (if any) — cards without one just move, instead of\n // failing retries against a binding that never existed.\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:pull-request-merged`,\n board: 'review',\n stage: 'done',\n message: {\n text:\n `Pull request #${context.pullRequest.number} merged; this Review card was moved to Done. ` +\n 'No further review is needed unless follow-up work was requested.',\n },\n } as const;\n }\n // Provenance bound the event to the originating Work item instead: remind\n // its agent to assess completion — never auto-complete the Work item.\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:assess-work-completion`,\n role: 'work',\n message:\n `Pull request #${context.pullRequest.number} merged. Assess whether the linked Work item is complete. ` +\n 'Do not mark it Done solely because this PR merged; use factory_transition_work_item only after verifying the work.',\n } as const;\n}\n\nfunction addressReviewFeedback(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || !context.review) return;\n // Only the Work item that authored the PR can act on the feedback. Provenance\n // binds the event there; a Review card seeing its own posted review must not\n // react to it (that would loop the reviewer against itself).\n if (context.board !== 'work') return;\n // A closed or merged pull request has no branch left to push fixes to.\n if (context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // `approved` needs no work, and `commented` (a review body with no verdict)\n // is how a reviewer leaves notes without blocking — only a verdict that asks\n // for changes should pull the author back in.\n if (context.review.state.toLowerCase() !== 'changes_requested') return;\n // The authoring thread is already subscribed to this PR (`gh pr create`\n // subscribes automatically), so it can read the individual line comments\n // from its own notification inbox — the message only has to wake it and\n // point at the review.\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-review-feedback`,\n role: 'work',\n priority: 'high',\n message:\n `Changes were requested on pull request #${context.pullRequest.number} (${context.review.url}). ` +\n 'Read the review comments on this PR, address the ones you agree with, and push the fixes to the PR branch. ' +\n 'Reply on GitHub to anything you are deliberately not changing, explaining why.',\n } as const;\n}\n\n/**\n * Detects the `factory-review` handoff verdict in a comment body.\n *\n * GitHub forbids an app from reviewing a pull request it authored, so on\n * Factory-authored PRs the review skill falls back to posting its verdict as a\n * plain comment. That comment is the only signal the authoring agent gets, so\n * it has to be readable back out. The skill's handoff contract puts the verdict\n * on the first line (`Verdict: request changes`), so only that line is\n * inspected — a verdict quoted later in the findings must not count.\n */\nfunction requestsChangesVerdict(body: string | undefined): boolean {\n const firstLine = body\n ?.split('\\n')\n .map(line => line.trim())\n .find(line => line.length > 0);\n if (!firstLine) return false;\n // Tolerate the markdown the skill wraps the line in (`**Verdict: ...**`).\n const normalized = firstLine\n .replaceAll(/[*_`#>\\s]+/g, ' ')\n .trim()\n .toLowerCase();\n // Match the verdict exactly so negated phrasings (\"Verdict: do not request\n // changes\") cannot wake the author.\n return /^verdict: ?(request changes|changes requested)$/.test(normalized);\n}\n\nfunction addressPullRequestComment(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || !context.issueComment) return;\n // Provenance binds the comment to the Work item that authored the PR — the\n // only session that can act on it. A Review card must not react to comments\n // on the PR it is reviewing.\n if (context.board !== 'work') return;\n if (context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // `factoryAuthored` is one bit for the whole Factory, so Factory's own\n // comments are indistinguishable between roles — waking on all of them would\n // let the Work agent's own progress comments wake itself in a loop. The one\n // exception is the review verdict the Review run had to post as a comment\n // because GitHub refused a self-review: that is the handoff, and it only ever\n // asks for changes once per review, so it cannot sustain a loop.\n if (\n context.actor.type === 'github' &&\n context.actor.factoryAuthored &&\n !requestsChangesVerdict(context.issueComment.body)\n ) {\n return;\n }\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-pull-request-comment`,\n role: 'work',\n priority: 'high',\n message:\n `${context.issueComment.author ?? 'Someone'} commented on pull request #${context.pullRequest.number} ` +\n `(${context.issueComment.url ?? context.pullRequest.url}). Read the comment, address it if you agree, and push ` +\n 'the fixes to the PR branch. Reply on GitHub to anything you are deliberately not changing, explaining why.',\n } as const;\n}\n\nfunction pullRequestClosed(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || context.pullRequest.merged) return;\n if (context.board !== 'review') return;\n // A PR closed without merging is abandoned review work: clear the card off\n // the board instead of leaving it in Reviewing forever.\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:pull-request-closed`,\n board: 'review',\n stage: 'canceled',\n message: {\n text:\n `Pull request #${context.pullRequest.number} was closed without merging; ` +\n 'this Review card was moved to Canceled.',\n },\n } as const;\n}\n\nfunction reReviewRequestedPullRequest(context: FactoryGithubRuleContext) {\n // Only a review re-requested *from Factory's own bot* restarts the review —\n // requesting a human reviewer is not Factory's signal.\n if (!context.item || context.board !== 'review' || !context.reviewRequest?.factoryReviewer) return;\n if (!context.pullRequest || context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // Trusted (write/admin) requesters only: re-entering review checks out and\n // executes PR code, the same bar pullRequestOpened applies to auto-review.\n if (!trustedGithubActor(context)) return;\n if (context.actor.type === 'github' && context.actor.factoryAuthored) return;\n // Already in Reviewing: a review pass is pending or running; re-entering\n // would be a same-stage no-op anyway (stage rules only fire on change).\n if (context.item.stages.length === 1 && context.item.stages[0] === 'review') return;\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-requested`,\n board: 'review',\n stage: 'review',\n } as const;\n}\n\nfunction reReviewUpdatedPullRequest(context: FactoryGithubRuleContext) {\n if (!context.item || context.board !== 'review') return;\n if (!context.pullRequest || context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // Intake has not started a review pass yet, so a push there is just more of\n // the code the first pass will read. A push to a card sitting in Reviewing is\n // different: it invalidates whatever that pass is reading, so re-enter the\n // stage to supersede it. `reviewPullRequest` cancels the stale run and picks\n // the right skill for the entry it sees.\n if (context.item.stages.some(stage => stage === 'intake')) return;\n const alreadyReviewing = context.item.stages.some(stage => stage === 'review');\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-updated`,\n board: 'review',\n stage: 'review',\n // Re-entry is the point when the card is already Reviewing: the stage's\n // entry rule is what cancels the superseded pass and starts one on the code\n // that just landed.\n ...(alreadyReviewing ? { reenter: true } : {}),\n } as const;\n}\n\nfunction linearIssueObserved(context: FactoryLinearRuleContext) {\n if (context.item) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-triage`,\n board: 'work',\n source: 'linear-issue',\n sourceKey: `linear:${context.issue.identifier}`,\n title: `${context.issue.identifier}: ${context.issue.title}`,\n url: context.issue.url,\n stage: 'triage',\n metadata: {\n linearIssueId: context.issue.id,\n identifier: context.issue.identifier,\n linearState: context.issue.state,\n linearStateType: context.issue.stateType,\n linearPriority: context.issue.priorityLabel,\n linearAssignee: context.issue.assignee,\n linearCreator: context.issue.creator,\n linearTeam: context.issue.team,\n labels: [...context.issue.labels] as string[],\n ...(context.issue.assignee ? { assignee: context.issue.assignee } : {}),\n ...(context.issue.creator ? { creator: context.issue.creator, author: context.issue.creator } : {}),\n },\n } as const;\n}\n\nfunction linearIssueClosed(context: FactoryLinearRuleContext) {\n if (!context.item || context.item.source !== 'linear-issue') return;\n if (context.board !== 'work') return;\n // Already off the board: nothing to reconcile.\n if (context.item.stages.some(stage => stage === 'done' || stage === 'canceled')) return;\n // Only terminal state types trigger close.\n const stateType = context.issue.stateType;\n if (stateType !== 'completed' && stateType !== 'canceled') return;\n const canceled = stateType === 'canceled';\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: 'work',\n stage: canceled ? 'canceled' : 'done',\n message: {\n text: `Linear issue ${context.issue.identifier} was ${canceled ? 'canceled' : 'completed'}; this Work card was moved to ${canceled ? 'Canceled' : 'Done'}.`,\n },\n } as const;\n}\n\nconst BUILT_IN_DEFAULTS: FactoryRulesOverrides = {\n work: {\n intake: { issue: { onEnter: onArrival(invokeIssueInvestigation) } },\n triage: {\n issue: { onEnter: invokeIssueInvestigation },\n linearIssue: { onEnter: investigateTriagedLinearIssue },\n },\n planning: {\n issue: { onEnter: planWorkItem },\n linearIssue: { onEnter: planWorkItem },\n manual: { onEnter: planWorkItem },\n },\n execute: {\n issue: { onEnter: buildWorkItem },\n linearIssue: { onEnter: buildWorkItem },\n manual: { onEnter: buildWorkItem },\n },\n done: {\n issue: { onEnter: completeIssue },\n },\n },\n review: {\n intake: { pullRequest: { onEnter: onArrival(reviewPullRequest) } },\n review: { pullRequest: { onEnter: reviewPullRequest } },\n },\n tools: { submit_plan: { onResult: advanceApprovedPlan } },\n github: {\n issueOpened: { onEvent: issueOpened },\n issueEdited: { onEvent: retriageGithubIssue },\n issueClosed: { onEvent: issueClosed },\n issueCommentCreated: { onEvent: retriageGithubIssue },\n issueCommentEdited: { onEvent: retriageGithubIssue },\n issueCommentDeleted: { onEvent: retriageGithubIssue },\n pullRequestOpened: { onEvent: pullRequestOpened },\n pullRequestUpdated: { onEvent: reReviewUpdatedPullRequest },\n pullRequestCommentCreated: { onEvent: addressPullRequestComment },\n pullRequestReviewRequested: { onEvent: reReviewRequestedPullRequest },\n pullRequestReviewSubmitted: { onEvent: addressReviewFeedback },\n pullRequestMerged: { onEvent: pullRequestMerged },\n pullRequestClosed: { onEvent: pullRequestClosed },\n },\n linear: { issueObserved: { onEvent: linearIssueObserved }, issueClosed: { onEvent: linearIssueClosed } },\n};\n\nfunction mergeBoardRules(\n base: FactoryBoardRules | undefined,\n overrides: FactoryBoardRules | undefined,\n): FactoryBoardRules {\n const result: FactoryBoardRules = {};\n const stages = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryRuleStage>;\n for (const stage of stages) {\n const baseSources = base?.[stage];\n const overrideSources = overrides?.[stage];\n const sources = new Set([\n ...Object.keys(baseSources ?? {}),\n ...Object.keys(overrideSources ?? {}),\n ]) as Set<FactoryRuleSource>;\n const mergedSources: Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>> = {};\n for (const source of sources) {\n const baseLeaf = baseSources?.[source];\n const overrideLeaf = overrideSources?.[source];\n mergedSources[source] = {\n ...(baseLeaf && 'onEnter' in baseLeaf ? { onEnter: baseLeaf.onEnter } : {}),\n ...(baseLeaf && 'onExit' in baseLeaf ? { onExit: baseLeaf.onExit } : {}),\n ...(overrideLeaf && 'onEnter' in overrideLeaf ? { onEnter: overrideLeaf.onEnter } : {}),\n ...(overrideLeaf && 'onExit' in overrideLeaf ? { onExit: overrideLeaf.onExit } : {}),\n };\n }\n result[stage] = mergedSources;\n }\n return result;\n}\n\nfunction mergeToolRules(\n base: Record<string, FactoryToolRuleLeaf> | undefined,\n overrides: Record<string, FactoryToolRuleLeaf> | undefined,\n): Record<string, FactoryToolRuleLeaf> {\n const result: Record<string, FactoryToolRuleLeaf> = {};\n for (const name of new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})])) {\n const baseLeaf = base?.[name];\n const overrideLeaf = overrides?.[name];\n result[name] = {\n ...(baseLeaf && 'onResult' in baseLeaf ? { onResult: baseLeaf.onResult } : {}),\n ...(overrideLeaf && 'onResult' in overrideLeaf ? { onResult: overrideLeaf.onResult } : {}),\n };\n }\n return result;\n}\n\nfunction mergeGithubRules(\n base: FactoryRulesOverrides['github'],\n overrides: FactoryRulesOverrides['github'],\n): NonNullable<FactoryRulesOverrides['github']> {\n const result: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>> = {};\n const events = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryGithubEventName>;\n for (const event of events) {\n const baseLeaf = base?.[event];\n const overrideLeaf = overrides?.[event];\n result[event] = {\n ...(baseLeaf && 'onEvent' in baseLeaf ? { onEvent: baseLeaf.onEvent } : {}),\n ...(overrideLeaf && 'onEvent' in overrideLeaf ? { onEvent: overrideLeaf.onEvent } : {}),\n };\n }\n return result;\n}\n\nfunction mergeLinearRules(\n base: FactoryRulesOverrides['linear'],\n overrides: FactoryRulesOverrides['linear'],\n): NonNullable<FactoryRulesOverrides['linear']> {\n const result: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>> = {};\n const events = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryLinearEventName>;\n for (const event of events) {\n const baseLeaf = base?.[event];\n const overrideLeaf = overrides?.[event];\n result[event] = {\n ...(baseLeaf && 'onEvent' in baseLeaf ? { onEvent: baseLeaf.onEvent } : {}),\n ...(overrideLeaf && 'onEvent' in overrideLeaf ? { onEvent: overrideLeaf.onEvent } : {}),\n };\n }\n return result;\n}\n\nexport function mergeFactoryRuleOverrides(\n base: FactoryRulesOverrides,\n overrides: FactoryRulesOverrides = {},\n): Omit<FactoryRules, 'version'> {\n return {\n work: mergeBoardRules(base.work, overrides.work),\n review: mergeBoardRules(base.review, overrides.review),\n tools: mergeToolRules(base.tools, overrides.tools),\n github: mergeGithubRules(base.github, overrides.github),\n linear: mergeLinearRules(base.linear, overrides.linear),\n };\n}\n\nexport function defaultFactoryRules(input: { version: string; overrides?: FactoryRulesOverrides }): FactoryRules {\n if (typeof input?.version !== 'string' || input.version.trim().length === 0) {\n throw new FactoryRuleValidationError('Factory rule version is required.');\n }\n\n const rules: FactoryRules = {\n version: input.version.trim(),\n ...mergeFactoryRuleOverrides(BUILT_IN_DEFAULTS, input.overrides),\n };\n assertFactoryRules(rules);\n return rules;\n}\n\nexport function builtInFactoryRules(): FactoryRules {\n return defaultFactoryRules({ version: DEFAULT_FACTORY_RULE_VERSION });\n}\n"],"mappings":";;AAmBA,MAAa,+BAA+B;AAE5C,SAAS,mBAAmB,SAA0D;CACpF,OAAO,QAAQ,MAAM,SAAS,YAAY,QAAQ,MAAM;AAC1D;AAEA,SAAS,iBAAiB,SAAqE;CAC7F,OAAO,QAAQ,MAAM,SAAS,WAAW,QAAQ,MAAM,QAAQ,KAAA;AACjE;AAEA,SAAS,yBAAyB,SAAkC;CAClE,OAAO;EACL,MAAM;EACN,gBAAgB,GAAG,QAAQ,QAAQ,GAAG;EACtC,MAAM;EACN,WAAW;EACX,WAAW,QAAQ,KAAK,MAAM,iBAAiB,QAAQ,KAAK,IAAI,KAAK,QAAQ,KAAK;CACpF;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,IAAI,CAAC,QAAQ,QAAQ,QAAQ,KAAK,WAAW,kBAAkB,CAAC,QAAQ,KAAK,KAA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SAAgB,0BACd,MACA,YAAmC,CAAC,GACL;CAC/B,OAAO;EACL,MAAM,gBAAgB,KAAK,MAAM,UAAU,IAAI;EAC/C,QAAQ,gBAAgB,KAAK,QAAQ,UAAU,MAAM;EACrD,OAAO,eAAe,KAAK,OAAO,UAAU,KAAK;EACjD,QAAQ,iBAAiB,KAAK,QAAQ,UAAU,MAAM;EACtD,QAAQ,iBAAiB,KAAK,QAAQ,UAAU,MAAM;CACxD;AACF;AAEA,SAAgB,oBAAoB,OAA6E;CAC/G,IAAI,OAAO,OAAO,YAAY,YAAY,MAAM,QAAQ,KAAK,CAAC,CAAC,WAAW,GACxE,MAAM,IAAI,2BAA2B,mCAAmC;CAG1E,MAAM,QAAsB;EAC1B,SAAS,MAAM,QAAQ,KAAK;EAC5B,GAAG,0BAA0B,mBAAmB,MAAM,SAAS;CACjE;CACA,mBAAmB,KAAK;CACxB,OAAO;AACT;AAEA,SAAgB,sBAAoC;CAClD,OAAO,oBAAoB,EAAE,SAAS,6BAA6B,CAAC;AACtE"}
1
+ {"version":3,"file":"defaults.js","names":[],"sources":["../../src/rules/defaults.ts"],"sourcesContent":["import type {\n FactoryBoardRuleLeaf,\n FactoryBoardRules,\n FactoryGithubRuleLeaf,\n FactoryGithubEventName,\n FactoryGithubRuleContext,\n FactoryLinearEventName,\n FactoryLinearRuleContext,\n FactoryLinearRuleLeaf,\n FactoryRules,\n FactoryRulesOverrides,\n FactoryRuleSource,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryToolResultRuleContext,\n FactoryToolRuleLeaf,\n} from './types.js';\nimport { assertFactoryRules, FactoryRuleValidationError } from './validation.js';\n\nexport const DEFAULT_FACTORY_RULE_VERSION = 'factory-default-v1';\n\nfunction trustedGithubActor(context: Pick<FactoryStageRuleContext, 'actor'>): boolean {\n return context.actor.type === 'github' && context.actor.trusted;\n}\n\nfunction githubActorLogin(context: Pick<FactoryStageRuleContext, 'actor'>): string | undefined {\n return context.actor.type === 'github' ? context.actor.login : undefined;\n}\n\nfunction invokeIssueInvestigation(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: context.item.url ? `GitHub issue (${context.item.url})` : context.item.title,\n } as const;\n}\n\nfunction retriageGithubIssue(context: FactoryGithubRuleContext) {\n if (!context.item || context.item.source !== 'github-issue' || !context.item.url) return;\n if (context.actor.type === 'github' && context.actor.factoryAuthored) return;\n\n const reason =\n context.event === 'issueEdited'\n ? context.issueChange?.title && context.issueChange.body\n ? 'issue title and body edited'\n : context.issueChange?.title\n ? 'issue title edited'\n : 'issue body edited'\n : context.event === 'issueCommentDeleted'\n ? 'comment deleted'\n : context.event === 'issueCommentEdited'\n ? 'comment edited'\n : 'comment created';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: `Re-triage GitHub issue (${context.item.url}) after ${reason}.`,\n } as const;\n}\n\nfunction investigateTriagedLinearIssue(context: FactoryStageRuleContext) {\n const identifier = context.item.sourceKey?.startsWith('linear:')\n ? context.item.sourceKey.slice('linear:'.length)\n : context.item.title;\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-triage-linear`,\n role: 'triage',\n skillName: 'factory-triage',\n arguments: `Linear issue ${identifier}${context.item.url ? ` (${context.item.url})` : ''}`,\n } as const;\n}\n\nfunction planWorkItem(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-plan`,\n role: 'plan',\n skillName: 'factory-plan',\n arguments: context.item.url ? `Work item (${context.item.url})` : context.item.title,\n } as const;\n}\n\n// A GitHub login is alphanumeric with interior hyphens — no underscores, no\n// spaces. Checking the grammar rejects the placeholder the issue poller stamps\n// when the reporter's account is gone (`__unknown__`), which would otherwise\n// become a trailer crediting an account that does not exist.\nconst GITHUB_LOGIN = /^[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/;\n\n/**\n * The reporter earns a `Co-Authored-By` trailer on the work their report caused.\n * Only a GitHub issue qualifies: Linear stamps a display name and a manual card\n * stamps nothing, and neither resolves to the GitHub identity a trailer needs.\n * Factory's own reports are skipped — crediting ourselves is noise.\n */\nfunction reporterCoAuthor(context: FactoryStageRuleContext) {\n if (context.source !== 'issue') return undefined;\n const author = context.item.metadata?.author;\n if (typeof author !== 'string' || !author) return undefined;\n if (author.endsWith('[bot]') || !GITHUB_LOGIN.test(author)) return undefined;\n return author;\n}\n\n/**\n * Building carries a prompt rather than a skill. The approved plan is already\n * the specification, so there is nothing for a skill document to add, and the\n * handoff a skill would define is unnecessary here: Building ends by opening a\n * pull request, which arrives as its own event and raises the Review card.\n */\nfunction buildWorkItem(context: FactoryStageRuleContext) {\n const subject = context.item.url ? `the approved plan for ${context.item.url}` : 'the approved plan';\n const reporter = reporterCoAuthor(context);\n // The trailer needs the reporter's numeric id, which intake does not stamp, so\n // the agent resolves it from the same issue it is already reading.\n const credit = reporter\n ? ` The work was reported by @${reporter}: credit them on every commit with a ` +\n `\\`Co-Authored-By: ${reporter} <ID+${reporter}@users.noreply.github.com>\\` trailer, ` +\n `resolving ID with \\`gh api users/${reporter} --jq .id\\`.`\n : '';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:build`,\n role: 'work',\n prompt: `Implement ${subject}. Open a pull request when the work is ready for review.${credit}`,\n } as const;\n}\n\nfunction completeIssue(context: FactoryStageRuleContext) {\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:factory-complete-issue`,\n role: 'triage',\n skillName: 'factory-complete-issue',\n arguments: context.item.url ? `GitHub issue (${context.item.url})` : context.item.title,\n } as const;\n}\n\nfunction reviewPullRequest(context: FactoryStageRuleContext) {\n // A re-entry into Review (from any post-intake stage) supersedes whichever\n // review pass previously ran on this card: cancel any in-flight run before\n // dispatching a fresh one so we don't burn tokens on the stale pass and race\n // two agents on the same card. Cancellation is safe when nothing is in flight.\n const supersedes = context.fromStage !== 'intake';\n // The re-review skill only applies when a prior review pass actually completed\n // (the card is returning from `done`). A cancelled first-time review that\n // re-enters Review from `review` itself still has no prior pass to reconcile —\n // it gets the regular factory-review skill.\n const priorReviewCompleted = context.fromStage === 'done';\n const skillName = priorReviewCompleted ? 'factory-rereview' : 'factory-review';\n return {\n type: 'invokeSkill',\n idempotencyKey: `${context.ingress.id}:${skillName}`,\n role: 'review',\n skillName,\n arguments: context.item.url ? `GitHub pull request (${context.item.url})` : context.item.title,\n ...(supersedes ? { cancelInFlight: true } : {}),\n } as const;\n}\n\n// Fires only on webhook materialization, so an item filed by hand or re-synced\n// from source never suggests its own run.\nfunction onArrival<Effect>(rule: (context: FactoryStageRuleContext) => Effect) {\n return (context: FactoryStageRuleContext): Effect | undefined => {\n if (context.cause !== 'linked_item_materialized') return;\n if (context.item.metadata?.autoStartCandidate !== true) return;\n return rule(context);\n };\n}\n\nfunction resultContent(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (!value || typeof value !== 'object' || Array.isArray(value)) return;\n const content = (value as { content?: unknown }).content;\n return typeof content === 'string' ? content : undefined;\n}\n\n// Interactive-session path only: factory-plan never calls submit_plan — it\n// advances planning → execute via factory_transition_work_item directly.\nfunction advanceApprovedPlan(context: FactoryToolResultRuleContext) {\n if (\n context.result.status !== 'success' ||\n context.board !== 'work' ||\n context.item.stages.length !== 1 ||\n context.item.stages[0] !== 'planning' ||\n context.actor.type !== 'agent' ||\n context.actor.role !== 'plan' ||\n !resultContent(context.result.value)?.startsWith('Plan approved.')\n ) {\n return;\n }\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:approved-plan`,\n board: 'work',\n stage: 'execute',\n } as const;\n}\n\nfunction createdAfterFactory(createdAt: string | undefined, factoryCreatedAt: string): boolean {\n if (!createdAt) return false;\n const sourceCreatedAt = Date.parse(createdAt);\n const projectCreatedAt = Date.parse(factoryCreatedAt);\n return Number.isFinite(sourceCreatedAt) && Number.isFinite(projectCreatedAt) && sourceCreatedAt > projectCreatedAt;\n}\n\nfunction issueOpened(context: FactoryGithubRuleContext) {\n if (!context.issue) return;\n // Everything arrives in Intake; arrival only stamps whether `onArrival` may\n // suggest this card's run without a person.\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-intake`,\n board: 'work',\n source: 'github-issue',\n sourceKey: `github-issue:${context.issue.number}`,\n title: context.issue.title,\n url: context.issue.url,\n stage: 'intake',\n metadata: {\n githubRepositoryId: context.repository.id,\n githubIssueNumber: context.issue.number,\n ...(context.issue.createdAt ? { sourceCreatedAt: context.issue.createdAt } : {}),\n ...(githubActorLogin(context) ? { author: githubActorLogin(context) } : {}),\n authorTrusted: trustedGithubActor(context),\n autoStartCandidate:\n trustedGithubActor(context) && createdAfterFactory(context.issue.createdAt, context.factory.createdAt),\n assignees: context.issue.assignees ?? [],\n labels: context.issue.labels ?? [],\n },\n } as const;\n}\n\nfunction issueClosed(context: FactoryGithubRuleContext) {\n if (!context.item || context.item.source !== 'github-issue' || !context.issue) return;\n if (context.board !== 'work') return;\n // Already off the board: nothing to reconcile.\n if (context.item.stages.some(stage => stage === 'done' || stage === 'canceled')) return;\n // Issue closure is a repository fact, not third-party input — no actor trust\n // gate. `not_planned` (and `duplicate`) means abandoned, everything else is\n // completed work.\n const canceled = context.issue.stateReason === 'not_planned' || context.issue.stateReason === 'duplicate';\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: 'work',\n stage: canceled ? 'canceled' : 'done',\n message: {\n text:\n `GitHub issue #${context.issue.number} was closed` +\n `${context.issue.stateReason ? ` (${context.issue.stateReason})` : ''}; ` +\n `this Work card was moved to ${canceled ? 'Canceled' : 'Done'}.`,\n },\n } as const;\n}\n\nfunction pullRequestOpened(context: FactoryGithubRuleContext) {\n if (!context.pullRequest) return;\n // A GitHub App bot is never a collaborator, so Factory's own PRs score\n // untrusted; their authorship is the trust signal.\n const factoryAuthored = context.actor.type === 'github' && context.actor.factoryAuthored;\n const autoStartCandidate =\n (trustedGithubActor(context) || factoryAuthored) &&\n createdAfterFactory(context.pullRequest.createdAt, context.factory.createdAt);\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:pull-request-intake`,\n board: 'review',\n source: 'github-pr',\n sourceKey: `github-pr:${context.pullRequest.number}`,\n title: context.pullRequest.title,\n url: context.pullRequest.url,\n stage: 'intake',\n metadata: {\n githubRepositoryId: context.repository.id,\n githubPullRequestNumber: context.pullRequest.number,\n ...(context.pullRequest.createdAt ? { sourceCreatedAt: context.pullRequest.createdAt } : {}),\n factoryAuthored,\n authorTrusted: trustedGithubActor(context),\n autoStartCandidate,\n state: context.pullRequest.state,\n draft: context.pullRequest.draft,\n merged: context.pullRequest.merged,\n assignees: context.pullRequest.assignees ?? [],\n requestedReviewers: context.pullRequest.requestedReviewers ?? [],\n labels: context.pullRequest.labels ?? [],\n headBranch: context.pullRequest.headBranch,\n baseBranch: context.pullRequest.baseBranch,\n ...(githubActorLogin(context) ? { author: githubActorLogin(context) } : {}),\n },\n } as const;\n}\n\nfunction pullRequestMerged(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest?.merged) return;\n if (context.board === 'review') {\n // The event is bound to the PR's own Review card: a merged PR is finished\n // review work, so always move the card to Done. The message only reaches\n // an active session (if any) — cards without one just move, instead of\n // failing retries against a binding that never existed.\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:pull-request-merged`,\n board: 'review',\n stage: 'done',\n message: {\n text:\n `Pull request #${context.pullRequest.number} merged; this Review card was moved to Done. ` +\n 'No further review is needed unless follow-up work was requested.',\n },\n } as const;\n }\n // Provenance bound the event to the originating Work item instead: remind\n // its agent to assess completion — never auto-complete the Work item.\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:assess-work-completion`,\n role: 'work',\n message:\n `Pull request #${context.pullRequest.number} merged. Assess whether the linked Work item is complete. ` +\n 'Do not mark it Done solely because this PR merged; use factory_transition_work_item only after verifying the work.',\n } as const;\n}\n\nfunction addressReviewFeedback(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || !context.review) return;\n // Only the Work item that authored the PR can act on the feedback. Provenance\n // binds the event there; a Review card seeing its own posted review must not\n // react to it (that would loop the reviewer against itself).\n if (context.board !== 'work') return;\n // A closed or merged pull request has no branch left to push fixes to.\n if (context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // `approved` needs no work, and `commented` (a review body with no verdict)\n // is how a reviewer leaves notes without blocking — only a verdict that asks\n // for changes should pull the author back in.\n if (context.review.state.toLowerCase() !== 'changes_requested') return;\n // The authoring thread is already subscribed to this PR (`gh pr create`\n // subscribes automatically), so it can read the individual line comments\n // from its own notification inbox — the message only has to wake it and\n // point at the review.\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-review-feedback`,\n role: 'work',\n priority: 'high',\n message:\n `Changes were requested on pull request #${context.pullRequest.number} (${context.review.url}). ` +\n 'Read the review comments on this PR, address the ones you agree with, and push the fixes to the PR branch. ' +\n 'Reply on GitHub to anything you are deliberately not changing, explaining why.',\n } as const;\n}\n\n/**\n * Detects the `factory-review` handoff verdict in a comment body.\n *\n * GitHub forbids an app from reviewing a pull request it authored, so on\n * Factory-authored PRs the review skill falls back to posting its verdict as a\n * plain comment. That comment is the only signal the authoring agent gets, so\n * it has to be readable back out. The skill's handoff contract puts the verdict\n * on the first line (`Verdict: request changes`), so only that line is\n * inspected — a verdict quoted later in the findings must not count.\n */\nfunction requestsChangesVerdict(body: string | undefined): boolean {\n const firstLine = body\n ?.split('\\n')\n .map(line => line.trim())\n .find(line => line.length > 0);\n if (!firstLine) return false;\n // Tolerate the markdown the skill wraps the line in (`**Verdict: ...**`).\n const normalized = firstLine\n .replaceAll(/[*_`#>\\s]+/g, ' ')\n .trim()\n .toLowerCase();\n // Match the verdict exactly so negated phrasings (\"Verdict: do not request\n // changes\") cannot wake the author.\n return /^verdict: ?(request changes|changes requested)$/.test(normalized);\n}\n\nfunction addressPullRequestComment(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || !context.issueComment) return;\n // Provenance binds the comment to the Work item that authored the PR — the\n // only session that can act on it. A Review card must not react to comments\n // on the PR it is reviewing.\n if (context.board !== 'work') return;\n if (context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // `factoryAuthored` is one bit for the whole Factory, so Factory's own\n // comments are indistinguishable between roles — waking on all of them would\n // let the Work agent's own progress comments wake itself in a loop. The one\n // exception is the review verdict the Review run had to post as a comment\n // because GitHub refused a self-review: that is the handoff, and it only ever\n // asks for changes once per review, so it cannot sustain a loop.\n if (\n context.actor.type === 'github' &&\n context.actor.factoryAuthored &&\n !requestsChangesVerdict(context.issueComment.body)\n ) {\n return;\n }\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-pull-request-comment`,\n role: 'work',\n priority: 'high',\n message:\n `${context.issueComment.author ?? 'Someone'} commented on pull request #${context.pullRequest.number} ` +\n `(${context.issueComment.url ?? context.pullRequest.url}). Read the comment, address it if you agree, and push ` +\n 'the fixes to the PR branch. Reply on GitHub to anything you are deliberately not changing, explaining why.',\n } as const;\n}\n\nfunction pullRequestClosed(context: FactoryGithubRuleContext) {\n if (!context.item || !context.pullRequest || context.pullRequest.merged) return;\n if (context.board !== 'review') return;\n // A PR closed without merging is abandoned review work: clear the card off\n // the board instead of leaving it in Reviewing forever.\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:pull-request-closed`,\n board: 'review',\n stage: 'canceled',\n message: {\n text:\n `Pull request #${context.pullRequest.number} was closed without merging; ` +\n 'this Review card was moved to Canceled.',\n },\n } as const;\n}\n\nfunction reReviewRequestedPullRequest(context: FactoryGithubRuleContext) {\n // Only a review re-requested *from Factory's own bot* restarts the review —\n // requesting a human reviewer is not Factory's signal.\n if (!context.item || context.board !== 'review' || !context.reviewRequest?.factoryReviewer) return;\n if (!context.pullRequest || context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // Trusted (write/admin) requesters only: re-entering review checks out and\n // executes PR code, the same bar pullRequestOpened applies to auto-review.\n if (!trustedGithubActor(context)) return;\n if (context.actor.type === 'github' && context.actor.factoryAuthored) return;\n // Already in Reviewing: a review pass is pending or running; re-entering\n // would be a same-stage no-op anyway (stage rules only fire on change).\n if (context.item.stages.length === 1 && context.item.stages[0] === 'review') return;\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-requested`,\n board: 'review',\n stage: 'review',\n } as const;\n}\n\nfunction reReviewUpdatedPullRequest(context: FactoryGithubRuleContext) {\n if (!context.item || context.board !== 'review') return;\n if (!context.pullRequest || context.pullRequest.state !== 'open' || context.pullRequest.merged) return;\n // Intake has not started a review pass yet, so a push there is just more of\n // the code the first pass will read. A push to a card sitting in Reviewing is\n // different: it invalidates whatever that pass is reading, so re-enter the\n // stage to supersede it. `reviewPullRequest` cancels the stale run and picks\n // the right skill for the entry it sees.\n if (context.item.stages.some(stage => stage === 'intake')) return;\n const alreadyReviewing = context.item.stages.some(stage => stage === 'review');\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-updated`,\n board: 'review',\n stage: 'review',\n // Re-entry is the point when the card is already Reviewing: the stage's\n // entry rule is what cancels the superseded pass and starts one on the code\n // that just landed.\n ...(alreadyReviewing ? { reenter: true } : {}),\n } as const;\n}\n\nfunction linearIssueObserved(context: FactoryLinearRuleContext) {\n if (context.item) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-triage`,\n board: 'work',\n source: 'linear-issue',\n sourceKey: `linear:${context.issue.identifier}`,\n title: `${context.issue.identifier}: ${context.issue.title}`,\n url: context.issue.url,\n stage: 'triage',\n metadata: {\n linearIssueId: context.issue.id,\n identifier: context.issue.identifier,\n sourceCreatedAt: context.issue.createdAt,\n linearState: context.issue.state,\n linearStateType: context.issue.stateType,\n linearPriority: context.issue.priorityLabel,\n linearAssignee: context.issue.assignee,\n linearCreator: context.issue.creator,\n linearTeam: context.issue.team,\n labels: [...context.issue.labels] as string[],\n ...(context.issue.assignee ? { assignee: context.issue.assignee } : {}),\n ...(context.issue.creator ? { creator: context.issue.creator, author: context.issue.creator } : {}),\n },\n } as const;\n}\n\nfunction linearIssueClosed(context: FactoryLinearRuleContext) {\n if (!context.item || context.item.source !== 'linear-issue') return;\n if (context.board !== 'work') return;\n // Already off the board: nothing to reconcile.\n if (context.item.stages.some(stage => stage === 'done' || stage === 'canceled')) return;\n // Only terminal state types trigger close.\n const stateType = context.issue.stateType;\n if (stateType !== 'completed' && stateType !== 'canceled') return;\n const canceled = stateType === 'canceled';\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: 'work',\n stage: canceled ? 'canceled' : 'done',\n message: {\n text: `Linear issue ${context.issue.identifier} was ${canceled ? 'canceled' : 'completed'}; this Work card was moved to ${canceled ? 'Canceled' : 'Done'}.`,\n },\n } as const;\n}\n\nconst BUILT_IN_DEFAULTS: FactoryRulesOverrides = {\n work: {\n intake: { issue: { onEnter: onArrival(invokeIssueInvestigation) } },\n triage: {\n issue: { onEnter: invokeIssueInvestigation },\n linearIssue: { onEnter: investigateTriagedLinearIssue },\n },\n planning: {\n issue: { onEnter: planWorkItem },\n linearIssue: { onEnter: planWorkItem },\n manual: { onEnter: planWorkItem },\n },\n execute: {\n issue: { onEnter: buildWorkItem },\n linearIssue: { onEnter: buildWorkItem },\n manual: { onEnter: buildWorkItem },\n },\n done: {\n issue: { onEnter: completeIssue },\n },\n },\n review: {\n intake: { pullRequest: { onEnter: onArrival(reviewPullRequest) } },\n review: { pullRequest: { onEnter: reviewPullRequest } },\n },\n tools: { submit_plan: { onResult: advanceApprovedPlan } },\n github: {\n issueOpened: { onEvent: issueOpened },\n issueEdited: { onEvent: retriageGithubIssue },\n issueClosed: { onEvent: issueClosed },\n issueCommentCreated: { onEvent: retriageGithubIssue },\n issueCommentEdited: { onEvent: retriageGithubIssue },\n issueCommentDeleted: { onEvent: retriageGithubIssue },\n pullRequestOpened: { onEvent: pullRequestOpened },\n pullRequestUpdated: { onEvent: reReviewUpdatedPullRequest },\n pullRequestCommentCreated: { onEvent: addressPullRequestComment },\n pullRequestReviewRequested: { onEvent: reReviewRequestedPullRequest },\n pullRequestReviewSubmitted: { onEvent: addressReviewFeedback },\n pullRequestMerged: { onEvent: pullRequestMerged },\n pullRequestClosed: { onEvent: pullRequestClosed },\n },\n linear: { issueObserved: { onEvent: linearIssueObserved }, issueClosed: { onEvent: linearIssueClosed } },\n};\n\nfunction mergeBoardRules(\n base: FactoryBoardRules | undefined,\n overrides: FactoryBoardRules | undefined,\n): FactoryBoardRules {\n const result: FactoryBoardRules = {};\n const stages = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryRuleStage>;\n for (const stage of stages) {\n const baseSources = base?.[stage];\n const overrideSources = overrides?.[stage];\n const sources = new Set([\n ...Object.keys(baseSources ?? {}),\n ...Object.keys(overrideSources ?? {}),\n ]) as Set<FactoryRuleSource>;\n const mergedSources: Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>> = {};\n for (const source of sources) {\n const baseLeaf = baseSources?.[source];\n const overrideLeaf = overrideSources?.[source];\n mergedSources[source] = {\n ...(baseLeaf && 'onEnter' in baseLeaf ? { onEnter: baseLeaf.onEnter } : {}),\n ...(baseLeaf && 'onExit' in baseLeaf ? { onExit: baseLeaf.onExit } : {}),\n ...(overrideLeaf && 'onEnter' in overrideLeaf ? { onEnter: overrideLeaf.onEnter } : {}),\n ...(overrideLeaf && 'onExit' in overrideLeaf ? { onExit: overrideLeaf.onExit } : {}),\n };\n }\n result[stage] = mergedSources;\n }\n return result;\n}\n\nfunction mergeToolRules(\n base: Record<string, FactoryToolRuleLeaf> | undefined,\n overrides: Record<string, FactoryToolRuleLeaf> | undefined,\n): Record<string, FactoryToolRuleLeaf> {\n const result: Record<string, FactoryToolRuleLeaf> = {};\n for (const name of new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})])) {\n const baseLeaf = base?.[name];\n const overrideLeaf = overrides?.[name];\n result[name] = {\n ...(baseLeaf && 'onResult' in baseLeaf ? { onResult: baseLeaf.onResult } : {}),\n ...(overrideLeaf && 'onResult' in overrideLeaf ? { onResult: overrideLeaf.onResult } : {}),\n };\n }\n return result;\n}\n\nfunction mergeGithubRules(\n base: FactoryRulesOverrides['github'],\n overrides: FactoryRulesOverrides['github'],\n): NonNullable<FactoryRulesOverrides['github']> {\n const result: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>> = {};\n const events = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryGithubEventName>;\n for (const event of events) {\n const baseLeaf = base?.[event];\n const overrideLeaf = overrides?.[event];\n result[event] = {\n ...(baseLeaf && 'onEvent' in baseLeaf ? { onEvent: baseLeaf.onEvent } : {}),\n ...(overrideLeaf && 'onEvent' in overrideLeaf ? { onEvent: overrideLeaf.onEvent } : {}),\n };\n }\n return result;\n}\n\nfunction mergeLinearRules(\n base: FactoryRulesOverrides['linear'],\n overrides: FactoryRulesOverrides['linear'],\n): NonNullable<FactoryRulesOverrides['linear']> {\n const result: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>> = {};\n const events = new Set([...Object.keys(base ?? {}), ...Object.keys(overrides ?? {})]) as Set<FactoryLinearEventName>;\n for (const event of events) {\n const baseLeaf = base?.[event];\n const overrideLeaf = overrides?.[event];\n result[event] = {\n ...(baseLeaf && 'onEvent' in baseLeaf ? { onEvent: baseLeaf.onEvent } : {}),\n ...(overrideLeaf && 'onEvent' in overrideLeaf ? { onEvent: overrideLeaf.onEvent } : {}),\n };\n }\n return result;\n}\n\nexport function mergeFactoryRuleOverrides(\n base: FactoryRulesOverrides,\n overrides: FactoryRulesOverrides = {},\n): Omit<FactoryRules, 'version'> {\n return {\n work: mergeBoardRules(base.work, overrides.work),\n review: mergeBoardRules(base.review, overrides.review),\n tools: mergeToolRules(base.tools, overrides.tools),\n github: mergeGithubRules(base.github, overrides.github),\n linear: mergeLinearRules(base.linear, overrides.linear),\n };\n}\n\nexport function defaultFactoryRules(input: { version: string; overrides?: FactoryRulesOverrides }): FactoryRules {\n if (typeof input?.version !== 'string' || input.version.trim().length === 0) {\n throw new FactoryRuleValidationError('Factory rule version is required.');\n }\n\n const rules: FactoryRules = {\n version: input.version.trim(),\n ...mergeFactoryRuleOverrides(BUILT_IN_DEFAULTS, input.overrides),\n };\n assertFactoryRules(rules);\n return rules;\n}\n\nexport function builtInFactoryRules(): FactoryRules {\n return defaultFactoryRules({ version: DEFAULT_FACTORY_RULE_VERSION });\n}\n"],"mappings":";;AAmBA,MAAa,+BAA+B;AAE5C,SAAS,mBAAmB,SAA0D;CACpF,OAAO,QAAQ,MAAM,SAAS,YAAY,QAAQ,MAAM;AAC1D;AAEA,SAAS,iBAAiB,SAAqE;CAC7F,OAAO,QAAQ,MAAM,SAAS,WAAW,QAAQ,MAAM,QAAQ,KAAA;AACjE;AAEA,SAAS,yBAAyB,SAAkC;CAClE,OAAO;EACL,MAAM;EACN,gBAAgB,GAAG,QAAQ,QAAQ,GAAG;EACtC,MAAM;EACN,WAAW;EACX,WAAW,QAAQ,KAAK,MAAM,iBAAiB,QAAQ,KAAK,IAAI,KAAK,QAAQ,KAAK;CACpF;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,IAAI,CAAC,QAAQ,QAAQ,QAAQ,KAAK,WAAW,kBAAkB,CAAC,QAAQ,KAAK,KAAK;CAClF,IAAI,QAAQ,MAAM,SAAS,YAAY,QAAQ,MAAM,iBAAiB;CAEtE,MAAM,SACJ,QAAQ,UAAU,gBACd,QAAQ,aAAa,SAAS,QAAQ,YAAY,OAChD,gCACA,QAAQ,aAAa,QACnB,uBACA,sBACJ,QAAQ,UAAU,wBAChB,oBACA,QAAQ,UAAU,uBAChB,mBACA;CACV,OAAO;EACL,MAAM;EACN,gBAAgB,GAAG,QAAQ,QAAQ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D,KAAK,IAAI,IAAI;IAOP,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAOrB,OAAO,CAAC,GAAG,OAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAguB/C;AAED,eAAO,MAAM,0BAA0B;;;;;;;;;;CAU7B,CAAC"}
@@ -577,7 +577,7 @@ var FactoryDecisionDispatcher = class {
577
577
  },
578
578
  reuseMode: "preserve"
579
579
  });
580
- if (!result.item.parentWorkItemId && parentWorkItemId) {
580
+ if (!result.item.parentWorkItemId && parentWorkItemId && parentWorkItemId !== result.item.id) {
581
581
  const item = await this.#storage.setParentWorkItemIfMissing({
582
582
  orgId: record.orgId,
583
583
  id: result.item.id,
@@ -589,6 +589,21 @@ var FactoryDecisionDispatcher = class {
589
589
  item
590
590
  };
591
591
  }
592
+ if (!result.created) {
593
+ const missing = Object.fromEntries(Object.entries(decision.metadata ?? {}).filter(([key]) => key !== "factoryRuleMaterializationKey" && result.item.metadata?.[key] === void 0));
594
+ if (Object.keys(missing).length > 0) {
595
+ const filled = await this.#storage.update({
596
+ orgId: record.orgId,
597
+ id: result.item.id,
598
+ userId: "factory-rule-dispatcher",
599
+ patch: { metadata: missing }
600
+ });
601
+ if (filled) result = {
602
+ ...result,
603
+ item: filled.item
604
+ };
605
+ }
606
+ }
592
607
  const materializedByDecision = result.item.metadata?.[FACTORY_RULE_MATERIALIZATION_KEY] === record.idempotencyKey;
593
608
  if (!materializedByDecision && (decision.stage === "intake" || !result.item.stages.includes("intake"))) return;
594
609
  const board = decision.board;