@mastra/factory 0.14.0-alpha.2 → 0.14.0-alpha.4
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/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +8 -3
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts +0 -1
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +3 -16
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/workos/integration.js +1 -1
- package/dist/integrations/workos/integration.js.map +1 -1
- package/dist/routes/contracts.d.ts +2 -2
- package/dist/routes/surface.d.ts +2 -2
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +10 -87
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +29 -0
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/transition-service.d.ts +11 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +72 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/session/run-audit.d.ts +49 -0
- package/dist/session/run-audit.d.ts.map +1 -0
- package/dist/session/run-audit.js +99 -0
- package/dist/session/run-audit.js.map +1 -0
- package/dist/session/shell-commands.d.ts +5 -0
- package/dist/session/shell-commands.d.ts.map +1 -0
- package/dist/session/shell-commands.js +25 -0
- package/dist/session/shell-commands.js.map +1 -0
- package/dist/storage/domains/audit/actions.d.ts +24 -0
- package/dist/storage/domains/audit/actions.d.ts.map +1 -0
- package/dist/storage/domains/audit/actions.js +67 -0
- package/dist/storage/domains/audit/actions.js.map +1 -0
- package/dist/storage/domains/audit/actors.d.ts +5 -0
- package/dist/storage/domains/audit/actors.d.ts.map +1 -0
- package/dist/storage/domains/audit/actors.js +25 -0
- package/dist/storage/domains/audit/actors.js.map +1 -0
- package/dist/storage/domains/audit/agent-audit.d.ts +5 -7
- package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -1
- package/dist/storage/domains/audit/agent-audit.js +33 -24
- package/dist/storage/domains/audit/agent-audit.js.map +1 -1
- package/dist/storage/domains/audit/base.d.ts +28 -33
- package/dist/storage/domains/audit/base.d.ts.map +1 -1
- package/dist/storage/domains/audit/base.js +58 -31
- package/dist/storage/domains/audit/base.js.map +1 -1
- package/dist/storage/domains/audit/domain.d.ts +12 -9
- package/dist/storage/domains/audit/domain.d.ts.map +1 -1
- package/dist/storage/domains/audit/domain.js +32 -48
- package/dist/storage/domains/audit/domain.js.map +1 -1
- package/dist/storage/domains/audit/wire.d.ts +24 -0
- package/dist/storage/domains/audit/wire.d.ts.map +1 -0
- package/dist/storage/domains/audit/wire.js +16 -0
- package/dist/storage/domains/audit/wire.js.map +1 -0
- package/dist/supervisor/write-tools.d.ts +2 -2
- package/dist/supervisor/write-tools.d.ts.map +1 -1
- package/dist/supervisor/write-tools.js +1 -17
- package/dist/supervisor/write-tools.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transition-service.js","names":["#configVersion","#boards","#storage","#timeoutMs","#onTerminalStage","#terminalCleanupTimeoutMs","#onAccepted","#commitRejection","#commit"],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { createBoardRegistry } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryStageRules } from './resolve.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryTriageType,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n} from './types.js';\nimport {\n externallyAuthoredWorkItem,\n factoryRuleSourceForWorkItem,\n isFactoryRuleStage,\n workItemSource,\n} from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: evaluate only the destination onEnter leaf even when already at that stage. */\n initialEntry?: boolean;\n /** Re-runs the stage's entry rules when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Structured verdict required from a bound triage-agent terminal request. */\n triageType?: FactoryTriageType;\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n boards?: BoardRegistry;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` before returning (default 30s). The cleanup continues\n * in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a transition first records a person's acceptance of a\n * non-bug item (see `WorkItemRow.acceptedAt`). Fire-and-forget: failures\n * are swallowed, the committed transition never depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: WorkItemRow;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n }\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n if (stages.length !== 1) return undefined;\n const stage = stages[0];\n return isFactoryRuleStage(stage) ? stage : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n accept?: boolean;\n triageType?: FactoryTriageType;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isTriageAgent(actor: FactoryRuleActor): actor is Extract<FactoryRuleActor, { type: 'agent' }> {\n return actor.type === 'agent' && actor.role === 'triage';\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: BoardRegistry;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = options.boards ?? createBoardRegistry();\n this.#storage = options.storage;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onAccepted = options.onAccepted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', 'Work item not found.');\n }\n\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const legacyBoard = source === 'pullRequest' ? 'review' : 'work';\n if (item.board === null && !this.#boards.has(legacyBoard)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = item.board ?? legacyBoard;\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n if ((itemBoard === 'review' && source !== 'pullRequest') || (itemBoard === 'work' && source === 'pullRequest')) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not belong to the requested board.',\n );\n }\n const board = this.#boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n !board.allowsTransition(fromStage, request.stage)\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.title} board does not allow moving from ${fromStage} to ${request.stage}.`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: [...item.stages],\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n requestedTriageType: request.triageType,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n if (\n policy?.triageType !== undefined &&\n (!isTriageAgent(request.actor) ||\n policy.triageType !== request.triageType ||\n (item.triageType !== null && item.triageType !== policy.triageType))\n ) {\n throw new Error('Board policy requested an unauthorized classification.');\n }\n if (policy?.accept && !isHumanTransition(request)) {\n throw new Error('Board policy requested unauthorized acceptance.');\n }\n // External content can steer a bound agent; board allowance cannot bypass this guard.\n if (\n request.actor.type === 'agent' &&\n !board.isWorking(fromStage) &&\n entersWorking &&\n externallyAuthoredWorkItem(item)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n 'This card comes from outside the write-access circle; a person must resume it from the Factory board.',\n };\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const rule of resolveFactoryStageRules(this.#boards, {\n board: request.board,\n source,\n fromStage,\n toStage: request.stage,\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n })) {\n const context: FactoryStageRuleContext = Object.freeze({\n ...contextBase,\n stage: rule.phase === 'exit' ? fromStage : request.stage,\n });\n const raw = await rule.handler(context);\n if (raw === undefined) continue;\n const decision = validateFactoryRuleDecision(raw, context.causalChain.length);\n if (decision.type === 'reject') {\n return { outcome: 'rejected' as const, code: decision.code, reason: decision.reason };\n }\n assertFactoryDecisionTarget(decision, this.#boards, itemBoard);\n if (startsRun(decision) && runAlreadyUnderway(request, decision)) continue;\n decisions.push(decision);\n }\n const validated = validateFactoryRuleDecisions(decisions);\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: { triageType: policy?.triageType, accept: policy?.accept === true && !item.acceptedAt },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(request, transitionId, { outcome: 'rejected', code, reason });\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions = {},\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n ...(options.accept ? { accept: true } : {}),\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, triggerType: request.ingress.type, transitionId },\n configVersion: this.#configVersion,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n ...(options.triageType ? { triageType: options.triageType } : {}),\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accept &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item?.acceptedAt\n ) {\n const item = committed.item;\n void Promise.resolve(\n this.#onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n ).catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n if (\n this.#onTerminalStage &&\n result.status === 'accepted' &&\n this.#boards.get(request.board)?.isTerminal(result.stage) === true\n ) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve(\n this.#onTerminalStage({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n stage: result.stage,\n revision: result.revision,\n }),\n );\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n return result;\n }\n}\n"],"mappings":";;;;;;;;AA+BA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AA0DpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,SAAS,MAAM;EACxB,KAAK,UACH,OAAO,UAAU,MAAM;CAC3B;AACF;AAEA,SAAgB,aAAa,QAAyD;CACpF,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,MAAM,QAAQ,OA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AiB;KACpB,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,YAAY,QAAQ;KACpB,OAAO,OAAO;KACd,UAAU,OAAO;IACnB,CAAC,CACH;IAGA,QAAQ,YAAY,CAAC,CAAC;IACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;KAC3B,QAAQ,WAAW,SAAS,KAAKC,yBAAyB;IAC5D,CAAC,CACH,CAAC;GACH,QAAQ,CAER,UAAU;IACR,aAAa,KAAK;GACpB;EACF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"transition-service.js","names":["#configVersion","#boards","#storage","#timeoutMs","#onTerminalStage","#terminalCleanupTimeoutMs","#onAccepted","#audit","#commitRejection","#recordTransition","#evaluateAndCommit","#commit"],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { createBoardRegistry } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { AuditActorProfileInput, AuditActorType, AuditContext } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { isAgentActor } from '../storage/domains/work-items/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryStageRules } from './resolve.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryTriageType,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n} from './types.js';\nimport {\n externallyAuthoredWorkItem,\n factoryRuleSourceForWorkItem,\n isFactoryRuleStage,\n workItemSource,\n} from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n actorProfile?: AuditActorProfileInput;\n /** Where a browser request came from; rules and agents carry none. */\n context?: AuditContext;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: evaluate only the destination onEnter leaf even when already at that stage. */\n initialEntry?: boolean;\n /** Re-runs the stage's entry rules when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Structured verdict required from a bound triage-agent terminal request. */\n triageType?: FactoryTriageType;\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n boards?: BoardRegistry;\n /** Every commit, accepted or rejected, lands here as `stage_moved` / `transition_rejected` under the request's actor. */\n audit?: AuditRecorder;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` before returning (default 30s). The cleanup continues\n * in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a transition first records a person's acceptance of a\n * non-bug item (see `WorkItemRow.acceptedAt`). Fire-and-forget: failures\n * are swallowed, the committed transition never depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: WorkItemRow;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n }\n}\n\n// The dispatcher executes an agent-approved decision as a human actor so its consent carries; the trail still names the agent.\nexport function auditActorOf(actor: FactoryRuleActor): { actorId: string; actorType: AuditActorType } {\n const id = actorId(actor);\n switch (actor.type) {\n case 'github':\n return { actorId: id, actorType: 'human' };\n case 'human':\n return { actorId: id, actorType: isAgentActor(id) ? 'agent' : 'human' };\n default:\n return { actorId: id, actorType: actor.type };\n }\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n if (stages.length !== 1) return undefined;\n const stage = stages[0];\n return isFactoryRuleStage(stage) ? stage : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n accept?: boolean;\n triageType?: FactoryTriageType;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isTriageAgent(actor: FactoryRuleActor): actor is Extract<FactoryRuleActor, { type: 'agent' }> {\n return actor.type === 'agent' && actor.role === 'triage';\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: BoardRegistry;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n readonly #audit: AuditRecorder | undefined;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = options.boards ?? createBoardRegistry();\n this.#storage = options.storage;\n this.#audit = options.audit;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onAccepted = options.onAccepted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n const rejection = await this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Work item not found.',\n );\n await this.#recordTransition(request, undefined, rejection);\n return rejection;\n }\n const result = await this.#evaluateAndCommit(request, transitionId, item);\n await this.#recordTransition(request, item, result);\n return result;\n }\n\n /** A rejection can outlive its work item: the row still names the id the caller asked for. */\n async #recordTransition(\n request: FactoryTransitionRequest,\n item: WorkItemRow | undefined,\n result: FactoryTransitionResult,\n ): Promise<void> {\n if (!this.#audit) return;\n const from = item ? currentStage(item.stages) : undefined;\n if (result.status === 'accepted' && result.stage === from && !request.reenter) return;\n const outcome =\n result.status === 'accepted'\n ? { action: 'factory.work_item.stage_moved' as const, to: result.stage, revision: result.revision }\n : {\n action: 'factory.work_item.transition_rejected' as const,\n to: request.stage,\n code: result.code,\n reason: result.reason,\n };\n const { action, ...detail } = outcome;\n await this.#audit\n .record({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n ...auditActorOf(request.actor),\n actorProfile: request.actorProfile,\n ...(request.context ? { context: request.context } : {}),\n action,\n idempotencyKey: result.transitionId,\n targets: [{ type: 'work_item', id: item?.id ?? request.workItemId, ...(item ? { name: item.title } : {}) }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: request.ingress.type,\n cause: request.cause,\n configVersion: this.#configVersion,\n ...(from ? { from } : {}),\n ...(request.reenter ? { reenter: true } : {}),\n ...detail,\n },\n })\n .catch(error => {\n console.warn(`[factory] audit failed for transition ${result.transitionId}:`, error);\n });\n }\n\n async #evaluateAndCommit(\n request: FactoryTransitionRequest,\n transitionId: string,\n item: WorkItemRow,\n ): Promise<FactoryTransitionResult> {\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const legacyBoard = source === 'pullRequest' ? 'review' : 'work';\n if (item.board === null && !this.#boards.has(legacyBoard)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = item.board ?? legacyBoard;\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n if ((itemBoard === 'review' && source !== 'pullRequest') || (itemBoard === 'work' && source === 'pullRequest')) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not belong to the requested board.',\n );\n }\n const board = this.#boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n !board.allowsTransition(fromStage, request.stage)\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.title} board does not allow moving from ${fromStage} to ${request.stage}.`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: [...item.stages],\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n requestedTriageType: request.triageType,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n if (\n policy?.triageType !== undefined &&\n (!isTriageAgent(request.actor) ||\n policy.triageType !== request.triageType ||\n (item.triageType !== null && item.triageType !== policy.triageType))\n ) {\n throw new Error('Board policy requested an unauthorized classification.');\n }\n if (policy?.accept && !isHumanTransition(request)) {\n throw new Error('Board policy requested unauthorized acceptance.');\n }\n // External content can steer a bound agent; board allowance cannot bypass this guard.\n if (\n request.actor.type === 'agent' &&\n !board.isWorking(fromStage) &&\n entersWorking &&\n externallyAuthoredWorkItem(item)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n 'This card comes from outside the write-access circle; a person must resume it from the Factory board.',\n };\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const rule of resolveFactoryStageRules(this.#boards, {\n board: request.board,\n source,\n fromStage,\n toStage: request.stage,\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n })) {\n const context: FactoryStageRuleContext = Object.freeze({\n ...contextBase,\n stage: rule.phase === 'exit' ? fromStage : request.stage,\n });\n const raw = await rule.handler(context);\n if (raw === undefined) continue;\n const decision = validateFactoryRuleDecision(raw, context.causalChain.length);\n if (decision.type === 'reject') {\n return { outcome: 'rejected' as const, code: decision.code, reason: decision.reason };\n }\n assertFactoryDecisionTarget(decision, this.#boards, itemBoard);\n if (startsRun(decision) && runAlreadyUnderway(request, decision)) continue;\n decisions.push(decision);\n }\n const validated = validateFactoryRuleDecisions(decisions);\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: { triageType: policy?.triageType, accept: policy?.accept === true && !item.acceptedAt },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(request, transitionId, { outcome: 'rejected', code, reason });\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions = {},\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n ...(options.accept ? { accept: true } : {}),\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, triggerType: request.ingress.type, transitionId },\n configVersion: this.#configVersion,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n ...(options.triageType ? { triageType: options.triageType } : {}),\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accept &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item?.acceptedAt\n ) {\n const item = committed.item;\n void Promise.resolve(\n this.#onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n ).catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n if (\n this.#onTerminalStage &&\n result.status === 'accepted' &&\n this.#boards.get(request.board)?.isTerminal(result.stage) === true\n ) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve(\n this.#onTerminalStage({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n stage: result.stage,\n revision: result.revision,\n }),\n );\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n return result;\n }\n}\n"],"mappings":";;;;;;;;;AAkCA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AA+DpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,SAAS,MAAM;EACxB,KAAK,UACH,OAAO,UAAU,MAAM;CAC3B;AACF;AAGA,SAAgB,aAAa,OAAyE;CACpG,MAAM,KAAK,QAAQ,KAAK;CACxB,QAAQ,MAAM,MAAd;EACE,KAAK,UACH,OAAO;GAAE,SAAS;GAAI,WAAW;EAAQ;EAC3C,KAAK,SACH,OAAO;GAAE,SAAS;GAAI,WAAW,aAAa,EAAE,IAAI,UAAU;EAAQ;EACxE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,IAAI,KAAK;GAC7F,CAAC;EACH;EAEA,IACE,KAAKF,oBACL,OAAO,WAAW,cAClB,KAAKH,QAAQ,IAAI,QAAQ,KAAK,CAAC,EAAE,WAAW,OAAO,KAAK,MAAM,MAC9D;GACA,IAAI;GACJ,IAAI;IACF,MAAM,UAAU,QAAQ,QACtB,KAAKG,iBAAiB;KACpB,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,YAAY,QAAQ;KACpB,OAAO,OAAO;KACd,UAAU,OAAO;IACnB,CAAC,CACH;IAGA,QAAQ,YAAY,CAAC,CAAC;IACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;KAC3B,QAAQ,WAAW,SAAS,KAAKC,yBAAyB;IAC5D,CAAC,CACH,CAAC;GACH,QAAQ,CAER,UAAU;IACR,aAAa,KAAK;GACpB;EACF;EACA,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { AgentControllerEvent } from '@mastra/core/agent-controller';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import type { AuditActorType } from '../storage/domains/audit/base.js';
|
|
4
|
+
import type { AuditRecorder } from '../storage/domains/audit/domain.js';
|
|
5
|
+
export declare const FACTORY_OPEN_RUNS_SETTING = "factoryOpenRuns";
|
|
6
|
+
declare const factoryOpenRunSchema: z.ZodObject<{
|
|
7
|
+
kickoffId: z.ZodString;
|
|
8
|
+
bindingId: z.ZodString;
|
|
9
|
+
role: z.ZodString;
|
|
10
|
+
startedBy: z.ZodString;
|
|
11
|
+
orgId: z.ZodString;
|
|
12
|
+
factoryProjectId: z.ZodString;
|
|
13
|
+
workItemId: z.ZodString;
|
|
14
|
+
workItemName: z.ZodOptional<z.ZodString>;
|
|
15
|
+
sessionId: z.ZodString;
|
|
16
|
+
threadId: z.ZodString;
|
|
17
|
+
branch: z.ZodString;
|
|
18
|
+
agentName: z.ZodString;
|
|
19
|
+
}, z.core.$strip>;
|
|
20
|
+
export type FactoryOpenRun = z.infer<typeof factoryOpenRunSchema>;
|
|
21
|
+
export interface RunEndCaptureSession {
|
|
22
|
+
readonly thread: {
|
|
23
|
+
getSetting(args: {
|
|
24
|
+
key: string;
|
|
25
|
+
}): Promise<unknown>;
|
|
26
|
+
setSetting(args: {
|
|
27
|
+
key: string;
|
|
28
|
+
value: unknown;
|
|
29
|
+
}): Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
readonly mode: {
|
|
32
|
+
get(): string;
|
|
33
|
+
};
|
|
34
|
+
subscribe(listener: (event: AgentControllerEvent) => void): () => void;
|
|
35
|
+
}
|
|
36
|
+
type RunEndReason = Extract<AgentControllerEvent, {
|
|
37
|
+
type: 'agent_end';
|
|
38
|
+
}>['reason'];
|
|
39
|
+
export declare function recordSessionRunStart(session: RunEndCaptureSession, { audit, run, actorType, observedEnd, }: {
|
|
40
|
+
audit: AuditRecorder;
|
|
41
|
+
run: Omit<FactoryOpenRun, 'agentName'>;
|
|
42
|
+
actorType: AuditActorType;
|
|
43
|
+
observedEnd: () => RunEndReason;
|
|
44
|
+
}): Promise<void>;
|
|
45
|
+
export declare function observeSessionRunEnd(session: RunEndCaptureSession, { audit }: {
|
|
46
|
+
audit: AuditRecorder;
|
|
47
|
+
}): () => void;
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=run-audit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-audit.d.ts","sourceRoot":"","sources":["../../src/session/run-audit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAExE,eAAO,MAAM,yBAAyB,oBAAoB,CAAC;AAE3D,QAAA,MAAM,oBAAoB;;;;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import { z } from "zod";
|
|
3
|
+
//#region src/session/run-audit.ts
|
|
4
|
+
const FACTORY_OPEN_RUNS_SETTING = "factoryOpenRuns";
|
|
5
|
+
const factoryOpenRunSchema = z.object({
|
|
6
|
+
kickoffId: z.string(),
|
|
7
|
+
bindingId: z.string(),
|
|
8
|
+
role: z.string(),
|
|
9
|
+
startedBy: z.string(),
|
|
10
|
+
orgId: z.string(),
|
|
11
|
+
factoryProjectId: z.string(),
|
|
12
|
+
workItemId: z.string(),
|
|
13
|
+
workItemName: z.string().optional(),
|
|
14
|
+
sessionId: z.string(),
|
|
15
|
+
threadId: z.string(),
|
|
16
|
+
branch: z.string(),
|
|
17
|
+
agentName: z.string()
|
|
18
|
+
});
|
|
19
|
+
const pendingWrites = /* @__PURE__ */ new WeakMap();
|
|
20
|
+
function serializeRunAudit(session, write) {
|
|
21
|
+
const pending = (pendingWrites.get(session) ?? Promise.resolve()).then(write).catch((error) => console.warn("[Factory run audit] Unable to record run lifecycle.", error));
|
|
22
|
+
pendingWrites.set(session, pending);
|
|
23
|
+
return pending;
|
|
24
|
+
}
|
|
25
|
+
async function readOpenRuns(session) {
|
|
26
|
+
const stored = await session.thread.getSetting({ key: FACTORY_OPEN_RUNS_SETTING });
|
|
27
|
+
return z.array(factoryOpenRunSchema).parse(stored ?? []);
|
|
28
|
+
}
|
|
29
|
+
function runAuditInput(run) {
|
|
30
|
+
const { orgId, factoryProjectId, workItemId, workItemName, ...metadata } = run;
|
|
31
|
+
return {
|
|
32
|
+
orgId,
|
|
33
|
+
factoryProjectId,
|
|
34
|
+
idempotencyKey: run.kickoffId,
|
|
35
|
+
targets: [{
|
|
36
|
+
type: "work_item",
|
|
37
|
+
id: workItemId,
|
|
38
|
+
...workItemName ? { name: workItemName } : {}
|
|
39
|
+
}],
|
|
40
|
+
metadata
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
async function recordRunEnds(session, audit, reason, kickoffId) {
|
|
44
|
+
if (!reason || reason === "suspended") return;
|
|
45
|
+
const runs = await readOpenRuns(session);
|
|
46
|
+
if (runs.length === 0) return;
|
|
47
|
+
const remaining = [];
|
|
48
|
+
for (const run of runs) {
|
|
49
|
+
if (kickoffId && run.kickoffId !== kickoffId) {
|
|
50
|
+
remaining.push(run);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const input = runAuditInput(run);
|
|
54
|
+
if (!await audit.record({
|
|
55
|
+
...input,
|
|
56
|
+
actorId: `agent:${run.threadId}`,
|
|
57
|
+
actorType: "agent",
|
|
58
|
+
action: "factory.run.ended",
|
|
59
|
+
metadata: {
|
|
60
|
+
...input.metadata,
|
|
61
|
+
reason
|
|
62
|
+
}
|
|
63
|
+
})) remaining.push(run);
|
|
64
|
+
}
|
|
65
|
+
await session.thread.setSetting({
|
|
66
|
+
key: FACTORY_OPEN_RUNS_SETTING,
|
|
67
|
+
value: remaining
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function recordSessionRunStart(session, { audit, run, actorType, observedEnd }) {
|
|
71
|
+
const openRun = {
|
|
72
|
+
...run,
|
|
73
|
+
agentName: auditAgentName(session.mode.get())
|
|
74
|
+
};
|
|
75
|
+
return serializeRunAudit(session, async () => {
|
|
76
|
+
const runs = await readOpenRuns(session);
|
|
77
|
+
if (!runs.some((existing) => existing.kickoffId === run.kickoffId)) await session.thread.setSetting({
|
|
78
|
+
key: FACTORY_OPEN_RUNS_SETTING,
|
|
79
|
+
value: [...runs, openRun]
|
|
80
|
+
});
|
|
81
|
+
await audit.record({
|
|
82
|
+
...runAuditInput(openRun),
|
|
83
|
+
actorId: run.startedBy,
|
|
84
|
+
actorType,
|
|
85
|
+
action: "factory.run.started"
|
|
86
|
+
});
|
|
87
|
+
await recordRunEnds(session, audit, observedEnd(), run.kickoffId);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function observeSessionRunEnd(session, { audit }) {
|
|
91
|
+
return session.subscribe((event) => {
|
|
92
|
+
if (event.type !== "agent_end" || !event.reason || event.reason === "suspended") return;
|
|
93
|
+
serializeRunAudit(session, () => recordRunEnds(session, audit, event.reason));
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
//#endregion
|
|
97
|
+
export { FACTORY_OPEN_RUNS_SETTING, observeSessionRunEnd, recordSessionRunStart };
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=run-audit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-audit.js","names":[],"sources":["../../src/session/run-audit.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { z } from 'zod';\n\nimport { auditAgentName } from '../storage/domains/audit/base.js';\nimport type { AuditActorType } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\n\nexport const FACTORY_OPEN_RUNS_SETTING = 'factoryOpenRuns';\n\nconst factoryOpenRunSchema = z.object({\n kickoffId: z.string(),\n bindingId: z.string(),\n role: z.string(),\n startedBy: z.string(),\n orgId: z.string(),\n factoryProjectId: z.string(),\n workItemId: z.string(),\n workItemName: z.string().optional(),\n sessionId: z.string(),\n threadId: z.string(),\n branch: z.string(),\n agentName: z.string(),\n});\n\nexport type FactoryOpenRun = z.infer<typeof factoryOpenRunSchema>;\n\nexport interface RunEndCaptureSession {\n readonly thread: {\n getSetting(args: { key: string }): Promise<unknown>;\n setSetting(args: { key: string; value: unknown }): Promise<void>;\n };\n readonly mode: { get(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\ntype RunEndReason = Extract<AgentControllerEvent, { type: 'agent_end' }>['reason'];\nconst pendingWrites = new WeakMap<RunEndCaptureSession, Promise<void>>();\n\nfunction serializeRunAudit(session: RunEndCaptureSession, write: () => Promise<void>): Promise<void> {\n const pending = (pendingWrites.get(session) ?? Promise.resolve())\n .then(write)\n .catch(error => console.warn('[Factory run audit] Unable to record run lifecycle.', error));\n pendingWrites.set(session, pending);\n return pending;\n}\n\nasync function readOpenRuns(session: RunEndCaptureSession): Promise<FactoryOpenRun[]> {\n const stored = await session.thread.getSetting({ key: FACTORY_OPEN_RUNS_SETTING });\n return z.array(factoryOpenRunSchema).parse(stored ?? []);\n}\n\nfunction runAuditInput(run: FactoryOpenRun) {\n const { orgId, factoryProjectId, workItemId, workItemName, ...metadata } = run;\n return {\n orgId,\n factoryProjectId,\n idempotencyKey: run.kickoffId,\n targets: [{ type: 'work_item', id: workItemId, ...(workItemName ? { name: workItemName } : {}) }],\n metadata,\n };\n}\n\nasync function recordRunEnds(\n session: RunEndCaptureSession,\n audit: AuditRecorder,\n reason: RunEndReason,\n kickoffId?: string,\n): Promise<void> {\n if (!reason || reason === 'suspended') return;\n const runs = await readOpenRuns(session);\n if (runs.length === 0) return;\n const remaining = [];\n for (const run of runs) {\n if (kickoffId && run.kickoffId !== kickoffId) {\n remaining.push(run);\n continue;\n }\n const input = runAuditInput(run);\n const recorded = await audit.record({\n ...input,\n actorId: `agent:${run.threadId}`,\n actorType: 'agent',\n action: 'factory.run.ended',\n metadata: { ...input.metadata, reason },\n });\n if (!recorded) remaining.push(run);\n }\n await session.thread.setSetting({ key: FACTORY_OPEN_RUNS_SETTING, value: remaining });\n}\n\nexport function recordSessionRunStart(\n session: RunEndCaptureSession,\n {\n audit,\n run,\n actorType,\n observedEnd,\n }: {\n audit: AuditRecorder;\n run: Omit<FactoryOpenRun, 'agentName'>;\n actorType: AuditActorType;\n observedEnd: () => RunEndReason;\n },\n): Promise<void> {\n const openRun = { ...run, agentName: auditAgentName(session.mode.get()) };\n return serializeRunAudit(session, async () => {\n const runs = await readOpenRuns(session);\n if (!runs.some(existing => existing.kickoffId === run.kickoffId)) {\n await session.thread.setSetting({ key: FACTORY_OPEN_RUNS_SETTING, value: [...runs, openRun] });\n }\n await audit.record({\n ...runAuditInput(openRun),\n actorId: run.startedBy,\n actorType,\n action: 'factory.run.started',\n });\n await recordRunEnds(session, audit, observedEnd(), run.kickoffId);\n });\n}\n\nexport function observeSessionRunEnd(session: RunEndCaptureSession, { audit }: { audit: AuditRecorder }): () => void {\n return session.subscribe(event => {\n if (event.type !== 'agent_end' || !event.reason || event.reason === 'suspended') return;\n void serializeRunAudit(session, () => recordRunEnds(session, audit, event.reason));\n });\n}\n"],"mappings":";;;AAOA,MAAa,4BAA4B;AAEzC,MAAM,uBAAuB,EAAE,OAAO;CACpC,WAAW,EAAE,OAAO;CACpB,WAAW,EAAE,OAAO;CACpB,MAAM,EAAE,OAAO;CACf,WAAW,EAAE,OAAO;CACpB,OAAO,EAAE,OAAO;CAChB,kBAAkB,EAAE,OAAO;CAC3B,YAAY,EAAE,OAAO;CACrB,cAAc,EAAE,OAAO,CAAC,CAAC,SAAS;CAClC,WAAW,EAAE,OAAO;CACpB,UAAU,EAAE,OAAO;CACnB,QAAQ,EAAE,OAAO;CACjB,WAAW,EAAE,OAAO;AACtB,CAAC;AAcD,MAAM,gCAAgB,IAAI,QAA6C;AAEvE,SAAS,kBAAkB,SAA+B,OAA2C;CACnG,MAAM,WAAW,cAAc,IAAI,OAAO,KAAK,QAAQ,QAAQ,EAAA,CAC5D,KAAK,KAAK,CAAC,CACX,OAAM,UAAS,QAAQ,KAAK,uDAAuD,KAAK,CAAC;CAC5F,cAAc,IAAI,SAAS,OAAO;CAClC,OAAO;AACT;AAEA,eAAe,aAAa,SAA0D;CACpF,MAAM,SAAS,MAAM,QAAQ,OAAO,WAAW,EAAE,KAAK,0BAA0B,CAAC;CACjF,OAAO,EAAE,MAAM,oBAAoB,CAAC,CAAC,MAAM,UAAU,CAAC,CAAC;AACzD;AAEA,SAAS,cAAc,KAAqB;CAC1C,MAAM,EAAE,OAAO,kBAAkB,YAAY,cAAc,GAAG,aAAa;CAC3E,OAAO;EACL;EACA;EACA,gBAAgB,IAAI;EACpB,SAAS,CAAC;GAAE,MAAM;GAAa,IAAI;GAAY,GAAI,eAAe,EAAE,MAAM,aAAa,IAAI,CAAC;EAAG,CAAC;EAChG;CACF;AACF;AAEA,eAAe,cACb,SACA,OACA,QACA,WAC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CAAC;AACH"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Two tool observers read the same `gh pr create`, so the reading lives here rather than once per observer. */
|
|
2
|
+
/** Heredoc bodies dropped, so prose inside a document never reads as a command. */
|
|
3
|
+
export declare function executableCommand(command: string): string;
|
|
4
|
+
export declare function runsPullRequestCreate(command: string): boolean;
|
|
5
|
+
//# sourceMappingURL=shell-commands.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shell-commands.d.ts","sourceRoot":"","sources":["../../src/session/shell-commands.ts"],"names":[],"mappings":"AAAA,gHAAgH;AAIhH,mFAAmF;AACnF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAgBzD;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9D"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/session/shell-commands.ts
|
|
2
|
+
/** Two tool observers read the same `gh pr create`, so the reading lives here rather than once per observer. */
|
|
3
|
+
const GH_PR_CREATE_RE = /(?:^|\n|;|&&|\|\|)\s*gh\s+pr\s+create(?:\s|$)/;
|
|
4
|
+
/** Heredoc bodies dropped, so prose inside a document never reads as a command. */
|
|
5
|
+
function executableCommand(command) {
|
|
6
|
+
const lines = command.split("\n");
|
|
7
|
+
const executableLines = [];
|
|
8
|
+
let delimiter;
|
|
9
|
+
for (const line of lines) {
|
|
10
|
+
if (delimiter) {
|
|
11
|
+
if (line.trim() === delimiter) delimiter = void 0;
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
executableLines.push(line);
|
|
15
|
+
delimiter = line.match(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/)?.[2];
|
|
16
|
+
}
|
|
17
|
+
return executableLines.join("\n");
|
|
18
|
+
}
|
|
19
|
+
function runsPullRequestCreate(command) {
|
|
20
|
+
return GH_PR_CREATE_RE.test(executableCommand(command));
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { executableCommand, runsPullRequestCreate };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=shell-commands.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shell-commands.js","names":[],"sources":["../../src/session/shell-commands.ts"],"sourcesContent":["/** Two tool observers read the same `gh pr create`, so the reading lives here rather than once per observer. */\n\nconst GH_PR_CREATE_RE = /(?:^|\\n|;|&&|\\|\\|)\\s*gh\\s+pr\\s+create(?:\\s|$)/;\n\n/** Heredoc bodies dropped, so prose inside a document never reads as a command. */\nexport function executableCommand(command: string): string {\n const lines = command.split('\\n');\n const executableLines: string[] = [];\n let delimiter: string | undefined;\n\n for (const line of lines) {\n if (delimiter) {\n if (line.trim() === delimiter) delimiter = undefined;\n continue;\n }\n executableLines.push(line);\n const heredoc = line.match(/<<-?\\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\\1/);\n delimiter = heredoc?.[2];\n }\n\n return executableLines.join('\\n');\n}\n\nexport function runsPullRequestCreate(command: string): boolean {\n return GH_PR_CREATE_RE.test(executableCommand(command));\n}\n"],"mappings":";;AAEA,MAAM,kBAAkB;;AAGxB,SAAgB,kBAAkB,SAAyB;CACzD,MAAM,QAAQ,QAAQ,MAAM,IAAI;CAChC,MAAM,kBAA4B,CAAC;CACnC,IAAI;CAEJ,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,WAAW;GACb,IAAI,KAAK,KAAK,MAAM,WAAW,YAAY,KAAA;GAC3C;EACF;EACA,gBAAgB,KAAK,IAAI;EAEzB,YADgB,KAAK,MAAM,0CACT,CAAC,GAAG;CACxB;CAEA,OAAO,gBAAgB,KAAK,IAAI;AAClC;AAEA,SAAgB,sBAAsB,SAA0B;CAC9D,OAAO,gBAAgB,KAAK,kBAAkB,OAAO,CAAC;AACxD"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every action the trail can hold, by namespace. Register new ones in the
|
|
3
|
+
* WorkOS dashboard under Audit Logs → Events before the mirror accepts them.
|
|
4
|
+
*/
|
|
5
|
+
export declare const AUDIT_ACTIONS: {
|
|
6
|
+
readonly work_item: readonly ["created", "updated", "deleted", "stage_moved", "transition_rejected", "comment_created", "comment_edited", "comment_deleted", "comment_mentioned", "labels_reconciled"];
|
|
7
|
+
readonly run: readonly ["started", "ended", "approved", "dismissed", "retry"];
|
|
8
|
+
readonly git: readonly ["commit", "push", "pr_opened"];
|
|
9
|
+
readonly agent: readonly ["commit", "push", "pr_opened", "signaled"];
|
|
10
|
+
readonly intake: readonly ["config_updated", "binding_updated", "label_route_updated"];
|
|
11
|
+
};
|
|
12
|
+
export type AuditNamespace = keyof typeof AUDIT_ACTIONS;
|
|
13
|
+
export type AuditAction = {
|
|
14
|
+
[Namespace in AuditNamespace]: `factory.${Namespace}.${(typeof AUDIT_ACTIONS)[Namespace][number]}`;
|
|
15
|
+
}[AuditNamespace];
|
|
16
|
+
export declare function isAuditNamespace(value: string): value is AuditNamespace;
|
|
17
|
+
export declare function auditNamespaces(): AuditNamespace[];
|
|
18
|
+
export declare function parseAuditAction(action: string): {
|
|
19
|
+
namespace: AuditNamespace;
|
|
20
|
+
leaf: string;
|
|
21
|
+
} | undefined;
|
|
22
|
+
export declare function isAuditAction(value: string): value is AuditAction;
|
|
23
|
+
export declare function auditActionsInNamespaces(namespaces: readonly AuditNamespace[]): string[];
|
|
24
|
+
//# sourceMappingURL=actions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,aAAa;;;;;;CAiBhB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,MAAM,OAAO,aAAa,CAAC;AAExD,MAAM,MAAM,WAAW,GAAG;KACvB,SAAS,IAAI,cAAc,GAAG,WAAW,SAAS,IAAI,CAAC,OAAO,aAAa,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE;CACnG,CAAC,cAAc,CAAC,CAAC;AAElB,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,cAAc,CAEvE;AAED,wBAAgB,eAAe,IAAI,cAAc,EAAE,CAElD;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAIxG;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,WAAW,CAGjE;AAED,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,SAAS,cAAc,EAAE,GAAG,MAAM,EAAE,CAExF"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
//#region src/storage/domains/audit/actions.ts
|
|
2
|
+
/**
|
|
3
|
+
* Every action the trail can hold, by namespace. Register new ones in the
|
|
4
|
+
* WorkOS dashboard under Audit Logs → Events before the mirror accepts them.
|
|
5
|
+
*/
|
|
6
|
+
const AUDIT_ACTIONS = {
|
|
7
|
+
work_item: [
|
|
8
|
+
"created",
|
|
9
|
+
"updated",
|
|
10
|
+
"deleted",
|
|
11
|
+
"stage_moved",
|
|
12
|
+
"transition_rejected",
|
|
13
|
+
"comment_created",
|
|
14
|
+
"comment_edited",
|
|
15
|
+
"comment_deleted",
|
|
16
|
+
"comment_mentioned",
|
|
17
|
+
"labels_reconciled"
|
|
18
|
+
],
|
|
19
|
+
run: [
|
|
20
|
+
"started",
|
|
21
|
+
"ended",
|
|
22
|
+
"approved",
|
|
23
|
+
"dismissed",
|
|
24
|
+
"retry"
|
|
25
|
+
],
|
|
26
|
+
git: [
|
|
27
|
+
"commit",
|
|
28
|
+
"push",
|
|
29
|
+
"pr_opened"
|
|
30
|
+
],
|
|
31
|
+
agent: [
|
|
32
|
+
"commit",
|
|
33
|
+
"push",
|
|
34
|
+
"pr_opened",
|
|
35
|
+
"signaled"
|
|
36
|
+
],
|
|
37
|
+
intake: [
|
|
38
|
+
"config_updated",
|
|
39
|
+
"binding_updated",
|
|
40
|
+
"label_route_updated"
|
|
41
|
+
]
|
|
42
|
+
};
|
|
43
|
+
function isAuditNamespace(value) {
|
|
44
|
+
return Object.hasOwn(AUDIT_ACTIONS, value);
|
|
45
|
+
}
|
|
46
|
+
function auditNamespaces() {
|
|
47
|
+
return Object.keys(AUDIT_ACTIONS).filter(isAuditNamespace);
|
|
48
|
+
}
|
|
49
|
+
function parseAuditAction(action) {
|
|
50
|
+
const [prefix, namespace, leaf, ...rest] = action.split(".");
|
|
51
|
+
if (prefix !== "factory" || namespace === void 0 || leaf === void 0 || rest.length > 0) return void 0;
|
|
52
|
+
return isAuditNamespace(namespace) ? {
|
|
53
|
+
namespace,
|
|
54
|
+
leaf
|
|
55
|
+
} : void 0;
|
|
56
|
+
}
|
|
57
|
+
function isAuditAction(value) {
|
|
58
|
+
const parsed = parseAuditAction(value);
|
|
59
|
+
return parsed !== void 0 && AUDIT_ACTIONS[parsed.namespace].some((leaf) => leaf === parsed.leaf);
|
|
60
|
+
}
|
|
61
|
+
function auditActionsInNamespaces(namespaces) {
|
|
62
|
+
return namespaces.flatMap((namespace) => AUDIT_ACTIONS[namespace].map((leaf) => `factory.${namespace}.${leaf}`));
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
export { AUDIT_ACTIONS, auditActionsInNamespaces, auditNamespaces, isAuditAction, isAuditNamespace, parseAuditAction };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=actions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"actions.js","names":[],"sources":["../../../../src/storage/domains/audit/actions.ts"],"sourcesContent":["/**\n * Every action the trail can hold, by namespace. Register new ones in the\n * WorkOS dashboard under Audit Logs → Events before the mirror accepts them.\n */\nexport const AUDIT_ACTIONS = {\n work_item: [\n 'created',\n 'updated',\n 'deleted',\n 'stage_moved',\n 'transition_rejected',\n 'comment_created',\n 'comment_edited',\n 'comment_deleted',\n 'comment_mentioned',\n 'labels_reconciled',\n ],\n run: ['started', 'ended', 'approved', 'dismissed', 'retry'],\n git: ['commit', 'push', 'pr_opened'],\n agent: ['commit', 'push', 'pr_opened', 'signaled'],\n intake: ['config_updated', 'binding_updated', 'label_route_updated'],\n} as const;\n\nexport type AuditNamespace = keyof typeof AUDIT_ACTIONS;\n\nexport type AuditAction = {\n [Namespace in AuditNamespace]: `factory.${Namespace}.${(typeof AUDIT_ACTIONS)[Namespace][number]}`;\n}[AuditNamespace];\n\nexport function isAuditNamespace(value: string): value is AuditNamespace {\n return Object.hasOwn(AUDIT_ACTIONS, value);\n}\n\nexport function auditNamespaces(): AuditNamespace[] {\n return Object.keys(AUDIT_ACTIONS).filter(isAuditNamespace);\n}\n\nexport function parseAuditAction(action: string): { namespace: AuditNamespace; leaf: string } | undefined {\n const [prefix, namespace, leaf, ...rest] = action.split('.');\n if (prefix !== 'factory' || namespace === undefined || leaf === undefined || rest.length > 0) return undefined;\n return isAuditNamespace(namespace) ? { namespace, leaf } : undefined;\n}\n\nexport function isAuditAction(value: string): value is AuditAction {\n const parsed = parseAuditAction(value);\n return parsed !== undefined && AUDIT_ACTIONS[parsed.namespace].some(leaf => leaf === parsed.leaf);\n}\n\nexport function auditActionsInNamespaces(namespaces: readonly AuditNamespace[]): string[] {\n return namespaces.flatMap(namespace => AUDIT_ACTIONS[namespace].map(leaf => `factory.${namespace}.${leaf}`));\n}\n"],"mappings":";;;;;AAIA,MAAa,gBAAgB;CAC3B,WAAW;EACT;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,KAAK;EAAC;EAAW;EAAS;EAAY;EAAa;CAAO;CAC1D,KAAK;EAAC;EAAU;EAAQ;CAAW;CACnC,OAAO;EAAC;EAAU;EAAQ;EAAa;CAAU;CACjD,QAAQ;EAAC;EAAkB;EAAmB;CAAqB;AACrE;AAQA,SAAgB,iBAAiB,OAAwC;CACvE,OAAO,OAAO,OAAO,eAAe,KAAK;AAC3C;AAEA,SAAgB,kBAAoC;CAClD,OAAO,OAAO,KAAK,aAAa,CAAC,CAAC,OAAO,gBAAgB;AAC3D;AAEA,SAAgB,iBAAiB,QAAyE;CACxG,MAAM,CAAC,QAAQ,WAAW,MAAM,GAAG,QAAQ,OAAO,MAAM,GAAG;CAC3D,IAAI,WAAW,aAAa,cAAc,KAAA,KAAa,SAAS,KAAA,KAAa,KAAK,SAAS,GAAG,OAAO,KAAA;CACrG,OAAO,iBAAiB,SAAS,IAAI;EAAE;EAAW;CAAK,IAAI,KAAA;AAC7D;AAEA,SAAgB,cAAc,OAAqC;CACjE,MAAM,SAAS,iBAAiB,KAAK;CACrC,OAAO,WAAW,KAAA,KAAa,cAAc,OAAO,UAAU,CAAC,MAAK,SAAQ,SAAS,OAAO,IAAI;AAClG;AAEA,SAAgB,yBAAyB,YAAiD;CACxF,OAAO,WAAW,SAAQ,cAAa,cAAc,UAAU,CAAC,KAAI,SAAQ,WAAW,UAAU,GAAG,MAAM,CAAC;AAC7G"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const AUDIT_ACTOR_TYPES: readonly ["human", "agent", "system"];
|
|
2
|
+
export type AuditActorType = (typeof AUDIT_ACTOR_TYPES)[number];
|
|
3
|
+
export declare function isAuditActorType(value: unknown): value is AuditActorType;
|
|
4
|
+
export declare function isHumanActorId(actorId: string | undefined): actorId is string;
|
|
5
|
+
//# sourceMappingURL=actors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"actors.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actors.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,iBAAiB,uCAAwC,CAAC;AAEvE,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEhE,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,cAAc,CAExE;AAWD,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,IAAI,MAAM,CAG7E"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/storage/domains/audit/actors.ts
|
|
2
|
+
const AUDIT_ACTOR_TYPES = [
|
|
3
|
+
"human",
|
|
4
|
+
"agent",
|
|
5
|
+
"system"
|
|
6
|
+
];
|
|
7
|
+
function isAuditActorType(value) {
|
|
8
|
+
return AUDIT_ACTOR_TYPES.some((type) => type === value);
|
|
9
|
+
}
|
|
10
|
+
/** Ids the factory writes for itself: never a person, so never a profile lookup. */
|
|
11
|
+
const AUTOMATION_ACTORS = /* @__PURE__ */ new Set([
|
|
12
|
+
"factory",
|
|
13
|
+
"system",
|
|
14
|
+
"automation",
|
|
15
|
+
"factory-rule-dispatcher",
|
|
16
|
+
"factory-tool-result-rule"
|
|
17
|
+
]);
|
|
18
|
+
function isHumanActorId(actorId) {
|
|
19
|
+
if (!actorId) return false;
|
|
20
|
+
return !AUTOMATION_ACTORS.has(actorId) && !actorId.startsWith("agent:") && !actorId.startsWith("github:");
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
export { AUDIT_ACTOR_TYPES, isAuditActorType, isHumanActorId };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=actors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"actors.js","names":[],"sources":["../../../../src/storage/domains/audit/actors.ts"],"sourcesContent":["export const AUDIT_ACTOR_TYPES = ['human', 'agent', 'system'] as const;\n\nexport type AuditActorType = (typeof AUDIT_ACTOR_TYPES)[number];\n\nexport function isAuditActorType(value: unknown): value is AuditActorType {\n return AUDIT_ACTOR_TYPES.some(type => type === value);\n}\n\n/** Ids the factory writes for itself: never a person, so never a profile lookup. */\nconst AUTOMATION_ACTORS = new Set([\n 'factory',\n 'system',\n 'automation',\n 'factory-rule-dispatcher',\n 'factory-tool-result-rule',\n]);\n\nexport function isHumanActorId(actorId: string | undefined): actorId is string {\n if (!actorId) return false;\n return !AUTOMATION_ACTORS.has(actorId) && !actorId.startsWith('agent:') && !actorId.startsWith('github:');\n}\n"],"mappings":";AAAA,MAAa,oBAAoB;CAAC;CAAS;CAAS;AAAQ;AAI5D,SAAgB,iBAAiB,OAAyC;CACxE,OAAO,kBAAkB,MAAK,SAAQ,SAAS,KAAK;AACtD;;AAGA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,eAAe,SAAgD;CAC7E,IAAI,CAAC,SAAS,OAAO;CACrB,OAAO,CAAC,kBAAkB,IAAI,OAAO,KAAK,CAAC,QAAQ,WAAW,QAAQ,KAAK,CAAC,QAAQ,WAAW,SAAS;AAC1G"}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* observer detects externally-visible git side effects and delegates recording
|
|
6
|
-
* to the factory-owned audit domain.
|
|
2
|
+
* Git and GitHub actions performed by agents inside runs never touch web routes,
|
|
3
|
+
* so this observer detects their externally-visible side effects in the command
|
|
4
|
+
* and delegates recording to the factory-owned audit domain.
|
|
7
5
|
*/
|
|
8
6
|
import type { RequestContext } from '@mastra/core/request-context';
|
|
9
7
|
import type { AuditAgentEmitter } from './domain.js';
|
|
@@ -15,8 +13,8 @@ interface ToolObserverContext {
|
|
|
15
13
|
context: RequestContext;
|
|
16
14
|
}
|
|
17
15
|
/**
|
|
18
|
-
* Detect externally-visible git side effects in a completed tool
|
|
19
|
-
* record `factory.agent.*` audit events for them. One command can emit
|
|
16
|
+
* Detect externally-visible git and GitHub side effects in a completed tool
|
|
17
|
+
* call and record `factory.agent.*` audit events for them. One command can emit
|
|
20
18
|
* multiple events (`git commit && git push` emits both). Never throws.
|
|
21
19
|
*/
|
|
22
20
|
export declare function observeAgentGitAction({ audit, toolContext, }: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-audit.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/agent-audit.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"agent-audit.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/agent-audit.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAIrD,UAAU,mBAAmB;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,cAAc,CAAC;CACzB;AA2BD;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,EAC1C,KAAK,EACL,WAAW,GACZ,EAAE;IACD,KAAK,EAAE,iBAAiB,CAAC;IACzB,WAAW,EAAE,mBAAmB,CAAC;CAClC,GAAG,OAAO,CAAC,IAAI,CAAC,CA4ChB"}
|