@mastra/factory 0.2.1 → 0.2.2-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/dist/auth.d.ts +2 -2
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +22 -2
- package/dist/auth.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +411 -244
- package/dist/factory.js.map +1 -1
- package/dist/index.js +411 -244
- package/dist/index.js.map +1 -1
- package/dist/integrations/github/integration.js +85 -37
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +85 -37
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +2 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +28 -8
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +119 -39
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +1 -4
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/surface.js +1 -4
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +7 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/tools.js.map +1 -1
- package/dist/spa-static.d.ts.map +1 -1
- package/dist/spa-static.js +1 -0
- package/dist/spa-static.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +9 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +4 -0
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +4 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +20 -4
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/dist/timing.d.ts +15 -0
- package/dist/timing.d.ts.map +1 -0
- package/dist/timing.js +27 -0
- package/dist/timing.js.map +1 -0
- package/dist/workspace.d.ts +2 -3
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +104 -65
- package/dist/workspace.js.map +1 -1
- package/factory-skills/factory-review/SKILL.md +9 -2
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/storage/domains/work-items/base.ts","../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Factory work-items storage domain.\n *\n * Work items belong to a first-class Factory project. External intake items use\n * a provider-neutral source reference; manual work items have no source.\n * Stage history is server-owned, while session and metadata patches merge\n * atomically so concurrent actors do not overwrite each other. The authoritative\n * Factory transition path keeps one exclusive current stage per item.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport type WorkItemStage = string;\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nexport function factoryDecisionHash(decision: Record<string, unknown>): string {\n return createHash('sha256').update(stableJson(decision)).digest('hex');\n}\n\nexport interface ExternalWorkItemSource {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n}\n\nexport interface WorkItemStageEntry {\n stage: WorkItemStage;\n enteredAt: string;\n exitedAt?: string;\n by: string;\n /**\n * Actor that closed this entry; absent on entries written before exit\n * stamping existed — treat as human.\n */\n exitedBy?: string;\n}\n\n/**\n * Sentinel actor ids that mark a stage transition as automation-driven (vs a\n * human's WorkOS user id): generic sentinels plus the system ids the Factory\n * rules engine stamps (see `actorId` in factory/rules/transition-service.ts).\n * Metrics treat any other actor — including a missing `exitedBy` on\n * pre-existing entries — as human.\n */\nexport const AUTOMATION_ACTORS = new Set([\n 'factory',\n 'system',\n 'automation',\n 'factory-rule-dispatcher',\n 'factory-tool-result-rule',\n]);\n\n/**\n * Whether an actor id marks a transition no human performed on the Factory\n * board: a sentinel automation id, an agent binding (`agent:*`), or an\n * external-webhook actor (`github:*` — a human may have acted on GitHub, but\n * the board move itself was automated).\n */\nexport function isAutomationActor(by: string | undefined): boolean {\n if (by === undefined) return false;\n return AUTOMATION_ACTORS.has(by) || by.startsWith('agent:') || by.startsWith('github:');\n}\n\nexport interface WorkItemSessionRef {\n sessionId: string;\n branch: string;\n threadId: string;\n startedBy: string;\n}\n\nexport interface FactoryRuleIngressRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n identity: string;\n triggerType: string;\n transitionId: string;\n result: Record<string, unknown>;\n createdAt: Date;\n}\n\nexport interface CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: string; triggerType: string };\n ruleSetVersion: string;\n expectedRevision: number | null;\n actor: Record<string, unknown> | null;\n outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string };\n decisions: Record<string, unknown>[];\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n now: Date;\n}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageId: string;\n lastMessageCreatedAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRuleEvaluationRecord {\n id: string;\n ingressId: string;\n workItemId: string | null;\n ruleSetVersion: string;\n expectedRevision: number | null;\n outcome: 'accepted' | 'rejected';\n code: string | null;\n reason: string | null;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n createdAt: Date;\n}\n\nexport type FactoryDispatchStatus = 'pending' | 'leased' | 'retry' | 'succeeded' | 'failed';\n\nexport interface FactoryDeferredDecisionPageInput {\n orgId: string;\n factoryProjectId: string;\n statuses?: FactoryDispatchStatus[];\n before?: { createdAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionPage {\n decisions: FactoryDeferredDecisionRecord[];\n hasMore: boolean;\n}\n\nexport interface FactoryDeferredDecisionRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n evaluationId: string;\n workItemId: string | null;\n idempotencyKey: string;\n effectOrdinal: number;\n effectHash: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n actor: Record<string, unknown> | null;\n decision: Record<string, unknown>;\n status: FactoryDispatchStatus;\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRunBindingSessionAddress {\n factoryProjectId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n}\n\nexport interface FactoryRunBindingAddress extends FactoryRunBindingSessionAddress {\n orgId: string;\n}\n\nexport interface RevokeFactoryRunBindingInput {\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n revokedAt: Date;\n}\n\nexport interface FactoryRunBindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n status: 'active' | 'revoked';\n createdAt: Date;\n revokedAt: Date | null;\n}\n\nexport interface FactoryPendingStartRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n kickoffKey: string;\n message: string | null;\n status: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryLeaseClaimInput {\n ownerId: string;\n now: Date;\n leaseExpiresAt: Date;\n limit: number;\n}\n\nexport interface FactoryLeaseIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n ownerId: string;\n}\n\nexport interface FactoryDispatchFailureInput extends FactoryLeaseIdentity {\n now: Date;\n availableAt: Date;\n lastError: string;\n terminal: boolean;\n}\n\nexport interface CommitFactoryTransitionInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n expectedRevision: number;\n destinationStage: string;\n actorId: string;\n ingress: { identity: string; triggerType: string; transitionId: string };\n ruleSetVersion: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n}\n\nexport type CommitFactoryTransitionResult =\n | { status: 'committed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: WorkItemRow;\n binding: FactoryRunBindingRecord;\n pendingStart: FactoryPendingStartRecord;\n replayed: boolean;\n}\n\n/** Session ref as accepted from clients — `startedBy` is stamped server-side. */\nexport interface WorkItemSessionInput {\n sessionId: string;\n branch: string;\n threadId: string;\n}\n\nexport type WorkItemSessions = Record<string, WorkItemSessionRef>;\n\nexport interface WorkItemRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemInput {\n externalSource?: ExternalWorkItemSource | null;\n parentWorkItemId?: string | null;\n title: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface UpdateWorkItemInput {\n parentWorkItemId?: string | null;\n title?: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: WorkItemRow;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_updated_at_idx',\n columns: ['org_id', 'factory_project_id', 'updated_at'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n ],\n};\n\ninterface WorkItemDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n stages: WorkItemStage[];\n stage_history: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction sourceKey(source: ExternalWorkItemSource | null | undefined): string | null {\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction toWorkItem(row: WorkItemDbRow): WorkItemRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n externalSource: row.external_source,\n parentWorkItemId: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<WorkItemRow>): Partial<WorkItemDbRow> {\n return {\n ...(changes.parentWorkItemId !== undefined ? { parent_work_item_id: changes.parentWorkItemId } : {}),\n ...(changes.title !== undefined ? { title: changes.title } : {}),\n ...(changes.stages !== undefined ? { stages: changes.stages } : {}),\n ...(changes.stageHistory !== undefined ? { stage_history: changes.stageHistory } : {}),\n ...(changes.sessions !== undefined ? { sessions: changes.sessions } : {}),\n ...(changes.metadata !== undefined ? { metadata: changes.metadata } : {}),\n ...(changes.revision !== undefined ? { revision: changes.revision } : {}),\n ...(changes.updatedAt !== undefined ? { updated_at: changes.updatedAt } : {}),\n };\n}\n\nfunction emptyPrior(): WorkItemPriorState {\n return { stages: [], sessionRoles: [] };\n}\n\nfunction priorState(row: WorkItemDbRow): WorkItemPriorState {\n return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };\n}\n\nexport class WorkItemRelationError extends Error {\n readonly code = 'invalid_work_item_relation';\n}\n\nexport function validateParentRelation(\n projectItems: WorkItemRow[],\n itemId: string | undefined,\n parentWorkItemId: string | null,\n): void {\n if (parentWorkItemId === null) return;\n const byId = new Map(projectItems.map(item => [item.id, item]));\n const parent = byId.get(parentWorkItemId);\n if (!parent) throw new WorkItemRelationError('Related work item not found in this project.');\n if (itemId === parentWorkItemId) throw new WorkItemRelationError('A work item cannot relate to itself.');\n\n const visited = new Set<string>();\n let cursor: WorkItemRow | undefined = parent;\n while (cursor?.parentWorkItemId) {\n if (cursor.parentWorkItemId === itemId) {\n throw new WorkItemRelationError('This relationship would create a cycle.');\n }\n if (visited.has(cursor.id)) throw new WorkItemRelationError('The related work item chain contains a cycle.');\n visited.add(cursor.id);\n cursor = byId.get(cursor.parentWorkItemId);\n }\n}\n\n/**\n * Diff `oldStages` → `newStages` and return the updated history: exited stages\n * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get\n * a new entry.\n */\nexport function applyStageTransition(\n history: WorkItemStageEntry[],\n oldStages: WorkItemStage[],\n newStages: WorkItemStage[],\n by: string,\n now: Date,\n): WorkItemStageEntry[] {\n const timestamp = now.toISOString();\n const next = history.map(entry => ({ ...entry }));\n for (const stage of oldStages) {\n if (newStages.includes(stage)) continue;\n for (let i = next.length - 1; i >= 0; i--) {\n const entry = next[i]!;\n if (entry.stage === stage && entry.exitedAt === undefined) {\n entry.exitedAt = timestamp;\n entry.exitedBy = by;\n break;\n }\n }\n }\n for (const stage of newStages) {\n if (!oldStages.includes(stage)) next.push({ stage, enteredAt: timestamp, by });\n }\n return next;\n}\n\nexport function stampSessions(sessions: Record<string, WorkItemSessionInput>, by: string): WorkItemSessions {\n return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, { ...session, startedBy: by }]));\n}\n\nfunction applyUpdate({\n current,\n userId,\n input,\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n}): Partial<WorkItemDbRow> {\n const now = new Date();\n return {\n ...(input.parentWorkItemId !== undefined ? { parent_work_item_id: input.parentWorkItemId } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.stages !== undefined\n ? {\n stages: input.stages,\n stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now),\n }\n : {}),\n ...(input.sessions !== undefined\n ? { sessions: { ...current.sessions, ...stampSessions(input.sessions, userId) } }\n : {}),\n ...(input.metadata !== undefined\n ? { metadata: input.metadata === null ? null : { ...(current.metadata ?? {}), ...input.metadata } }\n : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\n\nconst projectRelationLocks = new Map<string, Promise<unknown>>();\n\nfunction withInProcessProjectLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = projectRelationLocks.get(key) ?? Promise.resolve();\n const result = previous.then(fn, fn);\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n projectRelationLocks.set(key, tail);\n void tail.then(() => {\n if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);\n });\n return result;\n}\n\nconst FACTORY_GOVERNANCE_SCHEMAS: CollectionSchema[] = [\n {\n name: 'factory_rule_ingress',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n identity: { type: 'text' },\n trigger_type: { type: 'text' },\n transition_id: { type: 'text' },\n result: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_rule_ingress_tenant_identity_unique', columns: ['org_id', 'factory_project_id', 'identity'] },\n ],\n },\n {\n name: 'factory_rule_evaluations',\n columns: {\n id: { type: 'uuid-pk' },\n ingress_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n rule_set_version: { type: 'text' },\n expected_revision: { type: 'integer', nullable: true },\n outcome: { type: 'text' },\n code: { type: 'text', nullable: true },\n reason: { type: 'text', nullable: true },\n causal_chain: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_deferred_decisions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n evaluation_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n idempotency_key: { type: 'text' },\n effect_ordinal: { type: 'integer' },\n effect_hash: { type: 'text' },\n causal_chain: { type: 'json' },\n actor: { type: 'json', nullable: true },\n decision: { type: 'json' },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_deferred_decisions_tenant_key_unique',\n columns: ['org_id', 'factory_project_id', 'idempotency_key'],\n },\n ],\n },\n {\n name: 'factory_run_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n role: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n session_id: { type: 'text' },\n branch: { type: 'text' },\n status: { type: 'text' },\n created_at: { type: 'timestamp' },\n revoked_at: { type: 'timestamp', nullable: true },\n },\n },\n {\n name: 'factory_tool_result_cursors',\n columns: {\n binding_id: { type: 'text', primaryKey: true },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n last_message_id: { type: 'text' },\n last_message_created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_pending_starts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n binding_id: { type: 'text' },\n kickoff_key: { type: 'text' },\n message: { type: 'text', nullable: true },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_pending_starts_tenant_kickoff_unique',\n columns: ['org_id', 'factory_project_id', 'kickoff_key'],\n },\n ],\n },\n];\n\ninterface GovernanceDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n created_at: Date;\n [key: string]: unknown;\n}\n\nfunction toBinding(row: GovernanceDbRow): FactoryRunBindingRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: String(row.work_item_id),\n role: String(row.role),\n threadId: String(row.thread_id),\n resourceId: String(row.resource_id),\n sessionId: String(row.session_id),\n branch: String(row.branch),\n status: row.status as FactoryRunBindingRecord['status'],\n createdAt: row.created_at,\n revokedAt: (row.revoked_at as Date | null) ?? null,\n };\n}\nfunction toDeferredDecision(row: GovernanceDbRow): FactoryDeferredDecisionRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n evaluationId: String(row.evaluation_id),\n workItemId: row.work_item_id === null || row.work_item_id === undefined ? null : String(row.work_item_id),\n idempotencyKey: String(row.idempotency_key),\n effectOrdinal: Number(row.effect_ordinal),\n effectHash: String(row.effect_hash),\n causalChain: (row.causal_chain as FactoryDeferredDecisionRecord['causalChain']) ?? [],\n actor: (row.actor as Record<string, unknown> | null) ?? null,\n decision: row.decision as Record<string, unknown>,\n status: row.status as FactoryDispatchStatus,\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\nfunction toPendingStart(row: GovernanceDbRow): FactoryPendingStartRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n bindingId: String(row.binding_id),\n kickoffKey: String(row.kickoff_key),\n message: (row.message as string | null) ?? null,\n status: row.status as FactoryPendingStartRecord['status'],\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n constructor() {\n super('work-items');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([WORK_ITEMS_SCHEMA, ...FACTORY_GOVERNANCE_SCHEMAS]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_items', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #withProjectRelationTransaction<T>(\n orgId: string,\n factoryProjectId: string,\n fn: (ops: FactoryStorageOps) => Promise<T>,\n ): Promise<T> {\n const key = `work-items:${orgId}:${factoryProjectId}`;\n return withInProcessProjectLock(key, () => this.storage.withTransaction(fn, { isolationLevel: 'serializable' }));\n }\n\n async #claimLeases<T>(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryLeaseClaimInput,\n map: (row: GovernanceDbRow) => T,\n ): Promise<T[]> {\n const claim = () =>\n this.storage.withTransaction(async ops => {\n const candidates = await ops.findMany<GovernanceDbRow>(table, {}, { orderBy: [['created_at', 'asc']] });\n const claimed: T[] = [];\n for (const candidate of candidates) {\n if (claimed.length >= input.limit) break;\n const availableAt = new Date(candidate.available_at as Date | string).getTime();\n const leaseExpiresAt = candidate.lease_expires_at\n ? new Date(candidate.lease_expires_at as Date | string).getTime()\n : 0;\n const claimable =\n (candidate.status === 'pending' || candidate.status === 'retry') && availableAt <= input.now.getTime();\n const expired = candidate.status === 'leased' && leaseExpiresAt <= input.now.getTime();\n if (!claimable && !expired) continue;\n let didClaim = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(table, { id: candidate.id }, current => {\n const currentAvailable = new Date(current.available_at as Date | string).getTime();\n const currentExpiry = current.lease_expires_at\n ? new Date(current.lease_expires_at as Date | string).getTime()\n : 0;\n const currentClaimable =\n (current.status === 'pending' || current.status === 'retry') && currentAvailable <= input.now.getTime();\n const currentExpired = current.status === 'leased' && currentExpiry <= input.now.getTime();\n if (!currentClaimable && !currentExpired) return null;\n didClaim = true;\n return {\n status: 'leased',\n attempts: Number(current.attempts) + 1,\n lease_owner: input.ownerId,\n lease_expires_at: input.leaseExpiresAt,\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n return claimed;\n });\n return claim();\n }\n\n async #renewLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n leaseExpiresAt: Date,\n ): Promise<boolean> {\n let renewed = false;\n await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n renewed = true;\n return { lease_expires_at: leaseExpiresAt, updated_at: new Date() };\n },\n );\n return renewed;\n }\n\n async #completeLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<GovernanceDbRow | null> {\n let completed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n completed = true;\n return {\n status: table === 'factory_pending_starts' ? 'sent' : 'succeeded',\n lease_owner: null,\n lease_expires_at: null,\n completed_at: now,\n updated_at: now,\n };\n },\n );\n return completed ? row : null;\n }\n\n async #failLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryDispatchFailureInput,\n ): Promise<GovernanceDbRow | null> {\n let failed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: input.id, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== input.ownerId) return null;\n failed = true;\n return {\n status: input.terminal ? 'failed' : 'retry',\n available_at: input.availableAt,\n lease_owner: null,\n lease_expires_at: null,\n last_error: input.lastError,\n completed_at: input.terminal ? input.now : null,\n updated_at: input.now,\n };\n },\n );\n return failed ? row : null;\n }\n\n async #listWithOps(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<WorkItemRow[]> {\n const rows = await ops.findMany<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toWorkItem);\n }\n\n /** List the org's work items for a project, newest first. */\n async list({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<WorkItemRow[]> {\n return this.#listWithOps(this.#db, orgId, factoryProjectId);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n return row ? toWorkItem(row) : null;\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', {\n id,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toRow(row) : null;\n }\n\n async getTransitionResultByIngress(\n orgId: string,\n factoryProjectId: string,\n identity: string,\n ): Promise<Record<string, unknown> | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity,\n });\n return (row?.result as Record<string, unknown> | undefined) ?? null;\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.storage.withTransaction<CommitFactoryTransitionResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior)\n return {\n status: 'replayed',\n item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),\n result: prior.result as Record<string, unknown>,\n };\n\n const now = new Date();\n let item: WorkItemRow | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n },\n row => {\n const existing = toRow(row);\n item = existing;\n if (existing.revision !== input.expectedRevision) {\n code = 'stale';\n reason = 'The work item changed before this transition committed.';\n return null;\n }\n if (input.evaluation.outcome === 'rejected') {\n code = input.evaluation.code;\n reason = input.evaluation.reason;\n return null;\n }\n if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) return null;\n return patchColumns({\n stages: [input.destinationStage],\n stageHistory: applyStageTransition(\n existing.stageHistory,\n existing.stages,\n [input.destinationStage],\n input.actorId,\n now,\n ),\n revision: existing.revision + 1,\n updatedAt: now,\n });\n },\n );\n if (updated) item = toRow(updated);\n if (!item) {\n code = input.evaluation.outcome === 'rejected' ? input.evaluation.code : 'invalid_transition';\n reason = input.evaluation.outcome === 'rejected' ? input.evaluation.reason : 'Work item not found.';\n }\n const outcome: 'accepted' | 'rejected' =\n item && code === null && input.evaluation.outcome === 'accepted' ? 'accepted' : 'rejected';\n result =\n outcome === 'accepted'\n ? {\n status: 'accepted',\n transitionId: input.ingress.transitionId,\n itemId: item!.id,\n revision: item!.revision,\n stage: input.destinationStage,\n decisions: input.evaluation.outcome === 'accepted' ? input.evaluation.decisions : [],\n }\n : { status: 'rejected', transitionId: input.ingress.transitionId, itemId: input.workItemId, code, reason };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.transitionId,\n result,\n created_at: now,\n });\n if (item) {\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item.id,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: now,\n });\n if (outcome === 'accepted' && input.evaluation.outcome === 'accepted') {\n for (const [index, decision] of input.evaluation.decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item.id,\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: index,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: null,\n decision,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(now.getTime() + index),\n updated_at: now,\n });\n }\n }\n }\n return { status: 'committed', item, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async commitRuleEvaluation(input: CommitFactoryRuleEvaluationInput): Promise<CommitFactoryRuleEvaluationResult> {\n const commit = () =>\n this.storage.withTransaction<CommitFactoryRuleEvaluationResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior) {\n const result = prior.result as Record<string, unknown>;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: prior.id });\n for (const decision of decisions) {\n if (\n !evaluation ||\n !decision ||\n typeof decision !== 'object' ||\n (decision as Record<string, unknown>).type !== 'upsertLinkedWorkItem' ||\n typeof (decision as Record<string, unknown>).sourceKey !== 'string' ||\n typeof (decision as Record<string, unknown>).idempotencyKey !== 'string'\n ) {\n continue;\n }\n const materialization = decision as Record<string, unknown> & { sourceKey: string; idempotencyKey: string };\n const item = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: materialization.sourceKey,\n });\n if (item) continue;\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n idempotency_key: materialization.idempotencyKey,\n },\n current =>\n current.status === 'succeeded'\n ? {\n status: 'retry',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: input.now,\n }\n : null,\n );\n }\n return { status: 'replayed' as const, result };\n }\n const itemRow = input.workItemId\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : null;\n if (input.workItemId !== null && !itemRow) return { status: 'missing' as const };\n const item = itemRow ? toRow(itemRow) : null;\n const stale = item !== null && item.revision !== input.expectedRevision;\n const outcome = stale ? 'rejected' : input.outcome.status;\n const code = stale ? 'stale' : (input.outcome.code ?? null);\n const reason = stale\n ? 'The work item changed before this rule evaluation committed.'\n : (input.outcome.reason ?? null);\n const decisions = outcome === 'accepted' ? input.decisions : [];\n const result = {\n status: outcome,\n itemId: item?.id ?? null,\n revision: item?.revision ?? null,\n code,\n reason,\n decisions,\n };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.identity,\n result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item?.id ?? null,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item?.id ?? null,\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: effectOrdinal,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: input.actor,\n decision,\n status: 'pending',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(input.now.getTime() + effectOrdinal),\n updated_at: input.now,\n });\n }\n return { status: 'committed' as const, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async getToolResultCursor(\n orgId: string,\n factoryProjectId: string,\n bindingId: string,\n ): Promise<FactoryToolResultCursorRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_tool_result_cursors', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n binding_id: bindingId,\n });\n return row\n ? {\n bindingId: String(row.binding_id),\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n lastMessageId: String(row.last_message_id),\n lastMessageCreatedAt: row.last_message_created_at as Date,\n updatedAt: row.updated_at as Date,\n }\n : null;\n }\n\n async advanceToolResultCursor(cursor: FactoryToolResultCursorRecord): Promise<void> {\n const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);\n if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;\n await this.#db.upsertOne<GovernanceDbRow>('factory_tool_result_cursors', ['binding_id'], {\n binding_id: cursor.bindingId,\n org_id: cursor.orgId,\n factory_project_id: cursor.factoryProjectId,\n last_message_id: cursor.lastMessageId,\n last_message_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(orgId: string, factoryProjectId: string): Promise<FactoryDeferredDecisionRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toDeferredDecision);\n }\n\n /** Read a bounded newest-first status page without exposing another tenant. */\n async listDeferredDecisionPage(input: FactoryDeferredDecisionPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n ...(input.statuses ? { status: { in: input.statuses } } : {}),\n },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n async claimDeferredDecisions(input: FactoryLeaseClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision);\n }\n\n async renewDeferredDecisionLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_deferred_decisions', identity, leaseExpiresAt);\n }\n\n async completeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now);\n return row ? toDeferredDecision(row) : null;\n }\n\n async failDeferredDecision(input: FactoryDispatchFailureInput): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#failLease('factory_deferred_decisions', input);\n return row ? toDeferredDecision(row) : null;\n }\n\n /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let retried = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n retried = true;\n return {\n status: 'retry',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: now,\n };\n },\n );\n return retried && row ? toDeferredDecision(row) : null;\n }\n\n /** Resolve exact active agent authority; partial session matches never authorize. */\n async findActiveRunBinding(address: FactoryRunBindingAddress): Promise<FactoryRunBindingRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: address.orgId,\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n status: 'active',\n });\n return row ? toBinding(row) : null;\n }\n\n /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */\n async findRunBindingBySession(address: FactoryRunBindingSessionAddress): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n });\n if (new Set(rows.map(row => row.org_id)).size !== 1) return null;\n const row = rows.sort((left, right) => {\n if (left.status === 'active' && right.status !== 'active') return -1;\n if (right.status === 'active' && left.status !== 'active') return 1;\n return right.created_at.getTime() - left.created_at.getTime();\n })[0];\n return row ? toBinding(row) : null;\n }\n\n /** Revoke one exact tenant-scoped binding. */\n async revokeRunBinding(input: RevokeFactoryRunBindingInput): Promise<FactoryRunBindingRecord | null> {\n let revoked = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_run_bindings',\n { id: input.bindingId, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'active') return null;\n revoked = true;\n return { status: 'revoked', revoked_at: input.revokedAt };\n },\n );\n return revoked && row ? toBinding(row) : null;\n }\n\n /** Enumerate active bindings for the server-owned restart reconciler. */\n async listActiveRunBindings(): Promise<FactoryRunBindingRecord[]> {\n return (await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { status: 'active' })).map(toBinding);\n }\n\n /** List binding history, optionally narrowed to one work item. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string,\n ): Promise<FactoryRunBindingRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_run_bindings',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(workItemId ? { work_item_id: workItemId } : {}),\n },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toBinding);\n }\n\n async listPendingStarts(orgId: string, factoryProjectId: string): Promise<FactoryPendingStartRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_pending_starts',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toPendingStart);\n }\n\n async claimPendingStarts(input: FactoryLeaseClaimInput): Promise<FactoryPendingStartRecord[]> {\n return this.#claimLeases('factory_pending_starts', input, toPendingStart);\n }\n\n async renewPendingStartLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_pending_starts', identity, leaseExpiresAt);\n }\n\n async completePendingStart(identity: FactoryLeaseIdentity, now: Date): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#completeLease('factory_pending_starts', identity, now);\n return row ? toPendingStart(row) : null;\n }\n\n async failPendingStart(input: FactoryDispatchFailureInput): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#failLease('factory_pending_starts', input);\n return row ? toPendingStart(row) : null;\n }\n\n async prepareRunStart(input: PrepareFactoryRunStartInput): Promise<PrepareFactoryRunStartResult> {\n const prepare = () =>\n this.storage.withTransaction(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n kickoff_key: input.kickoffKey,\n });\n if (prior) {\n const bindingRow = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: String(prior.binding_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n const itemRow =\n bindingRow &&\n (await ops.findOne<WorkItemDbRow>('work_items', {\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n if (!bindingRow || !itemRow) throw new Error('Factory start replay references missing state.');\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : sourceKey(create.externalSource)\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey(create.externalSource),\n })\n : null;\n let item: WorkItemRow;\n if (row) {\n row = await ops.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n const roles = new Set([...Object.keys(current.sessions), input.role]);\n const sessions = Object.fromEntries([...roles].map(role => [role, input.session]));\n return applyUpdate({ current, userId: input.userId, input: { sessions } });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await ops.findMany<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n created_by: input.userId,\n factory_project_id: input.factoryProjectId,\n external_source: create.externalSource ?? null,\n source_key: sourceKey(create.externalSource),\n parent_work_item_id: create.parentWorkItemId ?? null,\n title: create.title,\n stages: create.stages ?? [],\n stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),\n sessions: stampSessions({ [input.role]: input.session }, input.userId),\n metadata: create.metadata ?? null,\n revision: 1,\n created_at: now,\n updated_at: now,\n });\n item = toRow(row);\n }\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n const bindingRow = await ops.insertOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n branch: input.session.branch,\n status: 'active',\n created_at: now,\n revoked_at: null,\n });\n const pendingRow = await ops.insertOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n binding_id: bindingRow.id,\n kickoff_key: input.kickoffKey,\n message: input.kickoffMessage,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: now,\n updated_at: now,\n });\n return { item, binding: toBinding(bindingRow), pendingStart: toPendingStart(pendingRow), replayed: false };\n });\n try {\n return await prepare();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return prepare();\n }\n }\n\n async markPendingStart(\n bindingId: string,\n status: 'sent' | 'failed',\n lastError?: string,\n ): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, last_error: lastError ?? null, updated_at: new Date() }),\n );\n return row ? toPendingStart(row) : null;\n }\n\n /**\n * Create a work item, reusing the existing record when `sourceKey` already\n * has one for the project (acting twice on the same issue must not duplicate\n * the card). On reuse the provided stages replace the current ones (with the\n * transition recorded in history) and sessions/metadata are merged in. The\n * result discriminates insert from reuse so callers can audit the actual\n * outcome.\n */\n async upsert(params: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n }): Promise<UpsertWorkItemResult> {\n const run = (ops: FactoryStorageOps) => this.#upsert(params, ops);\n const execute = () =>\n params.input.parentWorkItemId\n ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run)\n : run(this.#db);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return execute();\n }\n }\n\n async #upsert(\n {\n orgId,\n userId,\n factoryProjectId,\n input,\n reuseMode = 'update',\n }: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n },\n ops: FactoryStorageOps,\n ): Promise<UpsertWorkItemResult> {\n const key = sourceKey(input.externalSource);\n const reuse = async (): Promise<UpsertWorkItemResult | null> => {\n if (!key) return null;\n const existing = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n const item = toWorkItem(existing);\n return { created: false, item, previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId, source_key: key },\n async current => {\n previous = priorState(current);\n const fullPatch = input.parentWorkItemId === null ? { ...input, parentWorkItemId: undefined } : input;\n const patch: UpdateWorkItemInput =\n reuseMode === 'non-stage'\n ? {\n title: input.title,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return {\n external_source: input.externalSource ?? null,\n ...applyUpdate({ current, userId, input: patch }),\n };\n },\n );\n return updated ? { item: toWorkItem(updated), created: false, previous } : null;\n };\n\n const reused = await reuse();\n if (reused) return reused;\n\n const now = new Date();\n const stages = input.stages ?? ['intake'];\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n undefined,\n input.parentWorkItemId ?? null,\n );\n const row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n external_source: input.externalSource ?? null,\n source_key: key,\n parent_work_item_id: input.parentWorkItemId ?? null,\n title: input.title,\n stages,\n stage_history: stages.map(stage => ({ stage, enteredAt: now.toISOString(), by: userId })),\n sessions: stampSessions(input.sessions ?? {}, userId),\n metadata: input.metadata ?? null,\n revision: 1,\n created_by: userId,\n created_at: now,\n updated_at: now,\n });\n return { item: toWorkItem(row), created: true, previous: emptyPrior() };\n }\n\n async update({\n orgId,\n id,\n userId,\n patch,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: UpdateWorkItemInput;\n }): Promise<{ item: WorkItemRow; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n previous = priorState(current);\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return applyUpdate({ current, userId, input: patch });\n });\n return row ? { item: toWorkItem(row), previous } : null;\n };\n\n if (patch.parentWorkItemId === undefined) return run(this.#db);\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);\n }\n\n async delete({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await ops.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!existing) return null;\n const deleted = await ops.deleteMany('work_items', { org_id: orgId, id });\n if (deleted === 0) return null;\n await ops.updateMany(\n 'work_items',\n { org_id: orgId, parent_work_item_id: id },\n { parent_work_item_id: null, updated_at: new Date() },\n );\n return toWorkItem(existing);\n });\n }\n}\n","/**\n * Aggregation math for the Factory Metrics page.\n *\n * Pure functions over `work_items` rows — flow metrics (throughput, cycle\n * time, stage durations, WIP, aging WIP) plus demand mix, all derived from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n */\n\nimport { isAutomationActor } from './base.js';\nimport type { WorkItemRow, WorkItemStageEntry } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/** Terminal stage — items here count as completed, not in-flight. */\nconst DONE_STAGE = 'done';\n\n/** Terminal stage for tracked non-completions — never a completion. */\nconst CANCELED_STAGE = 'canceled';\n\n/**\n * Terminal stages — items holding only these are not in-flight. `done` is a\n * completion (feeds throughput/cycle time); `canceled` is a tracked\n * non-completion outcome and feeds neither.\n */\nconst TERMINAL_STAGES = new Set([DONE_STAGE, CANCELED_STAGE]);\n\nconst AGING_WIP_LIMIT = 10;\n\nexport interface FactoryMetrics {\n windowDays: number;\n /** Earliest work-item creation time (ISO, window-independent) — the natural\n * lower bound for a date-range control. `null` when the board is empty. */\n earliestItemAt: string | null;\n /** Items reaching `done` per UTC day, gap-filled across the window. */\n throughput: { date: string; count: number }[];\n /** Card creation → `done` duration for items completed in the window. */\n cycleTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Median time spent per stage, over visits that ended inside the window. */\n stageDurations: { stage: string; medianMs: number; samples: number }[];\n /** Current cards per stage (window-independent). */\n wip: { stage: string; count: number }[];\n /** Distinct in-flight cards (at least one non-terminal stage). */\n wipTotal: number;\n /** Oldest in-flight cards by time in their current stage. */\n agingWip: { id: string; title: string; stage: string; enteredAt: string; url: string | null }[];\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Stage moves in the window: human-performed vs total. */\n transitions: { human: number; total: number };\n /** Per-stage automation over completed visits that exited in the window. */\n stageAutomation: {\n stage: string;\n /** Completed visits (entered+exited) to this stage that exited in the window. */\n exits: number;\n /**\n * Of those: clean automated passes — the item's first visit to the stage,\n * entered *and* exited by an automation actor. Missing `exitedBy` (entries\n * written before exit stamping) counts as human.\n */\n automated: number;\n /**\n * Outcomes of the automated passes' items, mutually exclusive, first match\n * wins: `reworked` (a later visit to the same stage exists — deliberately\n * outranks `done`: an automated pass that needed a redo is an automation\n * failure even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n return Number.isNaN(time) ? 0 : time;\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/**\n * The item's completion time: the `enteredAt` of its still-open `done` entry.\n * `undefined` when the item isn't currently done (including when it was pulled\n * back out of done — that visit has `exitedAt` and doesn't count).\n */\nfunction completedAt(item: WorkItemRow): number | undefined {\n if (!item.stages.includes(DONE_STAGE)) return undefined;\n for (let i = item.stageHistory.length - 1; i >= 0; i--) {\n const entry = item.stageHistory[i]!;\n if (entry.stage === DONE_STAGE && entry.exitedAt === undefined) return parseTime(entry.enteredAt);\n }\n return undefined;\n}\n\n/** Open (no `exitedAt`) history entry for a currently-held non-terminal stage. */\nfunction openEntries(item: WorkItemRow): WorkItemStageEntry[] {\n return item.stageHistory.filter(\n entry => entry.exitedAt === undefined && !TERMINAL_STAGES.has(entry.stage) && item.stages.includes(entry.stage),\n );\n}\n\nexport function computeFactoryMetrics(\n items: WorkItemRow[],\n opts: { windowStart: number; windowEnd: number },\n): FactoryMetrics {\n const { windowStart, windowEnd } = opts;\n\n // Earliest creation across all items (window-independent) — the range lower bound.\n let earliest = Infinity;\n for (const item of items) earliest = Math.min(earliest, item.createdAt.getTime());\n const earliestItemAt = Number.isFinite(earliest) ? new Date(earliest).toISOString() : null;\n\n // ── Throughput + cycle time (completed in window) ─────────────────────────\n // Gap-fill every UTC calendar date intersecting the half-open window.\n const throughputByDay = new Map<string, number>();\n const firstDay = utcDayStart(windowStart);\n for (let day = firstDay; day < windowEnd; day += DAY_MS) {\n throughputByDay.set(utcDay(day), 0);\n }\n const cycleSamples: number[] = [];\n for (const item of items) {\n const doneAt = completedAt(item);\n if (doneAt === undefined || doneAt < windowStart || doneAt >= windowEnd) continue;\n const day = utcDay(doneAt);\n throughputByDay.set(day, (throughputByDay.get(day) ?? 0) + 1);\n cycleSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n\n // ── Stage durations (visits that ended in window) ─────────────────────────\n const durationsByStage = new Map<string, number[]>();\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (entry.exitedAt === undefined || TERMINAL_STAGES.has(entry.stage)) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n const duration = Math.max(0, exited - parseTime(entry.enteredAt));\n const samples = durationsByStage.get(entry.stage) ?? [];\n samples.push(duration);\n durationsByStage.set(entry.stage, samples);\n }\n }\n\n // ── Current WIP + aging (window-independent) ──────────────────────────────\n const wipByStage = new Map<string, number>();\n let wipTotal = 0;\n const aging: FactoryMetrics['agingWip'] = [];\n for (const item of items) {\n for (const stage of item.stages) {\n wipByStage.set(stage, (wipByStage.get(stage) ?? 0) + 1);\n }\n const inFlightStages = item.stages.filter(stage => !TERMINAL_STAGES.has(stage));\n if (inFlightStages.length === 0) continue;\n wipTotal += 1;\n // Age the card by its longest-held current stage; fall back to creation\n // time if history is missing an open entry (shouldn't happen — history is\n // server-appended).\n const open = openEntries(item);\n const oldest = open.reduce<WorkItemStageEntry | undefined>(\n (best, entry) => (!best || parseTime(entry.enteredAt) < parseTime(best.enteredAt) ? entry : best),\n undefined,\n );\n aging.push({\n id: item.id,\n title: item.title,\n stage: oldest?.stage ?? inFlightStages[0]!,\n enteredAt: oldest?.enteredAt ?? item.createdAt.toISOString(),\n url: item.externalSource?.url ?? null,\n });\n }\n aging.sort((a, b) => parseTime(a.enteredAt) - parseTime(b.enteredAt));\n\n // ── Demand mix + transitions (window) ─────────────────────────────────────\n const sourceCounts = new Map<string, number>();\n let transitionsTotal = 0;\n let transitionsHuman = 0;\n for (const item of items) {\n if (item.createdAt.getTime() >= windowStart && item.createdAt.getTime() < windowEnd) {\n const source = item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}`\n : 'manual';\n sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1);\n }\n for (const entry of item.stageHistory) {\n const entered = parseTime(entry.enteredAt);\n if (entered < windowStart || entered >= windowEnd) continue;\n transitionsTotal += 1;\n if (!isAutomationActor(entry.by)) transitionsHuman += 1;\n }\n }\n\n // ── Per-stage automation (completed visits that exited in window) ─────────\n // Rows appear in insertion order of each stage's first counted exit;\n // terminal stages never get rows (they have no meaningful \"pass through\").\n const automationByStage = new Map<string, FactoryMetrics['stageAutomation'][number]>();\n for (const item of items) {\n const itemDone = completedAt(item) !== undefined;\n const itemCanceled = item.stages.includes(CANCELED_STAGE);\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (entry.exitedAt === undefined || TERMINAL_STAGES.has(entry.stage)) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n let row = automationByStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n exits: 0,\n automated: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n automationByStage.set(entry.stage, row);\n }\n row.exits += 1;\n // A clean automated pass: automation entered AND exited it, and this is\n // the item's first visit to the stage (a re-run is rework, not clean\n // automation). Missing `exitedBy` → human-exited → not automated.\n const firstVisitIndex = item.stageHistory.findIndex(e => e.stage === entry.stage);\n if (firstVisitIndex !== i || !isAutomationActor(entry.by) || !isAutomationActor(entry.exitedBy)) continue;\n row.automated += 1;\n const reworked = item.stageHistory.some((e, j) => j > i && e.stage === entry.stage);\n if (reworked) row.outcomes.reworked += 1;\n else if (itemDone) row.outcomes.done += 1;\n else if (itemCanceled) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n\n return {\n windowDays: throughputByDay.size,\n earliestItemAt,\n throughput: [...throughputByDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n cycleTime: {\n medianMs: percentile(cycleSamples, 0.5),\n p90Ms: percentile(cycleSamples, 0.9),\n samples: cycleSamples.length,\n },\n stageDurations: [...durationsByStage.entries()].map(([stage, samples]) => ({\n stage,\n medianMs: percentile(samples, 0.5)!,\n samples: samples.length,\n })),\n wip: [...wipByStage.entries()].map(([stage, count]) => ({ stage, count })),\n wipTotal,\n agingWip: aging.slice(0, AGING_WIP_LIMIT),\n sourceMix: [...sourceCounts.entries()]\n .map(([source, count]) => ({ source, count }))\n .sort((a, b) => b.count - a.count),\n transitions: { human: transitionsHuman, total: transitionsTotal },\n stageAutomation: [...automationByStage.values()],\n };\n}\n"],"mappings":";AAUA,SAAS,kBAAkB;AAE3B,SAAS,sBAAsB,4BAA4B;AA8CpD,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQM,SAAS,kBAAkB,IAAiC;AACjE,MAAI,OAAO,OAAW,QAAO;AAC7B,SAAO,kBAAkB,IAAI,EAAE,KAAK,GAAG,WAAW,QAAQ,KAAK,GAAG,WAAW,SAAS;AACxF;;;AC9DO,IAAM,yBAAyB;AAE/B,IAAM,qBAAqB;AAElC,IAAM,SAAS;AAGf,IAAM,aAAa;AA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AAO,EAAE,OAAO,MAAM,EAAE;AAAA,IACzE;AAAA,IACA,UAAU,MAAM,MAAM,GAAG,eAAe;AAAA,IACxC,WAAW,CAAC,GAAG,aAAa,QAAQ,CAAC,EAClC,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,EAAE,QAAQ,MAAM,EAAE,EAC5C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAAA,IACnC,aAAa,EAAE,OAAO,kBAAkB,OAAO,iBAAiB;AAAA,IAChE,iBAAiB,CAAC,GAAG,kBAAkB,OAAO,CAAC;AAAA,EACjD;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/storage/domains/work-items/base.ts","../../../../src/storage/domains/work-items/metrics.ts"],"sourcesContent":["/**\n * Factory work-items storage domain.\n *\n * Work items belong to a first-class Factory project. External intake items use\n * a provider-neutral source reference; manual work items have no source.\n * Stage history is server-owned, while session and metadata patches merge\n * atomically so concurrent actors do not overwrite each other. The authoritative\n * Factory transition path keeps one exclusive current stage per item.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport type WorkItemStage = string;\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nexport function factoryDecisionHash(decision: Record<string, unknown>): string {\n return createHash('sha256').update(stableJson(decision)).digest('hex');\n}\n\nexport interface ExternalWorkItemSource {\n integrationId: string;\n type: string;\n externalId: string;\n url?: string;\n}\n\nexport interface WorkItemStageEntry {\n stage: WorkItemStage;\n enteredAt: string;\n exitedAt?: string;\n by: string;\n /**\n * Actor that closed this entry; absent on entries written before exit\n * stamping existed — treat as human.\n */\n exitedBy?: string;\n}\n\n/**\n * Sentinel actor ids that mark a stage transition as automation-driven (vs a\n * human's WorkOS user id): generic sentinels plus the system ids the Factory\n * rules engine stamps (see `actorId` in factory/rules/transition-service.ts).\n * Metrics treat any other actor — including a missing `exitedBy` on\n * pre-existing entries — as human.\n */\nexport const AUTOMATION_ACTORS = new Set([\n 'factory',\n 'system',\n 'automation',\n 'factory-rule-dispatcher',\n 'factory-tool-result-rule',\n]);\n\n/**\n * Whether an actor id marks a transition no human performed on the Factory\n * board: a sentinel automation id, an agent binding (`agent:*`), or an\n * external-webhook actor (`github:*` — a human may have acted on GitHub, but\n * the board move itself was automated).\n */\nexport function isAutomationActor(by: string | undefined): boolean {\n if (by === undefined) return false;\n return AUTOMATION_ACTORS.has(by) || by.startsWith('agent:') || by.startsWith('github:');\n}\n\nexport interface WorkItemSessionRef {\n sessionId: string;\n branch: string;\n threadId: string;\n startedBy: string;\n}\n\nexport interface FactoryRuleIngressRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n identity: string;\n triggerType: string;\n transitionId: string;\n result: Record<string, unknown>;\n createdAt: Date;\n}\n\nexport interface CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: string; triggerType: string };\n ruleSetVersion: string;\n expectedRevision: number | null;\n actor: Record<string, unknown> | null;\n outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string };\n decisions: Record<string, unknown>[];\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n now: Date;\n}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageId: string;\n lastMessageCreatedAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRuleEvaluationRecord {\n id: string;\n ingressId: string;\n workItemId: string | null;\n ruleSetVersion: string;\n expectedRevision: number | null;\n outcome: 'accepted' | 'rejected';\n code: string | null;\n reason: string | null;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n createdAt: Date;\n}\n\nexport type FactoryDispatchStatus = 'pending' | 'leased' | 'retry' | 'succeeded' | 'failed';\n\nexport interface FactoryDeferredDecisionPageInput {\n orgId: string;\n factoryProjectId: string;\n statuses?: FactoryDispatchStatus[];\n before?: { createdAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionPage {\n decisions: FactoryDeferredDecisionRecord[];\n hasMore: boolean;\n}\n\nexport interface FactoryDeferredDecisionRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n evaluationId: string;\n workItemId: string | null;\n idempotencyKey: string;\n effectOrdinal: number;\n effectHash: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n actor: Record<string, unknown> | null;\n decision: Record<string, unknown>;\n status: FactoryDispatchStatus;\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRunBindingSessionAddress {\n factoryProjectId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n}\n\nexport interface FactoryRunBindingAddress extends FactoryRunBindingSessionAddress {\n orgId: string;\n}\n\nexport interface RevokeFactoryRunBindingInput {\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n revokedAt: Date;\n}\n\nexport interface FactoryRunBindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n status: 'active' | 'revoked';\n createdAt: Date;\n revokedAt: Date | null;\n}\n\nexport interface FactoryPendingStartRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n kickoffKey: string;\n message: string | null;\n status: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryLeaseClaimInput {\n ownerId: string;\n now: Date;\n leaseExpiresAt: Date;\n limit: number;\n}\n\nexport interface FactoryLeaseIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n ownerId: string;\n}\n\nexport interface FactoryDispatchFailureInput extends FactoryLeaseIdentity {\n now: Date;\n availableAt: Date;\n lastError: string;\n terminal: boolean;\n}\n\nexport interface CommitFactoryTransitionInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n expectedRevision: number;\n destinationStage: string;\n actorId: string;\n ingress: { identity: string; triggerType: string; transitionId: string };\n ruleSetVersion: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n}\n\nexport type CommitFactoryTransitionResult =\n | { status: 'committed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: WorkItemRow;\n binding: FactoryRunBindingRecord;\n pendingStart: FactoryPendingStartRecord;\n replayed: boolean;\n}\n\n/** Session ref as accepted from clients — `startedBy` is stamped server-side. */\nexport interface WorkItemSessionInput {\n sessionId: string;\n branch: string;\n threadId: string;\n}\n\nexport type WorkItemSessions = Record<string, WorkItemSessionRef>;\n\nexport interface WorkItemRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemInput {\n externalSource?: ExternalWorkItemSource | null;\n parentWorkItemId?: string | null;\n title: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface UpdateWorkItemInput {\n parentWorkItemId?: string | null;\n title?: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: WorkItemRow;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_updated_at_idx',\n columns: ['org_id', 'factory_project_id', 'updated_at'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n ],\n};\n\ninterface WorkItemDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n stages: WorkItemStage[];\n stage_history: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction sourceKey(source: ExternalWorkItemSource | null | undefined): string | null {\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction toWorkItem(row: WorkItemDbRow): WorkItemRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n externalSource: row.external_source,\n parentWorkItemId: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<WorkItemRow>): Partial<WorkItemDbRow> {\n return {\n ...(changes.parentWorkItemId !== undefined ? { parent_work_item_id: changes.parentWorkItemId } : {}),\n ...(changes.title !== undefined ? { title: changes.title } : {}),\n ...(changes.stages !== undefined ? { stages: changes.stages } : {}),\n ...(changes.stageHistory !== undefined ? { stage_history: changes.stageHistory } : {}),\n ...(changes.sessions !== undefined ? { sessions: changes.sessions } : {}),\n ...(changes.metadata !== undefined ? { metadata: changes.metadata } : {}),\n ...(changes.revision !== undefined ? { revision: changes.revision } : {}),\n ...(changes.updatedAt !== undefined ? { updated_at: changes.updatedAt } : {}),\n };\n}\n\nfunction emptyPrior(): WorkItemPriorState {\n return { stages: [], sessionRoles: [] };\n}\n\nfunction priorState(row: WorkItemDbRow): WorkItemPriorState {\n return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };\n}\n\nexport class WorkItemRelationError extends Error {\n readonly code = 'invalid_work_item_relation';\n}\n\nexport function validateParentRelation(\n projectItems: WorkItemRow[],\n itemId: string | undefined,\n parentWorkItemId: string | null,\n): void {\n if (parentWorkItemId === null) return;\n const byId = new Map(projectItems.map(item => [item.id, item]));\n const parent = byId.get(parentWorkItemId);\n if (!parent) throw new WorkItemRelationError('Related work item not found in this project.');\n if (itemId === parentWorkItemId) throw new WorkItemRelationError('A work item cannot relate to itself.');\n\n const visited = new Set<string>();\n let cursor: WorkItemRow | undefined = parent;\n while (cursor?.parentWorkItemId) {\n if (cursor.parentWorkItemId === itemId) {\n throw new WorkItemRelationError('This relationship would create a cycle.');\n }\n if (visited.has(cursor.id)) throw new WorkItemRelationError('The related work item chain contains a cycle.');\n visited.add(cursor.id);\n cursor = byId.get(cursor.parentWorkItemId);\n }\n}\n\n/**\n * Diff `oldStages` → `newStages` and return the updated history: exited stages\n * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get\n * a new entry.\n */\nexport function applyStageTransition(\n history: WorkItemStageEntry[],\n oldStages: WorkItemStage[],\n newStages: WorkItemStage[],\n by: string,\n now: Date,\n): WorkItemStageEntry[] {\n const timestamp = now.toISOString();\n const next = history.map(entry => ({ ...entry }));\n for (const stage of oldStages) {\n if (newStages.includes(stage)) continue;\n for (let i = next.length - 1; i >= 0; i--) {\n const entry = next[i]!;\n if (entry.stage === stage && entry.exitedAt === undefined) {\n entry.exitedAt = timestamp;\n entry.exitedBy = by;\n break;\n }\n }\n }\n for (const stage of newStages) {\n if (!oldStages.includes(stage)) next.push({ stage, enteredAt: timestamp, by });\n }\n return next;\n}\n\nexport function stampSessions(sessions: Record<string, WorkItemSessionInput>, by: string): WorkItemSessions {\n return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, { ...session, startedBy: by }]));\n}\n\nfunction applyUpdate({\n current,\n userId,\n input,\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n}): Partial<WorkItemDbRow> {\n const now = new Date();\n return {\n ...(input.parentWorkItemId !== undefined ? { parent_work_item_id: input.parentWorkItemId } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.stages !== undefined\n ? {\n stages: input.stages,\n stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now),\n }\n : {}),\n ...(input.sessions !== undefined\n ? { sessions: { ...current.sessions, ...stampSessions(input.sessions, userId) } }\n : {}),\n ...(input.metadata !== undefined\n ? { metadata: input.metadata === null ? null : { ...(current.metadata ?? {}), ...input.metadata } }\n : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\n\nconst projectRelationLocks = new Map<string, Promise<unknown>>();\n\nfunction withInProcessProjectLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = projectRelationLocks.get(key) ?? Promise.resolve();\n const result = previous.then(fn, fn);\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n projectRelationLocks.set(key, tail);\n void tail.then(() => {\n if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);\n });\n return result;\n}\n\nconst FACTORY_GOVERNANCE_SCHEMAS: CollectionSchema[] = [\n {\n name: 'factory_rule_ingress',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n identity: { type: 'text' },\n trigger_type: { type: 'text' },\n transition_id: { type: 'text' },\n result: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_rule_ingress_tenant_identity_unique', columns: ['org_id', 'factory_project_id', 'identity'] },\n ],\n },\n {\n name: 'factory_rule_evaluations',\n columns: {\n id: { type: 'uuid-pk' },\n ingress_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n rule_set_version: { type: 'text' },\n expected_revision: { type: 'integer', nullable: true },\n outcome: { type: 'text' },\n code: { type: 'text', nullable: true },\n reason: { type: 'text', nullable: true },\n causal_chain: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_deferred_decisions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n evaluation_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n idempotency_key: { type: 'text' },\n effect_ordinal: { type: 'integer' },\n effect_hash: { type: 'text' },\n causal_chain: { type: 'json' },\n actor: { type: 'json', nullable: true },\n decision: { type: 'json' },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_deferred_decisions_tenant_key_unique',\n columns: ['org_id', 'factory_project_id', 'idempotency_key'],\n },\n ],\n indexes: [{ name: 'factory_deferred_decisions_claim_idx', columns: ['status', 'created_at'] }],\n },\n {\n name: 'factory_run_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n role: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n session_id: { type: 'text' },\n branch: { type: 'text' },\n status: { type: 'text' },\n created_at: { type: 'timestamp' },\n revoked_at: { type: 'timestamp', nullable: true },\n },\n indexes: [\n // Exact-address lookups run on every processor message; status filter is\n // applied on top of the address columns.\n {\n name: 'factory_run_bindings_session_idx',\n columns: ['factory_project_id', 'thread_id', 'resource_id', 'session_id'],\n },\n // Restart reconciler enumerates active bindings across all tenants.\n { name: 'factory_run_bindings_status_idx', columns: ['status'] },\n ],\n },\n {\n name: 'factory_tool_result_cursors',\n columns: {\n binding_id: { type: 'text', primaryKey: true },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n last_message_id: { type: 'text' },\n last_message_created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_pending_starts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n binding_id: { type: 'text' },\n kickoff_key: { type: 'text' },\n message: { type: 'text', nullable: true },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_pending_starts_tenant_kickoff_unique',\n columns: ['org_id', 'factory_project_id', 'kickoff_key'],\n },\n ],\n indexes: [{ name: 'factory_pending_starts_claim_idx', columns: ['status', 'created_at'] }],\n },\n];\n\ninterface GovernanceDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n created_at: Date;\n [key: string]: unknown;\n}\n\nfunction toBinding(row: GovernanceDbRow): FactoryRunBindingRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: String(row.work_item_id),\n role: String(row.role),\n threadId: String(row.thread_id),\n resourceId: String(row.resource_id),\n sessionId: String(row.session_id),\n branch: String(row.branch),\n status: row.status as FactoryRunBindingRecord['status'],\n createdAt: row.created_at,\n revokedAt: (row.revoked_at as Date | null) ?? null,\n };\n}\nfunction toDeferredDecision(row: GovernanceDbRow): FactoryDeferredDecisionRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n evaluationId: String(row.evaluation_id),\n workItemId: row.work_item_id === null || row.work_item_id === undefined ? null : String(row.work_item_id),\n idempotencyKey: String(row.idempotency_key),\n effectOrdinal: Number(row.effect_ordinal),\n effectHash: String(row.effect_hash),\n causalChain: (row.causal_chain as FactoryDeferredDecisionRecord['causalChain']) ?? [],\n actor: (row.actor as Record<string, unknown> | null) ?? null,\n decision: row.decision as Record<string, unknown>,\n status: row.status as FactoryDispatchStatus,\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\nfunction toPendingStart(row: GovernanceDbRow): FactoryPendingStartRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n bindingId: String(row.binding_id),\n kickoffKey: String(row.kickoff_key),\n message: (row.message as string | null) ?? null,\n status: row.status as FactoryPendingStartRecord['status'],\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n constructor() {\n super('work-items');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([WORK_ITEMS_SCHEMA, ...FACTORY_GOVERNANCE_SCHEMAS]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_items', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #withProjectRelationTransaction<T>(\n orgId: string,\n factoryProjectId: string,\n fn: (ops: FactoryStorageOps) => Promise<T>,\n ): Promise<T> {\n const key = `work-items:${orgId}:${factoryProjectId}`;\n return withInProcessProjectLock(key, () => this.storage.withTransaction(fn, { isolationLevel: 'serializable' }));\n }\n\n async #claimLeases<T>(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryLeaseClaimInput,\n map: (row: GovernanceDbRow) => T,\n ): Promise<T[]> {\n const claim = () =>\n this.storage.withTransaction(async ops => {\n // Bounded candidate window: only rows in claimable/expirable statuses,\n // oldest first. Terminal rows (sent/succeeded/failed) accumulate over a\n // deployment's lifetime and must never be scanned per dispatch tick.\n const candidates = await ops.findMany<GovernanceDbRow>(\n table,\n { status: { in: ['pending', 'retry', 'leased'] } },\n { orderBy: [['created_at', 'asc']], limit: Math.max(input.limit * 5, 50) },\n );\n const claimed: T[] = [];\n for (const candidate of candidates) {\n if (claimed.length >= input.limit) break;\n const availableAt = new Date(candidate.available_at as Date | string).getTime();\n const leaseExpiresAt = candidate.lease_expires_at\n ? new Date(candidate.lease_expires_at as Date | string).getTime()\n : 0;\n const claimable =\n (candidate.status === 'pending' || candidate.status === 'retry') && availableAt <= input.now.getTime();\n const expired = candidate.status === 'leased' && leaseExpiresAt <= input.now.getTime();\n if (!claimable && !expired) continue;\n let didClaim = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(table, { id: candidate.id }, current => {\n const currentAvailable = new Date(current.available_at as Date | string).getTime();\n const currentExpiry = current.lease_expires_at\n ? new Date(current.lease_expires_at as Date | string).getTime()\n : 0;\n const currentClaimable =\n (current.status === 'pending' || current.status === 'retry') && currentAvailable <= input.now.getTime();\n const currentExpired = current.status === 'leased' && currentExpiry <= input.now.getTime();\n if (!currentClaimable && !currentExpired) return null;\n didClaim = true;\n return {\n status: 'leased',\n attempts: Number(current.attempts) + 1,\n lease_owner: input.ownerId,\n lease_expires_at: input.leaseExpiresAt,\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n return claimed;\n });\n return claim();\n }\n\n async #renewLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n leaseExpiresAt: Date,\n ): Promise<boolean> {\n let renewed = false;\n await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n renewed = true;\n return { lease_expires_at: leaseExpiresAt, updated_at: new Date() };\n },\n );\n return renewed;\n }\n\n async #completeLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<GovernanceDbRow | null> {\n let completed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n completed = true;\n return {\n status: table === 'factory_pending_starts' ? 'sent' : 'succeeded',\n lease_owner: null,\n lease_expires_at: null,\n completed_at: now,\n updated_at: now,\n };\n },\n );\n return completed ? row : null;\n }\n\n async #failLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryDispatchFailureInput,\n ): Promise<GovernanceDbRow | null> {\n let failed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: input.id, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== input.ownerId) return null;\n failed = true;\n return {\n status: input.terminal ? 'failed' : 'retry',\n available_at: input.availableAt,\n lease_owner: null,\n lease_expires_at: null,\n last_error: input.lastError,\n completed_at: input.terminal ? input.now : null,\n updated_at: input.now,\n };\n },\n );\n return failed ? row : null;\n }\n\n async #listWithOps(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<WorkItemRow[]> {\n const rows = await ops.findMany<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toWorkItem);\n }\n\n /** List the org's work items for a project, newest first. */\n async list({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<WorkItemRow[]> {\n return this.#listWithOps(this.#db, orgId, factoryProjectId);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n return row ? toWorkItem(row) : null;\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', {\n id,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toRow(row) : null;\n }\n\n async getTransitionResultByIngress(\n orgId: string,\n factoryProjectId: string,\n identity: string,\n ): Promise<Record<string, unknown> | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity,\n });\n return (row?.result as Record<string, unknown> | undefined) ?? null;\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.storage.withTransaction<CommitFactoryTransitionResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior)\n return {\n status: 'replayed',\n item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),\n result: prior.result as Record<string, unknown>,\n };\n\n const now = new Date();\n let item: WorkItemRow | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n },\n row => {\n const existing = toRow(row);\n item = existing;\n if (existing.revision !== input.expectedRevision) {\n code = 'stale';\n reason = 'The work item changed before this transition committed.';\n return null;\n }\n if (input.evaluation.outcome === 'rejected') {\n code = input.evaluation.code;\n reason = input.evaluation.reason;\n return null;\n }\n if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) return null;\n return patchColumns({\n stages: [input.destinationStage],\n stageHistory: applyStageTransition(\n existing.stageHistory,\n existing.stages,\n [input.destinationStage],\n input.actorId,\n now,\n ),\n revision: existing.revision + 1,\n updatedAt: now,\n });\n },\n );\n if (updated) item = toRow(updated);\n if (!item) {\n code = input.evaluation.outcome === 'rejected' ? input.evaluation.code : 'invalid_transition';\n reason = input.evaluation.outcome === 'rejected' ? input.evaluation.reason : 'Work item not found.';\n }\n const outcome: 'accepted' | 'rejected' =\n item && code === null && input.evaluation.outcome === 'accepted' ? 'accepted' : 'rejected';\n result =\n outcome === 'accepted'\n ? {\n status: 'accepted',\n transitionId: input.ingress.transitionId,\n itemId: item!.id,\n revision: item!.revision,\n stage: input.destinationStage,\n decisions: input.evaluation.outcome === 'accepted' ? input.evaluation.decisions : [],\n }\n : { status: 'rejected', transitionId: input.ingress.transitionId, itemId: input.workItemId, code, reason };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.transitionId,\n result,\n created_at: now,\n });\n if (item) {\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item.id,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: now,\n });\n if (outcome === 'accepted' && input.evaluation.outcome === 'accepted') {\n for (const [index, decision] of input.evaluation.decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item.id,\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: index,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: null,\n decision,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(now.getTime() + index),\n updated_at: now,\n });\n }\n }\n }\n return { status: 'committed', item, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async commitRuleEvaluation(input: CommitFactoryRuleEvaluationInput): Promise<CommitFactoryRuleEvaluationResult> {\n const commit = () =>\n this.storage.withTransaction<CommitFactoryRuleEvaluationResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior) {\n const result = prior.result as Record<string, unknown>;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: prior.id });\n for (const decision of decisions) {\n if (\n !evaluation ||\n !decision ||\n typeof decision !== 'object' ||\n (decision as Record<string, unknown>).type !== 'upsertLinkedWorkItem' ||\n typeof (decision as Record<string, unknown>).sourceKey !== 'string' ||\n typeof (decision as Record<string, unknown>).idempotencyKey !== 'string'\n ) {\n continue;\n }\n const materialization = decision as Record<string, unknown> & { sourceKey: string; idempotencyKey: string };\n const item = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: materialization.sourceKey,\n });\n if (item) continue;\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n idempotency_key: materialization.idempotencyKey,\n },\n current =>\n current.status === 'succeeded'\n ? {\n status: 'retry',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: input.now,\n }\n : null,\n );\n }\n return { status: 'replayed' as const, result };\n }\n const itemRow = input.workItemId\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : null;\n if (input.workItemId !== null && !itemRow) return { status: 'missing' as const };\n const item = itemRow ? toRow(itemRow) : null;\n const stale = item !== null && item.revision !== input.expectedRevision;\n const outcome = stale ? 'rejected' : input.outcome.status;\n const code = stale ? 'stale' : (input.outcome.code ?? null);\n const reason = stale\n ? 'The work item changed before this rule evaluation committed.'\n : (input.outcome.reason ?? null);\n const decisions = outcome === 'accepted' ? input.decisions : [];\n const result = {\n status: outcome,\n itemId: item?.id ?? null,\n revision: item?.revision ?? null,\n code,\n reason,\n decisions,\n };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.identity,\n result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item?.id ?? null,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item?.id ?? null,\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: effectOrdinal,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: input.actor,\n decision,\n status: 'pending',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(input.now.getTime() + effectOrdinal),\n updated_at: input.now,\n });\n }\n return { status: 'committed' as const, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async getToolResultCursor(\n orgId: string,\n factoryProjectId: string,\n bindingId: string,\n ): Promise<FactoryToolResultCursorRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_tool_result_cursors', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n binding_id: bindingId,\n });\n return row\n ? {\n bindingId: String(row.binding_id),\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n lastMessageId: String(row.last_message_id),\n lastMessageCreatedAt: row.last_message_created_at as Date,\n updatedAt: row.updated_at as Date,\n }\n : null;\n }\n\n async advanceToolResultCursor(cursor: FactoryToolResultCursorRecord): Promise<void> {\n const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);\n if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;\n await this.#db.upsertOne<GovernanceDbRow>('factory_tool_result_cursors', ['binding_id'], {\n binding_id: cursor.bindingId,\n org_id: cursor.orgId,\n factory_project_id: cursor.factoryProjectId,\n last_message_id: cursor.lastMessageId,\n last_message_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(orgId: string, factoryProjectId: string): Promise<FactoryDeferredDecisionRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toDeferredDecision);\n }\n\n /** Read a bounded newest-first status page without exposing another tenant. */\n async listDeferredDecisionPage(input: FactoryDeferredDecisionPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n ...(input.statuses ? { status: { in: input.statuses } } : {}),\n },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n async claimDeferredDecisions(input: FactoryLeaseClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision);\n }\n\n async renewDeferredDecisionLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_deferred_decisions', identity, leaseExpiresAt);\n }\n\n async completeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now);\n return row ? toDeferredDecision(row) : null;\n }\n\n async failDeferredDecision(input: FactoryDispatchFailureInput): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#failLease('factory_deferred_decisions', input);\n return row ? toDeferredDecision(row) : null;\n }\n\n /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let retried = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n retried = true;\n return {\n status: 'retry',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: now,\n };\n },\n );\n return retried && row ? toDeferredDecision(row) : null;\n }\n\n /** Resolve exact active agent authority; partial session matches never authorize. */\n async findActiveRunBinding(address: FactoryRunBindingAddress): Promise<FactoryRunBindingRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: address.orgId,\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n status: 'active',\n });\n return row ? toBinding(row) : null;\n }\n\n /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */\n async findRunBindingBySession(address: FactoryRunBindingSessionAddress): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n });\n if (new Set(rows.map(row => row.org_id)).size !== 1) return null;\n const row = rows.sort((left, right) => {\n if (left.status === 'active' && right.status !== 'active') return -1;\n if (right.status === 'active' && left.status !== 'active') return 1;\n return right.created_at.getTime() - left.created_at.getTime();\n })[0];\n return row ? toBinding(row) : null;\n }\n\n /** Revoke one exact tenant-scoped binding. */\n async revokeRunBinding(input: RevokeFactoryRunBindingInput): Promise<FactoryRunBindingRecord | null> {\n let revoked = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_run_bindings',\n { id: input.bindingId, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'active') return null;\n revoked = true;\n return { status: 'revoked', revoked_at: input.revokedAt };\n },\n );\n return revoked && row ? toBinding(row) : null;\n }\n\n /** Enumerate active bindings for the server-owned restart reconciler. */\n async listActiveRunBindings(): Promise<FactoryRunBindingRecord[]> {\n return (await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { status: 'active' })).map(toBinding);\n }\n\n /** List binding history, optionally narrowed to one work item. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string,\n ): Promise<FactoryRunBindingRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_run_bindings',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(workItemId ? { work_item_id: workItemId } : {}),\n },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toBinding);\n }\n\n async listPendingStarts(orgId: string, factoryProjectId: string): Promise<FactoryPendingStartRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_pending_starts',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toPendingStart);\n }\n\n async claimPendingStarts(input: FactoryLeaseClaimInput): Promise<FactoryPendingStartRecord[]> {\n return this.#claimLeases('factory_pending_starts', input, toPendingStart);\n }\n\n async renewPendingStartLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_pending_starts', identity, leaseExpiresAt);\n }\n\n async completePendingStart(identity: FactoryLeaseIdentity, now: Date): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#completeLease('factory_pending_starts', identity, now);\n return row ? toPendingStart(row) : null;\n }\n\n async failPendingStart(input: FactoryDispatchFailureInput): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#failLease('factory_pending_starts', input);\n return row ? toPendingStart(row) : null;\n }\n\n async prepareRunStart(input: PrepareFactoryRunStartInput): Promise<PrepareFactoryRunStartResult> {\n const prepare = () =>\n this.storage.withTransaction(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n kickoff_key: input.kickoffKey,\n });\n if (prior) {\n const bindingRow = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: String(prior.binding_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n const itemRow =\n bindingRow &&\n (await ops.findOne<WorkItemDbRow>('work_items', {\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n if (!bindingRow || !itemRow) throw new Error('Factory start replay references missing state.');\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : sourceKey(create.externalSource)\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey(create.externalSource),\n })\n : null;\n let item: WorkItemRow;\n if (row) {\n row = await ops.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n const roles = new Set([...Object.keys(current.sessions), input.role]);\n const sessions = Object.fromEntries([...roles].map(role => [role, input.session]));\n return applyUpdate({ current, userId: input.userId, input: { sessions } });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await ops.findMany<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n created_by: input.userId,\n factory_project_id: input.factoryProjectId,\n external_source: create.externalSource ?? null,\n source_key: sourceKey(create.externalSource),\n parent_work_item_id: create.parentWorkItemId ?? null,\n title: create.title,\n stages: create.stages ?? [],\n stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),\n sessions: stampSessions({ [input.role]: input.session }, input.userId),\n metadata: create.metadata ?? null,\n revision: 1,\n created_at: now,\n updated_at: now,\n });\n item = toRow(row);\n }\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n const bindingRow = await ops.insertOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n branch: input.session.branch,\n status: 'active',\n created_at: now,\n revoked_at: null,\n });\n const pendingRow = await ops.insertOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n binding_id: bindingRow.id,\n kickoff_key: input.kickoffKey,\n message: input.kickoffMessage,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: now,\n updated_at: now,\n });\n return { item, binding: toBinding(bindingRow), pendingStart: toPendingStart(pendingRow), replayed: false };\n });\n try {\n return await prepare();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return prepare();\n }\n }\n\n async markPendingStart(\n bindingId: string,\n status: 'sent' | 'failed',\n lastError?: string,\n ): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, last_error: lastError ?? null, updated_at: new Date() }),\n );\n return row ? toPendingStart(row) : null;\n }\n\n /**\n * Create a work item, reusing the existing record when `sourceKey` already\n * has one for the project (acting twice on the same issue must not duplicate\n * the card). On reuse the provided stages replace the current ones (with the\n * transition recorded in history) and sessions/metadata are merged in. The\n * result discriminates insert from reuse so callers can audit the actual\n * outcome.\n */\n async upsert(params: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n }): Promise<UpsertWorkItemResult> {\n const run = (ops: FactoryStorageOps) => this.#upsert(params, ops);\n const execute = () =>\n params.input.parentWorkItemId\n ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run)\n : run(this.#db);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return execute();\n }\n }\n\n async #upsert(\n {\n orgId,\n userId,\n factoryProjectId,\n input,\n reuseMode = 'update',\n }: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n },\n ops: FactoryStorageOps,\n ): Promise<UpsertWorkItemResult> {\n const key = sourceKey(input.externalSource);\n const reuse = async (): Promise<UpsertWorkItemResult | null> => {\n if (!key) return null;\n const existing = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n const item = toWorkItem(existing);\n return { created: false, item, previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId, source_key: key },\n async current => {\n previous = priorState(current);\n const fullPatch = input.parentWorkItemId === null ? { ...input, parentWorkItemId: undefined } : input;\n const patch: UpdateWorkItemInput =\n reuseMode === 'non-stage'\n ? {\n title: input.title,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return {\n external_source: input.externalSource ?? null,\n ...applyUpdate({ current, userId, input: patch }),\n };\n },\n );\n return updated ? { item: toWorkItem(updated), created: false, previous } : null;\n };\n\n const reused = await reuse();\n if (reused) return reused;\n\n const now = new Date();\n const stages = input.stages ?? ['intake'];\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n undefined,\n input.parentWorkItemId ?? null,\n );\n const row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n external_source: input.externalSource ?? null,\n source_key: key,\n parent_work_item_id: input.parentWorkItemId ?? null,\n title: input.title,\n stages,\n stage_history: stages.map(stage => ({ stage, enteredAt: now.toISOString(), by: userId })),\n sessions: stampSessions(input.sessions ?? {}, userId),\n metadata: input.metadata ?? null,\n revision: 1,\n created_by: userId,\n created_at: now,\n updated_at: now,\n });\n return { item: toWorkItem(row), created: true, previous: emptyPrior() };\n }\n\n async update({\n orgId,\n id,\n userId,\n patch,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: UpdateWorkItemInput;\n }): Promise<{ item: WorkItemRow; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n previous = priorState(current);\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return applyUpdate({ current, userId, input: patch });\n });\n return row ? { item: toWorkItem(row), previous } : null;\n };\n\n if (patch.parentWorkItemId === undefined) return run(this.#db);\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);\n }\n\n async delete({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await ops.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!existing) return null;\n const deleted = await ops.deleteMany('work_items', { org_id: orgId, id });\n if (deleted === 0) return null;\n await ops.updateMany(\n 'work_items',\n { org_id: orgId, parent_work_item_id: id },\n { parent_work_item_id: null, updated_at: new Date() },\n );\n return toWorkItem(existing);\n });\n }\n}\n","/**\n * Aggregation math for the Factory Metrics page.\n *\n * Pure functions over `work_items` rows — flow metrics (throughput, cycle\n * time, stage durations, WIP, aging WIP) plus demand mix, all derived from the\n * server-appended `stageHistory` log. Keeping this DB-free makes the math unit\n * testable and lets the route stay a thin shell.\n */\n\nimport { isAutomationActor } from './base.js';\nimport type { WorkItemRow, WorkItemStageEntry } from './base.js';\n\n/** Default window span (days) when the request omits or malforms the range. */\nexport const DEFAULT_METRICS_WINDOW = 30;\n/** Hard cap on the range span (days) — bounds the gap-filled throughput array. */\nexport const MAX_METRICS_WINDOW = 366;\n\nconst DAY_MS = 86_400_000;\n\n/** Terminal stage — items here count as completed, not in-flight. */\nconst DONE_STAGE = 'done';\n\n/** Terminal stage for tracked non-completions — never a completion. */\nconst CANCELED_STAGE = 'canceled';\n\n/**\n * Terminal stages — items holding only these are not in-flight. `done` is a\n * completion (feeds throughput/cycle time); `canceled` is a tracked\n * non-completion outcome and feeds neither.\n */\nconst TERMINAL_STAGES = new Set([DONE_STAGE, CANCELED_STAGE]);\n\nconst AGING_WIP_LIMIT = 10;\n\nexport interface FactoryMetrics {\n windowDays: number;\n /** Earliest work-item creation time (ISO, window-independent) — the natural\n * lower bound for a date-range control. `null` when the board is empty. */\n earliestItemAt: string | null;\n /** Items reaching `done` per UTC day, gap-filled across the window. */\n throughput: { date: string; count: number }[];\n /** Card creation → `done` duration for items completed in the window. */\n cycleTime: { medianMs: number | null; p90Ms: number | null; samples: number };\n /** Median time spent per stage, over visits that ended inside the window. */\n stageDurations: { stage: string; medianMs: number; samples: number }[];\n /** Current cards per stage (window-independent). */\n wip: { stage: string; count: number }[];\n /** Distinct in-flight cards (at least one non-terminal stage). */\n wipTotal: number;\n /** Oldest in-flight cards by time in their current stage. */\n agingWip: { id: string; title: string; stage: string; enteredAt: string; url: string | null }[];\n /** Cards created in the window, by source. */\n sourceMix: { source: string; count: number }[];\n /** Stage moves in the window: human-performed vs total. */\n transitions: { human: number; total: number };\n /** Per-stage automation over completed visits that exited in the window. */\n stageAutomation: {\n stage: string;\n /** Completed visits (entered+exited) to this stage that exited in the window. */\n exits: number;\n /**\n * Of those: clean automated passes — the item's first visit to the stage,\n * entered *and* exited by an automation actor. Missing `exitedBy` (entries\n * written before exit stamping) counts as human.\n */\n automated: number;\n /**\n * Outcomes of the automated passes' items, mutually exclusive, first match\n * wins: `reworked` (a later visit to the same stage exists — deliberately\n * outranks `done`: an automated pass that needed a redo is an automation\n * failure even if the item eventually merged), then `done`, then\n * `canceled`, then `inFlight`.\n */\n outcomes: { done: number; canceled: number; reworked: number; inFlight: number };\n }[];\n}\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Datetime carrying an explicit `Z` or `±HH:MM` offset. */\nconst ZONED_DATETIME_RE = /(?:[Zz]|[+-]\\d{2}:?\\d{2})$/;\n\nfunction parseRangeParam(value: unknown, boundary: 'from' | 'to'): number | undefined {\n if (typeof value !== 'string' || value.length === 0) return undefined;\n const dateOnly = DATE_ONLY_RE.test(value);\n // Timezone-less datetimes are parsed as server-local by Date.parse, so the\n // window would shift by deployment region — reject them as invalid.\n if (!dateOnly && !ZONED_DATETIME_RE.test(value)) return undefined;\n const time = Date.parse(value);\n if (Number.isNaN(time)) return undefined;\n return boundary === 'to' && dateOnly ? time + DAY_MS : time;\n}\n\nfunction utcDayStart(time: number): number {\n return Date.parse(`${utcDay(time)}T00:00:00Z`);\n}\n\n/**\n * Resolve untrusted `from`/`to` into a bounded half-open UTC window. A date-only\n * `to` covers the whole day; an open/future end resolves to the end of the\n * current UTC day (not `now`) so an event at this instant stays inside the\n * window instead of on its excluded edge.\n */\nexport function parseMetricsRange(\n fromParam: unknown,\n toParam: unknown,\n now: Date,\n): { windowStart: number; windowEnd: number } {\n const nowMs = now.getTime();\n const endOfToday = utcDayStart(nowMs) + DAY_MS;\n const requestedEnd = parseRangeParam(toParam, 'to') ?? endOfToday;\n const windowEnd = Math.min(requestedEnd, endOfToday);\n const lastIncludedDay = utcDayStart(windowEnd - 1);\n const defaultStart = lastIncludedDay - (DEFAULT_METRICS_WINDOW - 1) * DAY_MS;\n const parsedFrom = parseRangeParam(fromParam, 'from');\n let windowStart = parsedFrom !== undefined && parsedFrom < windowEnd ? parsedFrom : defaultStart;\n const earliestStart = lastIncludedDay - (MAX_METRICS_WINDOW - 1) * DAY_MS;\n if (windowStart < earliestStart) windowStart = earliestStart;\n return { windowStart, windowEnd };\n}\n\nfunction parseTime(iso: string): number {\n const time = Date.parse(iso);\n return Number.isNaN(time) ? 0 : time;\n}\n\n/** Nearest-rank percentile over an unsorted sample list. */\nfunction percentile(samples: number[], fraction: number): number | null {\n if (samples.length === 0) return null;\n const sorted = [...samples].sort((a, b) => a - b);\n const rank = Math.max(1, Math.ceil(fraction * sorted.length));\n return sorted[rank - 1]!;\n}\n\n/** UTC `YYYY-MM-DD` for a timestamp. */\nfunction utcDay(time: number): string {\n return new Date(time).toISOString().slice(0, 10);\n}\n\n/**\n * The item's completion time: the `enteredAt` of its still-open `done` entry.\n * `undefined` when the item isn't currently done (including when it was pulled\n * back out of done — that visit has `exitedAt` and doesn't count).\n */\nfunction completedAt(item: WorkItemRow): number | undefined {\n if (!item.stages.includes(DONE_STAGE)) return undefined;\n for (let i = item.stageHistory.length - 1; i >= 0; i--) {\n const entry = item.stageHistory[i]!;\n if (entry.stage === DONE_STAGE && entry.exitedAt === undefined) return parseTime(entry.enteredAt);\n }\n return undefined;\n}\n\n/** Open (no `exitedAt`) history entry for a currently-held non-terminal stage. */\nfunction openEntries(item: WorkItemRow): WorkItemStageEntry[] {\n return item.stageHistory.filter(\n entry => entry.exitedAt === undefined && !TERMINAL_STAGES.has(entry.stage) && item.stages.includes(entry.stage),\n );\n}\n\nexport function computeFactoryMetrics(\n items: WorkItemRow[],\n opts: { windowStart: number; windowEnd: number },\n): FactoryMetrics {\n const { windowStart, windowEnd } = opts;\n\n // Earliest creation across all items (window-independent) — the range lower bound.\n let earliest = Infinity;\n for (const item of items) earliest = Math.min(earliest, item.createdAt.getTime());\n const earliestItemAt = Number.isFinite(earliest) ? new Date(earliest).toISOString() : null;\n\n // ── Throughput + cycle time (completed in window) ─────────────────────────\n // Gap-fill every UTC calendar date intersecting the half-open window.\n const throughputByDay = new Map<string, number>();\n const firstDay = utcDayStart(windowStart);\n for (let day = firstDay; day < windowEnd; day += DAY_MS) {\n throughputByDay.set(utcDay(day), 0);\n }\n const cycleSamples: number[] = [];\n for (const item of items) {\n const doneAt = completedAt(item);\n if (doneAt === undefined || doneAt < windowStart || doneAt >= windowEnd) continue;\n const day = utcDay(doneAt);\n throughputByDay.set(day, (throughputByDay.get(day) ?? 0) + 1);\n cycleSamples.push(Math.max(0, doneAt - item.createdAt.getTime()));\n }\n\n // ── Stage durations (visits that ended in window) ─────────────────────────\n const durationsByStage = new Map<string, number[]>();\n for (const item of items) {\n for (const entry of item.stageHistory) {\n if (entry.exitedAt === undefined || TERMINAL_STAGES.has(entry.stage)) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n const duration = Math.max(0, exited - parseTime(entry.enteredAt));\n const samples = durationsByStage.get(entry.stage) ?? [];\n samples.push(duration);\n durationsByStage.set(entry.stage, samples);\n }\n }\n\n // ── Current WIP + aging (window-independent) ──────────────────────────────\n const wipByStage = new Map<string, number>();\n let wipTotal = 0;\n const aging: FactoryMetrics['agingWip'] = [];\n for (const item of items) {\n for (const stage of item.stages) {\n wipByStage.set(stage, (wipByStage.get(stage) ?? 0) + 1);\n }\n const inFlightStages = item.stages.filter(stage => !TERMINAL_STAGES.has(stage));\n if (inFlightStages.length === 0) continue;\n wipTotal += 1;\n // Age the card by its longest-held current stage; fall back to creation\n // time if history is missing an open entry (shouldn't happen — history is\n // server-appended).\n const open = openEntries(item);\n const oldest = open.reduce<WorkItemStageEntry | undefined>(\n (best, entry) => (!best || parseTime(entry.enteredAt) < parseTime(best.enteredAt) ? entry : best),\n undefined,\n );\n aging.push({\n id: item.id,\n title: item.title,\n stage: oldest?.stage ?? inFlightStages[0]!,\n enteredAt: oldest?.enteredAt ?? item.createdAt.toISOString(),\n url: item.externalSource?.url ?? null,\n });\n }\n aging.sort((a, b) => parseTime(a.enteredAt) - parseTime(b.enteredAt));\n\n // ── Demand mix + transitions (window) ─────────────────────────────────────\n const sourceCounts = new Map<string, number>();\n let transitionsTotal = 0;\n let transitionsHuman = 0;\n for (const item of items) {\n if (item.createdAt.getTime() >= windowStart && item.createdAt.getTime() < windowEnd) {\n const source = item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}`\n : 'manual';\n sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1);\n }\n for (const entry of item.stageHistory) {\n const entered = parseTime(entry.enteredAt);\n if (entered < windowStart || entered >= windowEnd) continue;\n transitionsTotal += 1;\n if (!isAutomationActor(entry.by)) transitionsHuman += 1;\n }\n }\n\n // ── Per-stage automation (completed visits that exited in window) ─────────\n // Rows appear in insertion order of each stage's first counted exit;\n // terminal stages never get rows (they have no meaningful \"pass through\").\n const automationByStage = new Map<string, FactoryMetrics['stageAutomation'][number]>();\n for (const item of items) {\n const itemDone = completedAt(item) !== undefined;\n const itemCanceled = item.stages.includes(CANCELED_STAGE);\n for (let i = 0; i < item.stageHistory.length; i++) {\n const entry = item.stageHistory[i]!;\n if (entry.exitedAt === undefined || TERMINAL_STAGES.has(entry.stage)) continue;\n const exited = parseTime(entry.exitedAt);\n if (exited < windowStart || exited >= windowEnd) continue;\n let row = automationByStage.get(entry.stage);\n if (!row) {\n row = {\n stage: entry.stage,\n exits: 0,\n automated: 0,\n outcomes: { done: 0, canceled: 0, reworked: 0, inFlight: 0 },\n };\n automationByStage.set(entry.stage, row);\n }\n row.exits += 1;\n // A clean automated pass: automation entered AND exited it, and this is\n // the item's first visit to the stage (a re-run is rework, not clean\n // automation). Missing `exitedBy` → human-exited → not automated.\n const firstVisitIndex = item.stageHistory.findIndex(e => e.stage === entry.stage);\n if (firstVisitIndex !== i || !isAutomationActor(entry.by) || !isAutomationActor(entry.exitedBy)) continue;\n row.automated += 1;\n const reworked = item.stageHistory.some((e, j) => j > i && e.stage === entry.stage);\n if (reworked) row.outcomes.reworked += 1;\n else if (itemDone) row.outcomes.done += 1;\n else if (itemCanceled) row.outcomes.canceled += 1;\n else row.outcomes.inFlight += 1;\n }\n }\n\n return {\n windowDays: throughputByDay.size,\n earliestItemAt,\n throughput: [...throughputByDay.entries()]\n .map(([date, count]) => ({ date, count }))\n .sort((a, b) => a.date.localeCompare(b.date)),\n cycleTime: {\n medianMs: percentile(cycleSamples, 0.5),\n p90Ms: percentile(cycleSamples, 0.9),\n samples: cycleSamples.length,\n },\n stageDurations: [...durationsByStage.entries()].map(([stage, samples]) => ({\n stage,\n medianMs: percentile(samples, 0.5)!,\n samples: samples.length,\n })),\n wip: [...wipByStage.entries()].map(([stage, count]) => ({ stage, count })),\n wipTotal,\n agingWip: aging.slice(0, AGING_WIP_LIMIT),\n sourceMix: [...sourceCounts.entries()]\n .map(([source, count]) => ({ source, count }))\n .sort((a, b) => b.count - a.count),\n transitions: { human: transitionsHuman, total: transitionsTotal },\n stageAutomation: [...automationByStage.values()],\n };\n}\n"],"mappings":";AAUA,SAAS,kBAAkB;AAE3B,SAAS,sBAAsB,4BAA4B;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C,OAAO,WAAW,cAAc,GAAG;AAAA,MACnC,SAAS,aAAa;AAAA,IACxB;AAAA,IACA,gBAAgB,CAAC,GAAG,iBAAiB,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,OAAO,OAAO,OAAO;AAAA,MACzE;AAAA,MACA,UAAU,WAAW,SAAS,GAAG;AAAA,MACjC,SAAS,QAAQ;AAAA,IACnB,EAAE;AAAA,IACF,KAAK,CAAC,GAAG,WAAW,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO,EAAE,OAAO,MAAM,EAAE;AAAA,IACzE;AAAA,IACA,UAAU,MAAM,MAAM,GAAG,eAAe;AAAA,IACxC,WAAW,CAAC,GAAG,aAAa,QAAQ,CAAC,EAClC,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,EAAE,QAAQ,MAAM,EAAE,EAC5C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAAA,IACnC,aAAa,EAAE,OAAO,kBAAkB,OAAO,iBAAiB;AAAA,IAChE,iBAAiB,CAAC,GAAG,kBAAkB,OAAO,CAAC;AAAA,EACjD;AACF;","names":[]}
|
package/dist/timing.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight phase timing for factory boot and hot request paths.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately not a metrics framework: structured stderr lines that can be
|
|
5
|
+
* grepped (`[factory:timing]`) and diffed across runs to localize slow boot
|
|
6
|
+
* phases and slow per-request dependencies.
|
|
7
|
+
*/
|
|
8
|
+
/** Run `fn`, always logging its duration under `phase`. Boot-phase use. */
|
|
9
|
+
export declare function timedPhase<T>(phase: string, fn: () => Promise<T>): Promise<T>;
|
|
10
|
+
/**
|
|
11
|
+
* Run `fn`, logging only when it exceeds `thresholdMs`. Request-path use,
|
|
12
|
+
* where per-request logging would be noise but slow outliers must surface.
|
|
13
|
+
*/
|
|
14
|
+
export declare function timedAboveThreshold<T>(phase: string, thresholdMs: number, fn: () => Promise<T>): Promise<T>;
|
|
15
|
+
//# sourceMappingURL=timing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timing.d.ts","sourceRoot":"","sources":["../src/timing.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,2EAA2E;AAC3E,wBAAsB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOnF;AAED;;;GAGG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAUjH"}
|
package/dist/timing.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/timing.ts
|
|
2
|
+
async function timedPhase(phase, fn) {
|
|
3
|
+
const start = performance.now();
|
|
4
|
+
try {
|
|
5
|
+
return await fn();
|
|
6
|
+
} finally {
|
|
7
|
+
process.stderr.write(`[factory:timing] ${phase} ${Math.round(performance.now() - start)}ms
|
|
8
|
+
`);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
async function timedAboveThreshold(phase, thresholdMs, fn) {
|
|
12
|
+
const start = performance.now();
|
|
13
|
+
try {
|
|
14
|
+
return await fn();
|
|
15
|
+
} finally {
|
|
16
|
+
const elapsed = performance.now() - start;
|
|
17
|
+
if (elapsed > thresholdMs) {
|
|
18
|
+
process.stderr.write(`[factory:timing] slow ${phase} ${Math.round(elapsed)}ms
|
|
19
|
+
`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
timedAboveThreshold,
|
|
25
|
+
timedPhase
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=timing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/timing.ts"],"sourcesContent":["/**\n * Lightweight phase timing for factory boot and hot request paths.\n *\n * Deliberately not a metrics framework: structured stderr lines that can be\n * grepped (`[factory:timing]`) and diffed across runs to localize slow boot\n * phases and slow per-request dependencies.\n */\n\n/** Run `fn`, always logging its duration under `phase`. Boot-phase use. */\nexport async function timedPhase<T>(phase: string, fn: () => Promise<T>): Promise<T> {\n const start = performance.now();\n try {\n return await fn();\n } finally {\n process.stderr.write(`[factory:timing] ${phase} ${Math.round(performance.now() - start)}ms\\n`);\n }\n}\n\n/**\n * Run `fn`, logging only when it exceeds `thresholdMs`. Request-path use,\n * where per-request logging would be noise but slow outliers must surface.\n */\nexport async function timedAboveThreshold<T>(phase: string, thresholdMs: number, fn: () => Promise<T>): Promise<T> {\n const start = performance.now();\n try {\n return await fn();\n } finally {\n const elapsed = performance.now() - start;\n if (elapsed > thresholdMs) {\n process.stderr.write(`[factory:timing] slow ${phase} ${Math.round(elapsed)}ms\\n`);\n }\n }\n}\n"],"mappings":";AASA,eAAsB,WAAc,OAAe,IAAkC;AACnF,QAAM,QAAQ,YAAY,IAAI;AAC9B,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,UAAE;AACA,YAAQ,OAAO,MAAM,oBAAoB,KAAK,IAAI,KAAK,MAAM,YAAY,IAAI,IAAI,KAAK,CAAC;AAAA,CAAM;AAAA,EAC/F;AACF;AAMA,eAAsB,oBAAuB,OAAe,aAAqB,IAAkC;AACjH,QAAM,QAAQ,YAAY,IAAI;AAC9B,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,UAAE;AACA,UAAM,UAAU,YAAY,IAAI,IAAI;AACpC,QAAI,UAAU,aAAa;AACzB,cAAQ,OAAO,MAAM,yBAAyB,KAAK,IAAI,KAAK,MAAM,OAAO,CAAC;AAAA,CAAM;AAAA,IAClF;AAAA,EACF;AACF;","names":[]}
|
package/dist/workspace.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';
|
|
2
1
|
import { getDynamicWorkspace } from '@mastra/code-sdk/agents/workspace';
|
|
3
2
|
import { LocalSandbox, Workspace } from '@mastra/core/workspace';
|
|
4
3
|
import type { MastraFactorySandboxConfig } from './factory.js';
|
|
@@ -19,7 +18,7 @@ export interface CreateWorkspaceFactoryOptions {
|
|
|
19
18
|
* without it every session uses the default (worker) PAT. */
|
|
20
19
|
workItems?: Pick<WorkItemsStorage, 'findRunBindingBySession'>;
|
|
21
20
|
}
|
|
22
|
-
export declare function createWorkspaceFactory(options?: CreateWorkspaceFactoryOptions): ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => Promise<Workspace<import("@mastra/core/workspace").WorkspaceFilesystem | undefined, import("@mastra/core/workspace").WorkspaceSandbox | undefined, undefined> | Workspace<import("@mastra/core/workspace").LocalFilesystem, LocalSandbox, undefined
|
|
23
|
-
export declare const getFactoryWorkspace: ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => Promise<Workspace<import("@mastra/core/workspace").WorkspaceFilesystem | undefined, import("@mastra/core/workspace").WorkspaceSandbox | undefined, undefined> | Workspace<import("@mastra/core/workspace").LocalFilesystem, LocalSandbox, undefined
|
|
21
|
+
export declare function createWorkspaceFactory(options?: CreateWorkspaceFactoryOptions): ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => Promise<Workspace<import("@mastra/core/workspace").WorkspaceFilesystem | undefined, import("@mastra/core/workspace").WorkspaceSandbox | undefined, undefined> | Workspace<import("@mastra/core/workspace").LocalFilesystem, LocalSandbox, undefined>>;
|
|
22
|
+
export declare const getFactoryWorkspace: ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => Promise<Workspace<import("@mastra/core/workspace").WorkspaceFilesystem | undefined, import("@mastra/core/workspace").WorkspaceSandbox | undefined, undefined> | Workspace<import("@mastra/core/workspace").LocalFilesystem, LocalSandbox, undefined>>;
|
|
24
23
|
export {};
|
|
25
24
|
//# sourceMappingURL=workspace.d.ts.map
|
package/dist/workspace.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,OAAO,EAAE,YAAY,EAAoB,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAM9E,OAAO,KAAK,EAAuB,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAK7E,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AA+ED,KAAK,uBAAuB,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,6BAA6B;IAC5C,wEAAwE;IACxE,OAAO,CAAC,EAAE,0BAA0B,CAAC;IACrC,gFAAgF;IAChF,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB;;iEAE6D;IAC7D,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,yBAAyB,CAAC,CAAC;CAC/D;AAED,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,6BAAkC,IAYlE,4CAA4C,uBAAuB,2PAgLlF;AAED,eAAO,MAAM,mBAAmB,+CAlL4B,uBAAuB,0PAkLxB,CAAC"}
|