@mastra/factory 0.29.0-alpha.7 → 0.29.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -20
- package/dist/boards/board-events.d.ts +23 -0
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +37 -3
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts +6 -4
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +9 -6
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/intake-routing.d.ts +30 -16
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +41 -28
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/project-boards.d.ts +15 -0
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +43 -7
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/factory.d.ts +4 -14
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +22 -15
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +101 -0
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +7 -3
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +7 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +15 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +1 -1
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +2 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.d.ts +1 -0
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +4 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/slack/run-error-card.js +6 -1
- package/dist/integrations/slack/run-error-card.js.map +1 -1
- package/dist/links.d.ts +4 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +5 -3
- package/dist/links.js.map +1 -1
- package/dist/routes/boards.d.ts +1 -1
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/contracts.d.ts +32 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +36 -9
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-check.d.ts.map +1 -1
- package/dist/routes/intake-check.js +3 -1
- package/dist/routes/intake-check.js.map +1 -1
- package/dist/routes/intake-routes.d.ts +0 -3
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +1 -1
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/skills.d.ts +1 -1
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +92 -28
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/surface.d.ts +0 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +0 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +6 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +10 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +74 -32
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +3 -2
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +5 -3
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/public-failure-reason.d.ts +11 -0
- package/dist/rules/public-failure-reason.d.ts.map +1 -0
- package/dist/rules/public-failure-reason.js +136 -0
- package/dist/rules/public-failure-reason.js.map +1 -0
- package/dist/rules/transition-service.d.ts +13 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +5 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +12 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +11 -2
- package/dist/rules/validation.js.map +1 -1
- package/dist/run-error.d.ts +1 -1
- package/dist/run-error.d.ts.map +1 -1
- package/dist/run-error.js +21 -12
- package/dist/run-error.js.map +1 -1
- package/dist/session/environment-state-processor.d.ts.map +1 -1
- package/dist/session/environment-state-processor.js +6 -2
- package/dist/session/environment-state-processor.js.map +1 -1
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +5 -3
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/skills/app-skills.d.ts +3 -2
- package/dist/skills/app-skills.d.ts.map +1 -1
- package/dist/skills/app-skills.js +5 -3
- package/dist/skills/app-skills.js.map +1 -1
- package/dist/skills/catalog.d.ts +23 -4
- package/dist/skills/catalog.d.ts.map +1 -1
- package/dist/skills/catalog.js +61 -28
- package/dist/skills/catalog.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +6 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +12 -0
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +3 -0
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +4 -0
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
- package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
- package/dist/storage/domains/skill-overrides/base.js +54 -1
- package/dist/storage/domains/skill-overrides/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +13 -5
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +1 -1
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +0 -1
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +0 -3
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +2 -1
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/workspace.d.ts +5 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +69 -9
- package/dist/workspace.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-control-tools.js","names":[],"sources":["../../src/session/source-control-tools.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { z } from 'zod';\n\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../auth.js';\nimport type { CommitCheck, CommitCheckStatus, VersionControl } from '../capabilities/version-control.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport {\n ensureLocalBranch,\n isCheckoutOf,\n pushRepositoryBranch,\n refreshMergeRequestCheckout,\n} from '../integrations/github/sandbox.js';\nimport { normalizedVerdictLine } from '../review-verdict.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { resolveSessionWorkdir } from '../sandbox/session-sandbox.js';\nimport type { AuditAgentEmitter } from '../storage/domains/audit/domain.js';\nimport type {\n ProjectRepository,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { mergeRequestNumberFromBranch } from '../work-item-branch.js';\nimport { environmentSlugs, findEnvironmentRepository, resolveSessionRepositories } from './environment-repositories.js';\nimport { updateSessionEnvironmentRepository } from './environment-state-processor.js';\nimport type { ChangeTarget } from './self-review-gate.js';\n\ntype RepositorySessionState = {\n factoryProjectId?: string;\n projectRepositoryId?: string;\n};\n\nexport interface SourceControlToolProvider {\n id: string;\n storage: SourceControlStorageHandle;\n versionControl: VersionControl;\n}\n\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n provider: SourceControlToolProvider;\n session: SourceControlSession;\n projectRepository: ProjectRepository;\n repository: SourceControlRepository;\n orgId: string;\n userId: string;\n /** True when the target is the link the session is filed under, the default. */\n ownRepository: boolean;\n}\n\ntype ReviewEvent = 'approve' | 'request-changes' | 'comment';\n\n/** Returns why a review's leading `Verdict:` line contradicts the submitted event, if it does. */\nexport function verdictEventMismatch(event: ReviewEvent, body: string | undefined): string | undefined {\n const match = /^verdict: ?(approve|request changes|changes requested)\\b/.exec(normalizedVerdictLine(body) ?? '');\n if (!match) return undefined;\n const verdict = match[1] === 'approve' ? 'approve' : 'request changes';\n // GitLab has no request-changes state, so a blocking verdict is published as a comment review.\n const allowed: ReviewEvent[] = verdict === 'approve' ? ['approve'] : ['request-changes', 'comment'];\n if (allowed.includes(event)) return undefined;\n return `Review body opens with \"Verdict: ${verdict}\" but event is \"${event}\". Nothing was posted. Use event ${allowed\n .map(e => `\"${e}\"`)\n .join(' or ')} for this body, or regenerate the body for the verdict you intend.`;\n}\n\nconst REVIEWED_HEAD_LINE = /^[\\s*_>-]*reviewed head[*_]*:[*_]*\\s*(.*)$/gim;\nconst FULL_SHA = /^`?([0-9a-f]{40}|[0-9a-f]{64})`?(?:\\s|$)/i;\n\n/**\n * Returns the full SHA named by the body's `Reviewed head:` lines, `null` when any line is malformed or the lines\n * disagree, or `undefined` when absent.\n */\nexport function reviewedHeadFromBody(body: string | undefined): string | null | undefined {\n const shas = new Set(\n [...(body ?? '').matchAll(REVIEWED_HEAD_LINE)].map(\n line => FULL_SHA.exec(line[1]!.trim())?.[1]?.toLowerCase() ?? null,\n ),\n );\n if (shas.size === 0) return undefined;\n if (shas.size > 1) return null;\n return [...shas][0];\n}\n\nfunction authIdentity(requestContext: RequestContext) {\n const user = getFactoryAuthUserFromContext(requestContext);\n return { orgId: getFactoryAuthOrgId(user), userId: getFactoryAuthUserId(user) };\n}\n\nasync function resolveProviderSession(\n sessionId: string,\n providers: readonly SourceControlToolProvider[],\n): Promise<{ provider: SourceControlToolProvider; session: SourceControlSession }> {\n const matches = (\n await Promise.all(\n providers.map(async provider => ({\n provider,\n session: await provider.storage.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { provider: SourceControlToolProvider; session: SourceControlSession } => match.session !== null,\n );\n if (matches.length !== 1) {\n throw new Error(\n matches.length === 0\n ? 'The active session is not backed by a source-control repository.'\n : 'The active session is ambiguous across source-control providers.',\n );\n }\n return matches[0]!;\n}\n\nasync function resolveSessionTarget(\n requestContext: RequestContext,\n providers: readonly SourceControlToolProvider[],\n options: { repository?: string } = {},\n): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const { orgId, userId } = authIdentity(requestContext);\n if (!context?.sessionId || !orgId || !userId) {\n throw new Error('Source-control tools require an authenticated repository session.');\n }\n\n const { provider, session } = await resolveProviderSession(context.sessionId, providers);\n if (session.orgId !== orgId || (session.visibility === 'private' && session.userId !== userId)) {\n throw new Error('The active source-control session is not available to the authenticated user.');\n }\n const ownRepository = session.projectRepositoryId\n ? await provider.storage.projectRepositories.get({ orgId, id: session.projectRepositoryId })\n : null;\n if (!ownRepository) throw new Error('The active project repository was not found.');\n const state = context.getState();\n if (state.projectRepositoryId && state.projectRepositoryId !== ownRepository.id) {\n throw new Error('The active source-control session does not match its controller repository.');\n }\n const ownConnection = await provider.storage.connections.get({ orgId, id: ownRepository.connectionId });\n if (!ownConnection) throw new Error('The active source-control connection was not found.');\n if (state.factoryProjectId && state.factoryProjectId !== ownConnection.factoryProjectId) {\n throw new Error('The active source-control session does not match its Factory project.');\n }\n\n if (options.repository !== undefined) {\n const candidates = await resolveSessionRepositories({ sourceControl: provider.storage, session });\n const match = findEnvironmentRepository(candidates, options.repository);\n if (!match) {\n throw new Error(\n `Repository '${options.repository}' is not in this Factory's environment. Valid repositories: ${environmentSlugs(candidates).join(', ')}.`,\n );\n }\n return {\n context,\n provider,\n session,\n projectRepository: match.link,\n repository: match.repository,\n orgId,\n userId,\n ownRepository: match.link.id === ownRepository.id,\n };\n }\n\n const repository = await provider.storage.repositories.get({ orgId, id: ownRepository.repositoryId });\n if (!repository) throw new Error('The active source-control repository was not found.');\n return {\n context,\n provider,\n session,\n projectRepository: ownRepository,\n repository,\n orgId,\n userId,\n ownRepository: true,\n };\n}\n\n/**\n * The slugs a session may target and the one it is filed under, for the tool\n * descriptions. `undefined` when the session cannot be resolved; the tools\n * then describe the default without naming it.\n */\nasync function describeSessionRepositories(\n sessionId: string,\n providers: readonly SourceControlToolProvider[],\n): Promise<{ slugs: string[]; own: string | undefined } | undefined> {\n try {\n const { provider, session } = await resolveProviderSession(sessionId, providers);\n const repositories = await resolveSessionRepositories({ sourceControl: provider.storage, session });\n const own = repositories.find(candidate => candidate.link.id === session.projectRepositoryId);\n return { slugs: environmentSlugs(repositories), own: own?.repository.slug };\n } catch {\n return undefined;\n }\n}\n\nfunction repositoryArgumentDescription(described: { slugs: string[]; own: string | undefined } | undefined): string {\n if (!described || described.slugs.length === 0) {\n return \"Optional `repository` (owner/name) selects another repository of this Factory's environment; defaults to this session's repository.\";\n }\n const fallback = described.own ? `${described.own}, this session's repository` : \"this session's repository\";\n return `Optional \\`repository\\` (owner/name) selects one of this Factory's environment repositories: ${described.slugs.join(', ')}. Defaults to ${fallback}.`;\n}\n\nfunction changeRequestId(value: string | number): string {\n return String(value);\n}\n\nfunction executableSandbox(value: unknown): WorkspaceSandbox & ExecutableSandbox {\n const sandbox = value as Partial<ExecutableSandbox> | undefined;\n if (!sandbox?.executeCommand) throw new Error('The active Factory workspace has no executable sandbox.');\n return sandbox as WorkspaceSandbox & ExecutableSandbox;\n}\n\nasync function emitAgentAudit(\n audit: AuditAgentEmitter,\n requestContext: RequestContext,\n input: Parameters<AuditAgentEmitter['emitAgent']>[0]['input'],\n): Promise<void> {\n try {\n await audit.emitAgent({ requestContext, input });\n } catch (error) {\n console.warn('[Audit] Failed to record brokered source-control action', {\n action: input.action,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction changeTarget(target: SessionTarget): ChangeTarget {\n return { slug: target.repository.slug, ownRepository: target.ownRepository };\n}\n\nconst repositorySchema = z.object({ repository: z.string().trim().min(1).optional() });\nconst changeRequestSchema = repositorySchema.extend({\n changeRequestId: z.union([z.string().trim().min(1), z.number().int().positive()]),\n});\n\nexport async function createSourceControlTools({\n requestContext,\n providers,\n audit,\n workItem,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n audit: AuditAgentEmitter;\n /** The session's card, when it is bound to one. */\n workItem?: {\n /**\n * Self-review gate for opening a change request in `target`. `undefined` means\n * it is not gated (no Work item, another repository than the card's, or its\n * change request predates Self-review); `null` means Self-review has not\n * approved; a SHA is the approved head.\n */\n selfReviewApprovedHead(target: ChangeTarget): Promise<string | null | undefined>;\n /** Records `target` as the card's repository when the card names none. */\n recordRepository(sourceControl: SourceControlStorageHandle, target: ChangeTarget): Promise<void>;\n };\n}): Promise<IntegrationTools> {\n if (!requestContext || typeof (requestContext as { get?: unknown }).get !== 'function') return {};\n const controller = requestContext.get('controller') as\n | AgentControllerRequestContext<RepositorySessionState>\n | undefined;\n const identity = authIdentity(requestContext);\n if (!controller?.sessionId || !identity.orgId || !identity.userId || providers.length === 0) return {};\n\n const repositoryArgument = repositoryArgumentDescription(\n await describeSessionRepositories(controller.sessionId, providers),\n );\n const withTarget = (options?: { repository?: string }) => resolveSessionTarget(requestContext, providers, options);\n const targetFor = (input: { repository?: string }) =>\n withTarget(input.repository !== undefined ? { repository: input.repository } : undefined);\n const reference = async (target: SessionTarget) => ({\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n });\n\n return {\n source_control_refresh_change_request_checkout: createTool({\n id: 'source_control_refresh_change_request_checkout',\n description:\n 'Refresh the active GitLab review session checkout to its current MR head. The MR, repository, branch, and credential are resolved server-side; no provider credentials enter the agent workspace.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const mergeRequestNumber = mergeRequestNumberFromBranch(target.session.branch);\n if (target.provider.id !== 'gitlab' || mergeRequestNumber === undefined) {\n throw new Error('Checkout refresh is only available in a bound GitLab merge-request review session.');\n }\n const ref = await reference(target);\n const mergeRequest = await target.provider.versionControl.getPullRequest({\n ...ref,\n pullRequestId: String(mergeRequestNumber),\n });\n if (!mergeRequest || mergeRequest.state !== 'open' || mergeRequest.merged) {\n throw new Error('The bound GitLab merge request is no longer open.');\n }\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n const result = await refreshMergeRequestCheckout(sandbox, workdir, {\n branch: target.session.branch,\n mergeRequestNumber,\n expectedHeadSha: mergeRequest.headSha,\n access,\n });\n return result;\n },\n }),\n source_control_push_branch: createTool({\n id: 'source_control_push_branch',\n description: `Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, remote, or branch arguments. ${repositoryArgument}`,\n inputSchema: repositorySchema,\n execute: async (input, { workspace }) => {\n const target = await targetFor(input);\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n // Another environment repository's directory may not be its checkout:\n // a boot skips a link whose directory name collides with another's, and\n // a session that booted single-repository has no siblings at all.\n if (!target.ownRepository && !(await isCheckoutOf(sandbox, workdir, access.cloneUrl))) {\n throw new Error(`There is no checkout of ${target.repository.slug} in this session.`);\n }\n const branch = target.session.branch;\n // Materialize the session branch at the active HEAD without discarding\n // session-only commits, so the push includes the agent's current work.\n await ensureLocalBranch(sandbox, workdir, branch);\n await pushRepositoryBranch(sandbox, workdir, branch, access, target.repository.slug);\n await target.provider.storage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: target.projectRepository.id,\n branch,\n });\n updateSessionEnvironmentRepository(target.session.sessionId, target.repository.slug, { branch });\n await workItem?.recordRepository(target.provider.storage, changeTarget(target));\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.push',\n targets: [{ type: 'repository', id: target.repository.slug }],\n metadata: { branch, provider: target.provider.id, repository: target.repository.slug },\n });\n return { pushed: true, branch, repository: target.repository.slug };\n },\n }),\n source_control_get_change_request: createTool({\n id: 'source_control_get_change_request',\n description: `Read a pull request or merge request in the active Factory repository by its numeric repository-local ID. ${repositoryArgument}`,\n inputSchema: changeRequestSchema,\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n },\n }),\n source_control_list_change_request_reviews: createTool({\n id: 'source_control_list_change_request_reviews',\n description: `List submitted reviews and approvals on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listReviews({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_change_request: createTool({\n id: 'source_control_create_change_request',\n description: `Open a pull request or merge request from the active Factory session branch into the repository's base branch (the session's persisted base branch in its own repository, the linked or default branch elsewhere). Push the branch with source_control_push_branch first. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({\n title: z.string().trim().min(1),\n body: z.string().optional(),\n draft: z.boolean().optional(),\n }),\n execute: async (input, execution) => {\n const target = await targetFor(input);\n const approvedHead = await workItem?.selfReviewApprovedHead(changeTarget(target));\n if (approvedHead === null) {\n throw new Error(\n 'Self-review has not approved this branch. Move the work item to Self-review; the change request opens after it approves.',\n );\n }\n const baseBranch = target.ownRepository\n ? target.session.baseBranch\n : (target.projectRepository.branch ?? target.repository.defaultBranch);\n const created = await target.provider.versionControl.createPullRequest({\n ...(await reference(target)),\n title: input.title,\n ...(input.body !== undefined ? { body: input.body } : {}),\n baseBranch,\n headBranch: target.session.branch,\n ...(input.draft !== undefined ? { draft: input.draft } : {}),\n });\n if (approvedHead !== undefined && created.headSha.toLowerCase() !== approvedHead.toLowerCase()) {\n await target.provider.versionControl.closePullRequest({\n ...(await reference(target)),\n pullRequestId: created.id,\n });\n throw new Error(\n `Self-review approved ${approvedHead}, but the pushed branch is at ${created.headSha}; the change request was closed. Push the approved head, or move the work item back to Self-review to review the new commits.`,\n );\n }\n await target.provider.storage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: target.projectRepository.id,\n // Opening a change request pushes nothing: an existing row keeps its\n // `pushedAt`; the branch only seeds a row no push wrote yet.\n fallbackBranch: target.session.branch,\n changeRequestId: changeRequestId(created.id),\n changeRequestUrl: created.url,\n });\n updateSessionEnvironmentRepository(target.session.sessionId, target.repository.slug, {\n changeRequestUrl: created.url,\n });\n await workItem?.recordRepository(target.provider.storage, changeTarget(target));\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.pr_opened',\n targets: [\n { type: 'pull_request', id: created.url },\n { type: 'repository', id: target.repository.slug },\n ],\n metadata: { url: created.url, provider: target.provider.id, repository: target.repository.slug },\n });\n return created;\n },\n }),\n source_control_update_change_request: createTool({\n id: 'source_control_update_change_request',\n description: `Update the title, body, target branch, or open/closed state of a change request. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n title: z.string().trim().min(1).optional(),\n body: z.string().nullable().optional(),\n baseBranch: z.string().trim().min(1).optional(),\n state: z.enum(['open', 'closed']).optional(),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updatePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.baseBranch !== undefined ? { baseBranch: input.baseBranch } : {}),\n ...(input.state !== undefined ? { state: input.state } : {}),\n });\n },\n }),\n source_control_comment_change_request: createTool({\n id: 'source_control_comment_change_request',\n description: `Add a top-level comment to a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.createComment({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n });\n },\n }),\n source_control_list_change_request_comments: createTool({\n id: 'source_control_list_change_request_comments',\n description: `List top-level comments on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_update_change_request_comment: createTool({\n id: 'source_control_update_change_request_comment',\n description: `Edit a top-level pull-request or merge-request comment in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updateComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_change_request_comment: createTool({\n id: 'source_control_delete_change_request_comment',\n description: `Delete a top-level pull-request or merge-request comment in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n await target.provider.versionControl.deleteComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_list_diff_comments: createTool({\n id: 'source_control_list_diff_comments',\n description: `List line-anchored review comments and discussion replies on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listReviewComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_diff_comment: createTool({\n id: 'source_control_create_diff_comment',\n description: `Create a line-anchored review comment or reply to an existing diff discussion. Use replyToId alone for a reply; otherwise provide commitId, path, line, and side. ${repositoryArgument}`,\n // A root-level union is not representable as provider function parameters, which must be\n // an object schema, so both modes share one object shape and a refinement.\n inputSchema: changeRequestSchema\n .extend({\n body: z.string().trim().min(1),\n replyToId: z.string().trim().min(1).optional(),\n commitId: z.string().trim().min(1).optional(),\n path: z.string().trim().min(1).optional(),\n line: z.number().int().positive().optional(),\n side: z.enum(['left', 'right']).optional(),\n startLine: z.number().int().positive().optional(),\n startSide: z.enum(['left', 'right']).optional(),\n })\n .refine(\n input => {\n const anchorFields = [input.commitId, input.path, input.line, input.side];\n const anchor = anchorFields.every(field => field !== undefined);\n const reply = input.replyToId !== undefined;\n return (\n (reply ? anchorFields.every(field => field === undefined) : anchor) &&\n (input.startLine === undefined) === (input.startSide === undefined)\n );\n },\n {\n message:\n 'Provide replyToId alone to reply to a diff thread, or commitId, path, line, and side to start one. startLine and startSide must be provided together.',\n },\n ),\n execute: async input => {\n const target = await targetFor(input);\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n };\n if (input.replyToId !== undefined) {\n return target.provider.versionControl.createReviewComment({ ...base, replyToId: input.replyToId });\n }\n if (\n input.commitId === undefined ||\n input.path === undefined ||\n input.line === undefined ||\n input.side === undefined\n ) {\n throw new Error('commitId, path, line, and side are required to start a new diff thread.');\n }\n return target.provider.versionControl.createReviewComment({\n ...base,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side,\n ...(input.startLine !== undefined && input.startSide !== undefined\n ? { startLine: input.startLine, startSide: input.startSide }\n : {}),\n });\n },\n }),\n source_control_update_diff_comment: createTool({\n id: 'source_control_update_diff_comment',\n description: `Edit a line-anchored review comment or discussion reply in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updateReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_diff_comment: createTool({\n id: 'source_control_delete_diff_comment',\n description: `Delete a line-anchored review comment or discussion reply in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n await target.provider.versionControl.deleteReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_resolve_diff_thread: createTool({\n id: 'source_control_resolve_diff_thread',\n description: `Resolve or reopen the review thread containing a diff comment. Providers without resolvable threads return an explicit limitation. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({\n commentId: z.string().trim().min(1),\n resolved: z.boolean().default(true),\n }),\n execute: async input => {\n const target = await targetFor(input);\n const resolveReviewThread = target.provider.versionControl.resolveReviewThread;\n if (!resolveReviewThread) {\n throw new Error(`${target.provider.id} does not support resolving review threads.`);\n }\n await resolveReviewThread({\n ...(await reference(target)),\n commentId: input.commentId,\n resolved: input.resolved,\n });\n return { resolved: input.resolved };\n },\n }),\n source_control_review_change_request: createTool({\n id: 'source_control_review_change_request',\n description: `Submit an approve, request-changes, or comment review to a change request. Provider limitations are returned explicitly. ${repositoryArgument}`,\n inputSchema: changeRequestSchema\n .extend({\n event: z.enum(['approve', 'request-changes', 'comment']),\n body: z.string().optional(),\n commitId: z.string().trim().min(1).optional(),\n })\n .refine(input => input.event === 'approve' || Boolean(input.body?.trim()), {\n path: ['body'],\n message: 'request-changes and comment reviews require a body.',\n })\n .superRefine((input, ctx) => {\n const mismatch = verdictEventMismatch(input.event, input.body);\n if (mismatch) ctx.addIssue({ code: 'custom', path: ['body'], message: mismatch });\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead === null) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Every \"Reviewed head:\" line must name the same full 40- or 64-character commit SHA.',\n });\n } else if (reviewedHead && input.commitId && input.commitId.toLowerCase() !== reviewedHead) {\n ctx.addIssue({\n code: 'custom',\n path: ['commitId'],\n message: `Review body says \"Reviewed head: ${reviewedHead}\" but commitId is ${input.commitId}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n });\n }\n }),\n execute: async input => {\n const target = await targetFor(input);\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead) {\n const pullRequest = await target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n if (!pullRequest) {\n throw new Error(`Change request ${input.changeRequestId} was not found; nothing was posted.`);\n }\n if (pullRequest.headSha && pullRequest.headSha.toLowerCase() !== reviewedHead) {\n throw new Error(\n `Review body says \"Reviewed head: ${reviewedHead}\" but the current change-request head is ${pullRequest.headSha}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n );\n }\n }\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.commitId !== undefined\n ? { commitId: input.commitId }\n : reviewedHead\n ? { commitId: reviewedHead }\n : {}),\n };\n if (input.event === 'approve') {\n return target.provider.versionControl.createReview({\n ...base,\n event: 'approve',\n ...(input.body !== undefined ? { body: input.body } : {}),\n });\n }\n return target.provider.versionControl.createReview({ ...base, event: input.event, body: input.body! });\n },\n }),\n source_control_request_reviewers: createTool({\n id: 'source_control_request_reviewers',\n description: `Request individual or team reviewers on a pull request or merge request. Provider limitations are returned explicitly. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n users: z.array(z.string().trim().min(1)).default([]),\n teams: z.array(z.string().trim().min(1)).default([]),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.requestReviewers({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n users: input.users,\n teams: input.teams,\n });\n },\n }),\n source_control_merge_change_request: createTool({\n id: 'source_control_merge_change_request',\n description: `Merge a pull request or merge request using the requested provider-supported merge method. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n method: z.enum(['merge', 'squash', 'rebase']).optional(),\n commitTitle: z.string().optional(),\n commitMessage: z.string().optional(),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.mergePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.method !== undefined ? { method: input.method } : {}),\n ...(input.commitTitle !== undefined ? { commitTitle: input.commitTitle } : {}),\n ...(input.commitMessage !== undefined ? { commitMessage: input.commitMessage } : {}),\n });\n },\n }),\n };\n}\n\n/** The change request a Review run reviews, as `MastraFactory.reviewedChangeRequest()` returns it to an app tool. */\nexport interface ReviewedChangeRequest {\n /** Source-control integration id, such as `github` or `gitlab`. */\n provider: string;\n /** Repository slug, such as `acme/app`. */\n repository: string;\n /** The pull request or merge request number. */\n changeRequestId: string;\n /** The change request's head when it was read. */\n headSha: string;\n headBranch: string;\n /**\n * Publish a commit check on `headSha`. Refused, with nothing published, when\n * the change request is no longer open, `headSha` is not its current head, or\n * the provider cannot publish commit checks.\n */\n publishCommitCheck(input: PublishReviewedCommitCheckInput): Promise<CommitCheck>;\n}\n\nexport interface PublishReviewedCommitCheckInput {\n /** Full commit SHA you tested. */\n headSha: string;\n /** Publishing again with the same name updates the check. */\n name: string;\n status: CommitCheckStatus;\n title: string;\n summary: string;\n details?: string;\n}\n\n/**\n * The change request the session's Review run is bound to, read from its\n * provider. `undefined` when the session is not a Review run bound to a\n * change request.\n */\nexport async function resolveReviewedChangeRequest({\n requestContext,\n providers,\n boundChangeRequestId,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n boundChangeRequestId: () => Promise<string | undefined>;\n}): Promise<ReviewedChangeRequest | undefined> {\n const changeRequestId = await boundChangeRequestId();\n if (changeRequestId === undefined) return undefined;\n const target = await resolveSessionTarget(requestContext, providers);\n const ref = {\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n };\n const read = async () => {\n const pullRequest = await target.provider.versionControl.getPullRequest({ ...ref, pullRequestId: changeRequestId });\n if (!pullRequest || pullRequest.state !== 'open') {\n throw new Error(`Change request ${changeRequestId} is not open; nothing was published.`);\n }\n return pullRequest;\n };\n const opened = await read();\n return {\n provider: target.provider.id,\n repository: target.repository.slug,\n changeRequestId,\n headSha: opened.headSha.toLowerCase(),\n headBranch: opened.headBranch,\n publishCommitCheck: async input => {\n const publish = target.provider.versionControl.publishCommitCheck;\n if (!publish) {\n throw new Error(`${target.provider.id} does not support publishing commit checks; nothing was published.`);\n }\n const current = await read();\n const headSha = input.headSha.toLowerCase();\n if (current.headSha.toLowerCase() !== headSha) {\n throw new Error(\n `headSha ${headSha} is not the current change-request head ${current.headSha}. Nothing was published.`,\n );\n }\n return publish({\n connection: ref.connection,\n sourceId: ref.sourceId,\n actingUserId: ref.actingUserId,\n headSha,\n ref: current.headBranch,\n name: input.name,\n status: input.status,\n title: input.title,\n summary: input.summary,\n ...(input.details !== undefined ? { details: input.details } : {}),\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAwDA,SAAgB,qBAAqB,OAAoB,MAA8C;CACrG,MAAM,QAAQ,2DAA2D,KAAK,sBAAsB,IAAI,KAAK,EAAE;CAC/G,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,OAAO,YAAY,YAAY;CAErD,MAAM,UAAyB,YAAY,YAAY,CAAC,SAAS,IAAI,CAAC,mBAAmB,SAAS;CAClG,IAAI,QAAQ,SAAS,KAAK,GAAG,OAAO,KAAA;CACpC,OAAO,oCAAoC,QAAQ,kBAAkB,MAAM,mCAAmC,QAC3G,KAAI,MAAK,IAAI,EAAE,EAAE,CAAC,CAClB,KAAK,MAAM,EAAE;AAClB;AAEA,MAAM,qBAAqB;AAC3B,MAAM,WAAW;;;;;AAMjB,SAAgB,qBAAqB,MAAqD;CACxF,MAAM,OAAO,IAAI,IACf,CAAC,IAAI,QAAQ,GAAA,CAAI,SAAS,kBAAkB,CAAC,CAAC,CAAC,KAC7C,SAAQ,SAAS,KAAK,KAAK,EAAE,CAAE,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,YAAY,KAAK,IAChE,CACF;CACA,IAAI,KAAK,SAAS,GAAG,OAAO,KAAA;CAC5B,IAAI,KAAK,OAAO,GAAG,OAAO;CAC1B,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;AACnB;AAEA,SAAS,aAAa,gBAAgC;CACpD,MAAM,OAAO,8BAA8B,cAAc;CACzD,OAAO;EAAE,OAAO,oBAAoB,IAAI;EAAG,QAAQ,qBAAqB,IAAI;CAAE;AAChF;AAEA,eAAe,uBACb,WACA,WACiF;CACjF,MAAM,WACJ,MAAM,QAAQ,IACZ,UAAU,IAAI,OAAM,cAAa;EAC/B;EACA,SAAS,MAAM,SA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AClC,CAAC;EACD,cAAc,OAAO;CACvB;CACA,MAAM,OAAO,YAAY;EACvB,MAAM,cAAc,MAAM,OAAO,SAAS,eAAe,eAAe;GAAE,GAAG;GAAK,eAAe;EAAgB,CAAC;EAClH,IAAI,CAAC,eAAe,YAAY,UAAU,QACxC,MAAM,IAAI,MAAM,kBAAkB,gBAAgB,qCAAqC;EAEzF,OAAO;CACT;CACA,MAAM,SAAS,MAAM,KAAK;CAC1B,OAAO;EACL,UAAU,OAAO,SAAS;EAC1B,YAAY,OAAO,WAAW;EAC9B;EACA,SAAS,OAAO,QAAQ,YAAY;EACpC,YAAY,OAAO;EACnB,oBAAoB,OAAM,UAAS;GACjC,MAAM,UAAU,OAAO,SAAS,eAAe;GAC/C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,GAAG,OAAO,SAAS,GAAG,mEAAmE;GAE3G,MAAM,UAAU,MAAM,KAAK;GAC3B,MAAM,UAAU,MAAM,QAAQ,YAAY;GAC1C,IAAI,QAAQ,QAAQ,YAAY,MAAM,SACpC,MAAM,IAAI,MACR,WAAW,QAAQ,0CAA0C,QAAQ,QAAQ,yBAC/E;GAEF,OAAO,QAAQ;IACb,YAAY,IAAI;IAChB,UAAU,IAAI;IACd,cAAc,IAAI;IAClB;IACA,KAAK,QAAQ;IACb,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,OAAO,MAAM;IACb,SAAS,MAAM;IACf,GAAI,MAAM,YAAY,KAAA,IAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;GAClE,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"source-control-tools.js","names":[],"sources":["../../src/session/source-control-tools.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport type { WorkspaceSandbox } from '@mastra/core/workspace';\nimport { z } from 'zod';\n\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../auth.js';\nimport type { CommitCheck, CommitCheckStatus, VersionControl } from '../capabilities/version-control.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport {\n ensureLocalBranch,\n isCheckoutOf,\n pushRepositoryBranch,\n refreshMergeRequestCheckout,\n} from '../integrations/github/sandbox.js';\nimport { normalizedVerdictLine } from '../review-verdict.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { resolveSessionWorkdir } from '../sandbox/session-sandbox.js';\nimport type { AuditAgentEmitter } from '../storage/domains/audit/domain.js';\nimport type {\n ProjectRepository,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n} from '../storage/domains/source-control/base.js';\nimport { mergeRequestNumberFromBranch } from '../work-item-branch.js';\nimport { environmentSlugs, findEnvironmentRepository, resolveSessionRepositories } from './environment-repositories.js';\nimport { updateSessionEnvironmentRepository } from './environment-state-processor.js';\nimport type { ChangeTarget } from './self-review-gate.js';\n\ntype RepositorySessionState = {\n factoryProjectId?: string;\n projectRepositoryId?: string;\n};\n\nexport interface SourceControlToolProvider {\n id: string;\n storage: SourceControlStorageHandle;\n versionControl: VersionControl;\n}\n\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n provider: SourceControlToolProvider;\n session: SourceControlSession;\n projectRepository: ProjectRepository;\n repository: SourceControlRepository;\n orgId: string;\n userId: string;\n /** True when the target is the link the session is filed under, the default. */\n ownRepository: boolean;\n}\n\ntype ReviewEvent = 'approve' | 'request-changes' | 'comment';\n\n/** Returns why a review's leading `Verdict:` line contradicts the submitted event, if it does. */\nexport function verdictEventMismatch(event: ReviewEvent, body: string | undefined): string | undefined {\n const match = /^verdict: ?(approve|request changes|changes requested)\\b/.exec(normalizedVerdictLine(body) ?? '');\n if (!match) return undefined;\n const verdict = match[1] === 'approve' ? 'approve' : 'request changes';\n // GitLab has no request-changes state, so a blocking verdict is published as a comment review.\n const allowed: ReviewEvent[] = verdict === 'approve' ? ['approve'] : ['request-changes', 'comment'];\n if (allowed.includes(event)) return undefined;\n return `Review body opens with \"Verdict: ${verdict}\" but event is \"${event}\". Nothing was posted. Use event ${allowed\n .map(e => `\"${e}\"`)\n .join(' or ')} for this body, or regenerate the body for the verdict you intend.`;\n}\n\nconst REVIEWED_HEAD_LINE = /^[\\s*_>-]*reviewed head[*_]*:[*_]*\\s*(.*)$/gim;\nconst FULL_SHA = /^`?([0-9a-f]{40}|[0-9a-f]{64})`?(?:\\s|$)/i;\n\n/**\n * Returns the full SHA named by the body's `Reviewed head:` lines, `null` when any line is malformed or the lines\n * disagree, or `undefined` when absent.\n */\nexport function reviewedHeadFromBody(body: string | undefined): string | null | undefined {\n const shas = new Set(\n [...(body ?? '').matchAll(REVIEWED_HEAD_LINE)].map(\n line => FULL_SHA.exec(line[1]!.trim())?.[1]?.toLowerCase() ?? null,\n ),\n );\n if (shas.size === 0) return undefined;\n if (shas.size > 1) return null;\n return [...shas][0];\n}\n\nfunction authIdentity(requestContext: RequestContext) {\n const user = getFactoryAuthUserFromContext(requestContext);\n return { orgId: getFactoryAuthOrgId(user), userId: getFactoryAuthUserId(user) };\n}\n\nasync function resolveProviderSession(\n sessionId: string,\n providers: readonly SourceControlToolProvider[],\n): Promise<{ provider: SourceControlToolProvider; session: SourceControlSession }> {\n const matches = (\n await Promise.all(\n providers.map(async provider => ({\n provider,\n session: await provider.storage.sessions.getBySessionId(sessionId),\n })),\n )\n ).filter(\n (match): match is { provider: SourceControlToolProvider; session: SourceControlSession } => match.session !== null,\n );\n if (matches.length !== 1) {\n throw new Error(\n matches.length === 0\n ? 'The active session is not backed by a source-control repository.'\n : 'The active session is ambiguous across source-control providers.',\n );\n }\n return matches[0]!;\n}\n\nasync function resolveSessionTarget(\n requestContext: RequestContext,\n providers: readonly SourceControlToolProvider[],\n options: { repository?: string } = {},\n): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const { orgId, userId } = authIdentity(requestContext);\n if (!context?.sessionId || !orgId || !userId) {\n throw new Error('Source-control tools require an authenticated repository session.');\n }\n\n const { provider, session } = await resolveProviderSession(context.sessionId, providers);\n if (session.orgId !== orgId || (session.visibility === 'private' && session.userId !== userId)) {\n throw new Error('The active source-control session is not available to the authenticated user.');\n }\n const ownRepository = session.projectRepositoryId\n ? await provider.storage.projectRepositories.get({ orgId, id: session.projectRepositoryId })\n : null;\n if (!ownRepository) throw new Error('The active project repository was not found.');\n const state = context.getState();\n if (state.projectRepositoryId && state.projectRepositoryId !== ownRepository.id) {\n throw new Error('The active source-control session does not match its controller repository.');\n }\n const ownConnection = await provider.storage.connections.get({ orgId, id: ownRepository.connectionId });\n if (!ownConnection) throw new Error('The active source-control connection was not found.');\n if (state.factoryProjectId && state.factoryProjectId !== ownConnection.factoryProjectId) {\n throw new Error('The active source-control session does not match its Factory project.');\n }\n\n if (options.repository !== undefined) {\n const candidates = await resolveSessionRepositories({ sourceControl: provider.storage, session });\n const match = findEnvironmentRepository(candidates, options.repository);\n if (!match) {\n throw new Error(\n `Repository '${options.repository}' is not in this Factory's environment. Valid repositories: ${environmentSlugs(candidates).join(', ')}.`,\n );\n }\n return {\n context,\n provider,\n session,\n projectRepository: match.link,\n repository: match.repository,\n orgId,\n userId,\n ownRepository: match.link.id === ownRepository.id,\n };\n }\n\n const repository = await provider.storage.repositories.get({ orgId, id: ownRepository.repositoryId });\n if (!repository) throw new Error('The active source-control repository was not found.');\n return {\n context,\n provider,\n session,\n projectRepository: ownRepository,\n repository,\n orgId,\n userId,\n ownRepository: true,\n };\n}\n\n/**\n * The slugs a session may target and the one it is filed under, for the tool\n * descriptions. `undefined` when the session cannot be resolved; the tools\n * then describe the default without naming it.\n */\nasync function describeSessionRepositories(\n sessionId: string,\n providers: readonly SourceControlToolProvider[],\n): Promise<{ slugs: string[]; own: string | undefined } | undefined> {\n try {\n const { provider, session } = await resolveProviderSession(sessionId, providers);\n const repositories = await resolveSessionRepositories({ sourceControl: provider.storage, session });\n const own = repositories.find(candidate => candidate.link.id === session.projectRepositoryId);\n return { slugs: environmentSlugs(repositories), own: own?.repository.slug };\n } catch {\n return undefined;\n }\n}\n\nfunction repositoryArgumentDescription(described: { slugs: string[]; own: string | undefined } | undefined): string {\n if (!described || described.slugs.length === 0) {\n return \"Optional `repository` (owner/name) selects another repository of this Factory's environment; defaults to this session's repository.\";\n }\n const fallback = described.own ? `${described.own}, this session's repository` : \"this session's repository\";\n return `Optional \\`repository\\` (owner/name) selects one of this Factory's environment repositories: ${described.slugs.join(', ')}. Defaults to ${fallback}.`;\n}\n\nfunction changeRequestId(value: string | number): string {\n return String(value);\n}\n\nfunction executableSandbox(value: unknown): WorkspaceSandbox & ExecutableSandbox {\n const sandbox = value as Partial<ExecutableSandbox> | undefined;\n if (!sandbox?.executeCommand) throw new Error('The active Factory workspace has no executable sandbox.');\n return sandbox as WorkspaceSandbox & ExecutableSandbox;\n}\n\nasync function emitAgentAudit(\n audit: AuditAgentEmitter,\n requestContext: RequestContext,\n input: Parameters<AuditAgentEmitter['emitAgent']>[0]['input'],\n): Promise<void> {\n try {\n await audit.emitAgent({ requestContext, input });\n } catch (error) {\n console.warn('[Audit] Failed to record brokered source-control action', {\n action: input.action,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction changeTarget(target: SessionTarget): ChangeTarget {\n return { slug: target.repository.slug, ownRepository: target.ownRepository };\n}\n\nconst repositorySchema = z.object({ repository: z.string().trim().min(1).optional() });\nconst changeRequestSchema = repositorySchema.extend({\n changeRequestId: z.union([z.string().trim().min(1), z.number().int().positive()]),\n});\n\nexport async function createSourceControlTools({\n requestContext,\n providers,\n audit,\n workItem,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n audit: AuditAgentEmitter;\n /** The session's card, when it is bound to one. */\n workItem?: {\n /**\n * Self-review gate for opening a change request in `target`. `undefined` means\n * it is not gated (no Work item, another repository than the card's, or its\n * change request predates Self-review); `null` means Self-review has not\n * approved; a SHA is the approved head.\n */\n selfReviewApprovedHead(target: ChangeTarget): Promise<string | null | undefined>;\n /** Records `target` as the card's repository when the card names none. */\n recordRepository(sourceControl: SourceControlStorageHandle, target: ChangeTarget): Promise<void>;\n };\n}): Promise<IntegrationTools> {\n if (!requestContext || typeof (requestContext as { get?: unknown }).get !== 'function') return {};\n const controller = requestContext.get('controller') as\n | AgentControllerRequestContext<RepositorySessionState>\n | undefined;\n const identity = authIdentity(requestContext);\n if (!controller?.sessionId || !identity.orgId || !identity.userId || providers.length === 0) return {};\n\n const repositoryArgument = repositoryArgumentDescription(\n await describeSessionRepositories(controller.sessionId, providers),\n );\n const withTarget = (options?: { repository?: string }) => resolveSessionTarget(requestContext, providers, options);\n const targetFor = (input: { repository?: string }) =>\n withTarget(input.repository !== undefined ? { repository: input.repository } : undefined);\n const reference = async (target: SessionTarget) => ({\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n });\n\n return {\n source_control_refresh_change_request_checkout: createTool({\n id: 'source_control_refresh_change_request_checkout',\n description:\n 'Refresh the active GitLab review session checkout to its current MR head. The MR, repository, branch, and credential are resolved server-side; no provider credentials enter the agent workspace.',\n inputSchema: z.object({}),\n execute: async (_input, { workspace }) => {\n const target = await withTarget();\n const mergeRequestNumber = mergeRequestNumberFromBranch(target.session.branch);\n if (target.provider.id !== 'gitlab' || mergeRequestNumber === undefined) {\n throw new Error('Checkout refresh is only available in a bound GitLab merge-request review session.');\n }\n const ref = await reference(target);\n const mergeRequest = await target.provider.versionControl.getPullRequest({\n ...ref,\n pullRequestId: String(mergeRequestNumber),\n });\n if (!mergeRequest || mergeRequest.state !== 'open' || mergeRequest.merged) {\n throw new Error('The bound GitLab merge request is no longer open.');\n }\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n const result = await refreshMergeRequestCheckout(sandbox, workdir, {\n branch: target.session.branch,\n mergeRequestNumber,\n expectedHeadSha: mergeRequest.headSha,\n access,\n });\n return result;\n },\n }),\n source_control_push_branch: createTool({\n id: 'source_control_push_branch',\n description: `Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, remote, or branch arguments. Returns the pushed \\`commit\\`; \\`upToDate: true\\` means the remote already had it and nothing new was pushed, so check that commit is the one you meant to push. Commit before pushing, not in parallel with it. ${repositoryArgument}`,\n inputSchema: repositorySchema,\n execute: async (input, { workspace }) => {\n const target = await targetFor(input);\n const sandbox = executableSandbox(workspace?.sandbox);\n const workdir = await resolveSessionWorkdir(target.session.id, sandbox, target.repository.slug);\n const access = await target.provider.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n });\n // Another environment repository's directory may not be its checkout:\n // a boot skips a link whose directory name collides with another's, and\n // a session that booted single-repository has no siblings at all.\n if (!target.ownRepository && !(await isCheckoutOf(sandbox, workdir, access.cloneUrl))) {\n throw new Error(`There is no checkout of ${target.repository.slug} in this session.`);\n }\n const branch = target.session.branch;\n // Materialize the session branch at the active HEAD without discarding\n // session-only commits, so the push includes the agent's current work.\n await ensureLocalBranch(sandbox, workdir, branch);\n const { commit, upToDate } = await pushRepositoryBranch(\n sandbox,\n workdir,\n branch,\n access,\n target.repository.slug,\n );\n await target.provider.storage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: target.projectRepository.id,\n branch,\n });\n updateSessionEnvironmentRepository(target.session.sessionId, target.repository.slug, { branch });\n await workItem?.recordRepository(target.provider.storage, changeTarget(target));\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.push',\n targets: [{ type: 'repository', id: target.repository.slug }],\n metadata: { branch, provider: target.provider.id, repository: target.repository.slug },\n });\n return { pushed: true, branch, repository: target.repository.slug, commit, upToDate };\n },\n }),\n source_control_get_change_request: createTool({\n id: 'source_control_get_change_request',\n description: `Read a pull request or merge request in the active Factory repository by its numeric repository-local ID. ${repositoryArgument}`,\n inputSchema: changeRequestSchema,\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n },\n }),\n source_control_list_change_request_reviews: createTool({\n id: 'source_control_list_change_request_reviews',\n description: `List submitted reviews and approvals on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listReviews({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_change_request: createTool({\n id: 'source_control_create_change_request',\n description: `Open a pull request or merge request from the active Factory session branch into the repository's base branch (the session's persisted base branch in its own repository, the linked or default branch elsewhere). Push the branch with source_control_push_branch first. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({\n title: z.string().trim().min(1),\n body: z.string().optional(),\n draft: z.boolean().optional(),\n }),\n execute: async (input, execution) => {\n const target = await targetFor(input);\n const approvedHead = await workItem?.selfReviewApprovedHead(changeTarget(target));\n if (approvedHead === null) {\n throw new Error(\n 'Self-review has not approved this branch. Move the work item to Self-review; the change request opens after it approves.',\n );\n }\n const baseBranch = target.ownRepository\n ? target.session.baseBranch\n : (target.projectRepository.branch ?? target.repository.defaultBranch);\n const created = await target.provider.versionControl.createPullRequest({\n ...(await reference(target)),\n title: input.title,\n ...(input.body !== undefined ? { body: input.body } : {}),\n baseBranch,\n headBranch: target.session.branch,\n ...(input.draft !== undefined ? { draft: input.draft } : {}),\n });\n if (approvedHead !== undefined && created.headSha.toLowerCase() !== approvedHead.toLowerCase()) {\n await target.provider.versionControl.closePullRequest({\n ...(await reference(target)),\n pullRequestId: created.id,\n });\n throw new Error(\n `Self-review approved ${approvedHead}, but the pushed branch is at ${created.headSha}; the change request was closed. Push the approved head, or move the work item back to Self-review to review the new commits.`,\n );\n }\n await target.provider.storage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: target.projectRepository.id,\n // Opening a change request pushes nothing: an existing row keeps its\n // `pushedAt`; the branch only seeds a row no push wrote yet.\n fallbackBranch: target.session.branch,\n changeRequestId: changeRequestId(created.id),\n changeRequestUrl: created.url,\n });\n updateSessionEnvironmentRepository(target.session.sessionId, target.repository.slug, {\n changeRequestUrl: created.url,\n });\n await workItem?.recordRepository(target.provider.storage, changeTarget(target));\n await emitAgentAudit(audit, requestContext, {\n action: 'factory.agent.pr_opened',\n targets: [\n { type: 'pull_request', id: created.url },\n { type: 'repository', id: target.repository.slug },\n ],\n metadata: { url: created.url, provider: target.provider.id, repository: target.repository.slug },\n });\n return created;\n },\n }),\n source_control_update_change_request: createTool({\n id: 'source_control_update_change_request',\n description: `Update the title, body, target branch, or open/closed state of a change request. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n title: z.string().trim().min(1).optional(),\n body: z.string().nullable().optional(),\n baseBranch: z.string().trim().min(1).optional(),\n state: z.enum(['open', 'closed']).optional(),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updatePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.body !== undefined ? { body: input.body } : {}),\n ...(input.baseBranch !== undefined ? { baseBranch: input.baseBranch } : {}),\n ...(input.state !== undefined ? { state: input.state } : {}),\n });\n },\n }),\n source_control_comment_change_request: createTool({\n id: 'source_control_comment_change_request',\n description: `Add a top-level comment to a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.createComment({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n });\n },\n }),\n source_control_list_change_request_comments: createTool({\n id: 'source_control_list_change_request_comments',\n description: `List top-level comments on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_update_change_request_comment: createTool({\n id: 'source_control_update_change_request_comment',\n description: `Edit a top-level pull-request or merge-request comment in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updateComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_change_request_comment: createTool({\n id: 'source_control_delete_change_request_comment',\n description: `Delete a top-level pull-request or merge-request comment in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n await target.provider.versionControl.deleteComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_list_diff_comments: createTool({\n id: 'source_control_list_diff_comments',\n description: `List line-anchored review comments and discussion replies on a pull request or merge request in the active repository. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({ cursor: z.string().trim().min(1).optional() }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.listReviewComments({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n },\n }),\n source_control_create_diff_comment: createTool({\n id: 'source_control_create_diff_comment',\n description: `Create a line-anchored review comment or reply to an existing diff discussion. Use replyToId alone for a reply; otherwise provide commitId, path, line, and side. ${repositoryArgument}`,\n // A root-level union is not representable as provider function parameters, which must be\n // an object schema, so both modes share one object shape and a refinement.\n inputSchema: changeRequestSchema\n .extend({\n body: z.string().trim().min(1),\n replyToId: z.string().trim().min(1).optional(),\n commitId: z.string().trim().min(1).optional(),\n path: z.string().trim().min(1).optional(),\n line: z.number().int().positive().optional(),\n side: z.enum(['left', 'right']).optional(),\n startLine: z.number().int().positive().optional(),\n startSide: z.enum(['left', 'right']).optional(),\n })\n .refine(\n input => {\n const anchorFields = [input.commitId, input.path, input.line, input.side];\n const anchor = anchorFields.every(field => field !== undefined);\n const reply = input.replyToId !== undefined;\n return (\n (reply ? anchorFields.every(field => field === undefined) : anchor) &&\n (input.startLine === undefined) === (input.startSide === undefined)\n );\n },\n {\n message:\n 'Provide replyToId alone to reply to a diff thread, or commitId, path, line, and side to start one. startLine and startSide must be provided together.',\n },\n ),\n execute: async input => {\n const target = await targetFor(input);\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n body: input.body,\n };\n if (input.replyToId !== undefined) {\n return target.provider.versionControl.createReviewComment({ ...base, replyToId: input.replyToId });\n }\n if (\n input.commitId === undefined ||\n input.path === undefined ||\n input.line === undefined ||\n input.side === undefined\n ) {\n throw new Error('commitId, path, line, and side are required to start a new diff thread.');\n }\n return target.provider.versionControl.createReviewComment({\n ...base,\n commitId: input.commitId,\n path: input.path,\n line: input.line,\n side: input.side,\n ...(input.startLine !== undefined && input.startSide !== undefined\n ? { startLine: input.startLine, startSide: input.startSide }\n : {}),\n });\n },\n }),\n source_control_update_diff_comment: createTool({\n id: 'source_control_update_diff_comment',\n description: `Edit a line-anchored review comment or discussion reply in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1), body: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.updateReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n body: input.body,\n });\n },\n }),\n source_control_delete_diff_comment: createTool({\n id: 'source_control_delete_diff_comment',\n description: `Delete a line-anchored review comment or discussion reply in the active repository. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({ commentId: z.string().trim().min(1) }),\n execute: async input => {\n const target = await targetFor(input);\n await target.provider.versionControl.deleteReviewComment({\n ...(await reference(target)),\n commentId: input.commentId,\n });\n return { deleted: true };\n },\n }),\n source_control_resolve_diff_thread: createTool({\n id: 'source_control_resolve_diff_thread',\n description: `Resolve or reopen the review thread containing a diff comment. Providers without resolvable threads return an explicit limitation. ${repositoryArgument}`,\n inputSchema: repositorySchema.extend({\n commentId: z.string().trim().min(1),\n resolved: z.boolean().default(true),\n }),\n execute: async input => {\n const target = await targetFor(input);\n const resolveReviewThread = target.provider.versionControl.resolveReviewThread;\n if (!resolveReviewThread) {\n throw new Error(`${target.provider.id} does not support resolving review threads.`);\n }\n await resolveReviewThread({\n ...(await reference(target)),\n commentId: input.commentId,\n resolved: input.resolved,\n });\n return { resolved: input.resolved };\n },\n }),\n source_control_review_change_request: createTool({\n id: 'source_control_review_change_request',\n description: `Submit an approve, request-changes, or comment review to a change request. Provider limitations are returned explicitly. ${repositoryArgument}`,\n inputSchema: changeRequestSchema\n .extend({\n event: z.enum(['approve', 'request-changes', 'comment']),\n body: z.string().optional(),\n commitId: z.string().trim().min(1).optional(),\n })\n .refine(input => input.event === 'approve' || Boolean(input.body?.trim()), {\n path: ['body'],\n message: 'request-changes and comment reviews require a body.',\n })\n .superRefine((input, ctx) => {\n const mismatch = verdictEventMismatch(input.event, input.body);\n if (mismatch) ctx.addIssue({ code: 'custom', path: ['body'], message: mismatch });\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead === null) {\n ctx.addIssue({\n code: 'custom',\n path: ['body'],\n message: 'Every \"Reviewed head:\" line must name the same full 40- or 64-character commit SHA.',\n });\n } else if (reviewedHead && input.commitId && input.commitId.toLowerCase() !== reviewedHead) {\n ctx.addIssue({\n code: 'custom',\n path: ['commitId'],\n message: `Review body says \"Reviewed head: ${reviewedHead}\" but commitId is ${input.commitId}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n });\n }\n }),\n execute: async input => {\n const target = await targetFor(input);\n const reviewedHead = reviewedHeadFromBody(input.body);\n if (reviewedHead) {\n const pullRequest = await target.provider.versionControl.getPullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n });\n if (!pullRequest) {\n throw new Error(`Change request ${input.changeRequestId} was not found; nothing was posted.`);\n }\n if (pullRequest.headSha && pullRequest.headSha.toLowerCase() !== reviewedHead) {\n throw new Error(\n `Review body says \"Reviewed head: ${reviewedHead}\" but the current change-request head is ${pullRequest.headSha}. Nothing was posted. Re-review the current head and regenerate the body before publishing.`,\n );\n }\n }\n const base = {\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.commitId !== undefined\n ? { commitId: input.commitId }\n : reviewedHead\n ? { commitId: reviewedHead }\n : {}),\n };\n if (input.event === 'approve') {\n return target.provider.versionControl.createReview({\n ...base,\n event: 'approve',\n ...(input.body !== undefined ? { body: input.body } : {}),\n });\n }\n return target.provider.versionControl.createReview({ ...base, event: input.event, body: input.body! });\n },\n }),\n source_control_request_reviewers: createTool({\n id: 'source_control_request_reviewers',\n description: `Request individual or team reviewers on a pull request or merge request. Provider limitations are returned explicitly. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n users: z.array(z.string().trim().min(1)).default([]),\n teams: z.array(z.string().trim().min(1)).default([]),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.requestReviewers({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n users: input.users,\n teams: input.teams,\n });\n },\n }),\n source_control_merge_change_request: createTool({\n id: 'source_control_merge_change_request',\n description: `Merge a pull request or merge request using the requested provider-supported merge method. ${repositoryArgument}`,\n inputSchema: changeRequestSchema.extend({\n method: z.enum(['merge', 'squash', 'rebase']).optional(),\n commitTitle: z.string().optional(),\n commitMessage: z.string().optional(),\n }),\n execute: async input => {\n const target = await targetFor(input);\n return target.provider.versionControl.mergePullRequest({\n ...(await reference(target)),\n pullRequestId: changeRequestId(input.changeRequestId),\n ...(input.method !== undefined ? { method: input.method } : {}),\n ...(input.commitTitle !== undefined ? { commitTitle: input.commitTitle } : {}),\n ...(input.commitMessage !== undefined ? { commitMessage: input.commitMessage } : {}),\n });\n },\n }),\n };\n}\n\n/** The change request a Review run reviews, as `MastraFactory.reviewedChangeRequest()` returns it to an app tool. */\nexport interface ReviewedChangeRequest {\n /** Source-control integration id, such as `github` or `gitlab`. */\n provider: string;\n /** Repository slug, such as `acme/app`. */\n repository: string;\n /** The pull request or merge request number. */\n changeRequestId: string;\n /** The change request's head when it was read. */\n headSha: string;\n headBranch: string;\n /**\n * Publish a commit check on `headSha`. Refused, with nothing published, when\n * the change request is no longer open, `headSha` is not its current head, or\n * the provider cannot publish commit checks.\n */\n publishCommitCheck(input: PublishReviewedCommitCheckInput): Promise<CommitCheck>;\n}\n\nexport interface PublishReviewedCommitCheckInput {\n /** Full commit SHA you tested. */\n headSha: string;\n /** Publishing again with the same name updates the check. */\n name: string;\n status: CommitCheckStatus;\n title: string;\n summary: string;\n details?: string;\n}\n\n/**\n * The change request the session's Review run is bound to, read from its\n * provider. `undefined` when the session is not a Review run bound to a\n * change request.\n */\nexport async function resolveReviewedChangeRequest({\n requestContext,\n providers,\n boundChangeRequestId,\n}: {\n requestContext: RequestContext;\n providers: readonly SourceControlToolProvider[];\n boundChangeRequestId: () => Promise<string | undefined>;\n}): Promise<ReviewedChangeRequest | undefined> {\n const changeRequestId = await boundChangeRequestId();\n if (changeRequestId === undefined) return undefined;\n const target = await resolveSessionTarget(requestContext, providers);\n const ref = {\n ...(await target.provider.versionControl.getRepositoryTarget({\n orgId: target.orgId,\n repositoryId: target.repository.id,\n })),\n actingUserId: target.userId,\n };\n const read = async () => {\n const pullRequest = await target.provider.versionControl.getPullRequest({ ...ref, pullRequestId: changeRequestId });\n if (!pullRequest || pullRequest.state !== 'open') {\n throw new Error(`Change request ${changeRequestId} is not open; nothing was published.`);\n }\n return pullRequest;\n };\n const opened = await read();\n return {\n provider: target.provider.id,\n repository: target.repository.slug,\n changeRequestId,\n headSha: opened.headSha.toLowerCase(),\n headBranch: opened.headBranch,\n publishCommitCheck: async input => {\n const publish = target.provider.versionControl.publishCommitCheck;\n if (!publish) {\n throw new Error(`${target.provider.id} does not support publishing commit checks; nothing was published.`);\n }\n const current = await read();\n const headSha = input.headSha.toLowerCase();\n if (current.headSha.toLowerCase() !== headSha) {\n throw new Error(\n `headSha ${headSha} is not the current change-request head ${current.headSha}. Nothing was published.`,\n );\n }\n return publish({\n connection: ref.connection,\n sourceId: ref.sourceId,\n actingUserId: ref.actingUserId,\n headSha,\n ref: current.headBranch,\n name: input.name,\n status: input.status,\n title: input.title,\n summary: input.summary,\n ...(input.details !== undefined ? { details: input.details } : {}),\n });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAwDA,SAAgB,qBAAqB,OAAoB,MAA8C;CACrG,MAAM,QAAQ,2DAA2D,KAAK,sBAAsB,IAAI,KAAK,EAAE;CAC/G,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,OAAO,YAAY,YAAY;CAErD,MAAM,UAAyB,YAAY,YAAY,CAAC,SAAS,IAAI,CAAC,mBAAmB,SAAS;CAClG,IAAI,QAAQ,SAAS,KAAK,GAAG,OAAO,KAAA;CACpC,OAAO,oCAAoC,QAAQ,kBAAkB,MAAM,mCAAmC,QAC3G,KAAI,MAAK,IAAI,EAAE,EAAE,CAAC,CAClB,KAAK,MAAM,EAAE;AAClB;AAEA,MAAM,qBAAqB;AAC3B,MAAM,WAAW;;;;;AAMjB,SAAgB,qBAAqB,MAAqD;CACxF,MAAM,OAAO,IAAI,IACf,CAAC,IAAI,QAAQ,GAAA,CAAI,SAAS,kBAAkB,CAAC,CAAC,CAAC,KAC7C,SAAQ,SAAS,KAAK,KAAK,EAAE,CAAE,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,YAAY,KAAK,IAChE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AM;IACZ,QAAQ,MAAM;IACd,OAAO,MAAM;IACb,SAAS,MAAM;IACf,GAAI,MAAM,YAAY,KAAA,IAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;GAClE,CAAC;EACH;CACF;AACF"}
|
|
@@ -5,7 +5,8 @@ export declare function assertFactorySkills(skills: unknown): readonly InlineSki
|
|
|
5
5
|
/**
|
|
6
6
|
* Problems with the skills board phases name in `runner.skill`, found at
|
|
7
7
|
* startup instead of when a card first enters the phase. A skill is found when
|
|
8
|
-
* it is a code skill, a folder skill in the app's `factory-skills/`,
|
|
8
|
+
* it is a code skill, a folder skill in the app's `factory-skills/`, bundled,
|
|
9
|
+
* or one of `projectSkills`, the skills a project created for its own boards.
|
|
9
10
|
*/
|
|
10
|
-
export declare function findBoardSkillProblems(boards: BoardRegistry, codeSkills: readonly InlineSkill[], localSkillsPath?: string | undefined): string[];
|
|
11
|
+
export declare function findBoardSkillProblems(boards: BoardRegistry, codeSkills: readonly InlineSkill[], localSkillsPath?: string | undefined, projectSkills?: ReadonlySet<string>): string[];
|
|
11
12
|
//# sourceMappingURL=app-skills.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-skills.d.ts","sourceRoot":"","sources":["../../src/skills/app-skills.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGxD,6GAA6G;AAC7G,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,OAAO,GAAG,SAAS,WAAW,EAAE,CAkB3E;
|
|
1
|
+
{"version":3,"file":"app-skills.d.ts","sourceRoot":"","sources":["../../src/skills/app-skills.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGxD,6GAA6G;AAC7G,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,OAAO,GAAG,SAAS,WAAW,EAAE,CAkB3E;AAID;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,aAAa,EACrB,UAAU,EAAE,SAAS,WAAW,EAAE,EAClC,eAAe,GAAE,MAAM,GAAG,SAA2C,EACrE,aAAa,GAAE,WAAW,CAAC,MAAM,CAAqB,GACrD,MAAM,EAAE,CAyBV"}
|
|
@@ -15,19 +15,21 @@ function assertFactorySkills(skills) {
|
|
|
15
15
|
}
|
|
16
16
|
return Object.freeze([...skills]);
|
|
17
17
|
}
|
|
18
|
+
const NO_PROJECT_SKILLS = /* @__PURE__ */ new Set();
|
|
18
19
|
/**
|
|
19
20
|
* Problems with the skills board phases name in `runner.skill`, found at
|
|
20
21
|
* startup instead of when a card first enters the phase. A skill is found when
|
|
21
|
-
* it is a code skill, a folder skill in the app's `factory-skills/`,
|
|
22
|
+
* it is a code skill, a folder skill in the app's `factory-skills/`, bundled,
|
|
23
|
+
* or one of `projectSkills`, the skills a project created for its own boards.
|
|
22
24
|
*/
|
|
23
|
-
function findBoardSkillProblems(boards, codeSkills, localSkillsPath = resolveLocalFactorySkillsPath()) {
|
|
25
|
+
function findBoardSkillProblems(boards, codeSkills, localSkillsPath = resolveLocalFactorySkillsPath(), projectSkills = NO_PROJECT_SKILLS) {
|
|
24
26
|
const codeNames = new Set(codeSkills.map((skill) => skill.name));
|
|
25
27
|
const problems = [];
|
|
26
28
|
for (const [boardId, board] of boards) for (const [phaseId, phase] of Object.entries(board.phases)) {
|
|
27
29
|
if (phase.kind !== "working" || !phase.runner.skill) continue;
|
|
28
30
|
const { skill, context } = phase.runner;
|
|
29
31
|
const where = `Board '${boardId}' phase '${phaseId}'`;
|
|
30
|
-
if (!(codeNames.has(skill) || FACTORY_SKILL_NAMES.has(skill) || localSkillsPath !== void 0 && existsSync(join(localSkillsPath, skill, "SKILL.md")))) problems.push(`${where} runs skill '${skill}', but no such skill exists. Pass it in MastraFactory({ skills })
|
|
32
|
+
if (!(codeNames.has(skill) || FACTORY_SKILL_NAMES.has(skill) || projectSkills.has(skill) || localSkillsPath !== void 0 && existsSync(join(localSkillsPath, skill, "SKILL.md")))) problems.push(`${where} runs skill '${skill}', but no such skill exists. Pass it in MastraFactory({ skills }), add factory-skills/${skill}/SKILL.md, or create it in Settings › Skills.`);
|
|
31
33
|
else if (REVIEW_ONLY_FACTORY_SKILLS.has(skill) && context !== "review") problems.push(`${where} runs review skill '${skill}' in the '${context}' context; review skills only load in the 'review' context.`);
|
|
32
34
|
}
|
|
33
35
|
return problems;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-skills.js","names":[],"sources":["../../src/skills/app-skills.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { isInlineSkill } from '@mastra/core/skills';\nimport type { InlineSkill } from '@mastra/core/skills';\n\nimport type { BoardRegistry } from '../boards/index.js';\nimport { FACTORY_SKILL_NAMES, resolveLocalFactorySkillsPath, REVIEW_ONLY_FACTORY_SKILLS } from '../workspace.js';\n\n/** Check `MastraFactory({ skills })`: each entry must come from `createSkill()` and names must be unique. */\nexport function assertFactorySkills(skills: unknown): readonly InlineSkill[] {\n if (skills === undefined) return [];\n if (!Array.isArray(skills)) {\n throw new Error(\"MastraFactory: 'skills' must be an array of createSkill() results.\");\n }\n const names = new Set<string>();\n for (const skill of skills) {\n if (!isInlineSkill(skill)) {\n throw new Error(\n \"MastraFactory: every entry in 'skills' must be created with createSkill() from '@mastra/core/skills'.\",\n );\n }\n if (names.has(skill.name)) {\n throw new Error(`MastraFactory: duplicate skill name '${skill.name}' in 'skills'.`);\n }\n names.add(skill.name);\n }\n return Object.freeze([...skills]);\n}\n\n/**\n * Problems with the skills board phases name in `runner.skill`, found at\n * startup instead of when a card first enters the phase. A skill is found when\n * it is a code skill, a folder skill in the app's `factory-skills/`, or
|
|
1
|
+
{"version":3,"file":"app-skills.js","names":[],"sources":["../../src/skills/app-skills.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { isInlineSkill } from '@mastra/core/skills';\nimport type { InlineSkill } from '@mastra/core/skills';\n\nimport type { BoardRegistry } from '../boards/index.js';\nimport { FACTORY_SKILL_NAMES, resolveLocalFactorySkillsPath, REVIEW_ONLY_FACTORY_SKILLS } from '../workspace.js';\n\n/** Check `MastraFactory({ skills })`: each entry must come from `createSkill()` and names must be unique. */\nexport function assertFactorySkills(skills: unknown): readonly InlineSkill[] {\n if (skills === undefined) return [];\n if (!Array.isArray(skills)) {\n throw new Error(\"MastraFactory: 'skills' must be an array of createSkill() results.\");\n }\n const names = new Set<string>();\n for (const skill of skills) {\n if (!isInlineSkill(skill)) {\n throw new Error(\n \"MastraFactory: every entry in 'skills' must be created with createSkill() from '@mastra/core/skills'.\",\n );\n }\n if (names.has(skill.name)) {\n throw new Error(`MastraFactory: duplicate skill name '${skill.name}' in 'skills'.`);\n }\n names.add(skill.name);\n }\n return Object.freeze([...skills]);\n}\n\nconst NO_PROJECT_SKILLS: ReadonlySet<string> = new Set();\n\n/**\n * Problems with the skills board phases name in `runner.skill`, found at\n * startup instead of when a card first enters the phase. A skill is found when\n * it is a code skill, a folder skill in the app's `factory-skills/`, bundled,\n * or one of `projectSkills`, the skills a project created for its own boards.\n */\nexport function findBoardSkillProblems(\n boards: BoardRegistry,\n codeSkills: readonly InlineSkill[],\n localSkillsPath: string | undefined = resolveLocalFactorySkillsPath(),\n projectSkills: ReadonlySet<string> = NO_PROJECT_SKILLS,\n): string[] {\n const codeNames = new Set(codeSkills.map(skill => skill.name));\n const problems: string[] = [];\n for (const [boardId, board] of boards) {\n for (const [phaseId, phase] of Object.entries(board.phases)) {\n if (phase.kind !== 'working' || !phase.runner.skill) continue;\n const { skill, context } = phase.runner;\n const where = `Board '${boardId}' phase '${phaseId}'`;\n const found =\n codeNames.has(skill) ||\n FACTORY_SKILL_NAMES.has(skill) ||\n projectSkills.has(skill) ||\n (localSkillsPath !== undefined && existsSync(join(localSkillsPath, skill, 'SKILL.md')));\n if (!found) {\n problems.push(\n `${where} runs skill '${skill}', but no such skill exists. Pass it in MastraFactory({ skills }), add factory-skills/${skill}/SKILL.md, or create it in Settings › Skills.`,\n );\n } else if (REVIEW_ONLY_FACTORY_SKILLS.has(skill) && context !== 'review') {\n problems.push(\n `${where} runs review skill '${skill}' in the '${context}' context; review skills only load in the 'review' context.`,\n );\n }\n }\n }\n return problems;\n}\n"],"mappings":";;;;;;AAUA,SAAgB,oBAAoB,QAAyC;CAC3E,IAAI,WAAW,KAAA,GAAW,OAAO,CAAC;CAClC,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,MAAM,IAAI,MAAM,oEAAoE;CAEtF,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,cAAc,KAAK,GACtB,MAAM,IAAI,MACR,uGACF;EAEF,IAAI,MAAM,IAAI,MAAM,IAAI,GACtB,MAAM,IAAI,MAAM,wCAAwC,MAAM,KAAK,eAAe;EAEpF,MAAM,IAAI,MAAM,IAAI;CACtB;CACA,OAAO,OAAO,OAAO,CAAC,GAAG,MAAM,CAAC;AAClC;AAEA,MAAM,oCAAyC,IAAI,IAAI;;;;;;;AAQvD,SAAgB,uBACd,QACA,YACA,kBAAsC,8BAA8B,GACpE,gBAAqC,mBAC3B;CACV,MAAM,YAAY,IAAI,IAAI,WAAW,KAAI,UAAS,MAAM,IAAI,CAAC;CAC7D,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,CAAC,SAAS,UAAU,QAC7B,KAAK,MAAM,CAAC,SAAS,UAAU,OAAO,QAAQ,MAAM,MAAM,GAAG;EAC3D,IAAI,MAAM,SAAS,aAAa,CAAC,MAAM,OAAO,OAAO;EACrD,MAAM,EAAE,OAAO,YAAY,MAAM;EACjC,MAAM,QAAQ,UAAU,QAAQ,WAAW,QAAQ;EAMnD,IAAI,EAJF,UAAU,IAAI,KAAK,KACnB,oBAAoB,IAAI,KAAK,KAC7B,cAAc,IAAI,KAAK,KACtB,oBAAoB,KAAA,KAAa,WAAW,KAAK,iBAAiB,OAAO,UAAU,CAAC,IAErF,SAAS,KACP,GAAG,MAAM,eAAe,MAAM,wFAAwF,MAAM,8CAC9H;OACK,IAAI,2BAA2B,IAAI,KAAK,KAAK,YAAY,UAC9D,SAAS,KACP,GAAG,MAAM,sBAAsB,MAAM,YAAY,QAAQ,4DAC3D;CAEJ;CAEF,OAAO;AACT"}
|
package/dist/skills/catalog.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { InlineSkill } from '@mastra/core/skills';
|
|
2
|
-
import type {
|
|
2
|
+
import type { ProjectSkillNames } from '../boards/project-boards.js';
|
|
3
|
+
import type { SkillOverrideRecord, SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';
|
|
3
4
|
/** Where a skill comes from: shipped with Factory, the app's `factory-skills/` folder, or `MastraFactory({ skills })`. */
|
|
4
5
|
export type FactorySkillOrigin = 'bundled' | 'folder' | 'code';
|
|
6
|
+
/** Where a listed skill comes from: an original's origin, or `project` for a skill the project created. */
|
|
7
|
+
export type FactorySkillCatalogOrigin = FactorySkillOrigin | 'project';
|
|
5
8
|
export interface FactorySkillInfo {
|
|
6
9
|
name: string;
|
|
7
10
|
description: string;
|
|
@@ -9,7 +12,7 @@ export interface FactorySkillInfo {
|
|
|
9
12
|
content: string;
|
|
10
13
|
/** Frontmatter fields besides `name` and `description` (license, user-invocable, …), so an editor can keep them. */
|
|
11
14
|
frontmatter?: Record<string, unknown>;
|
|
12
|
-
origin:
|
|
15
|
+
origin: FactorySkillCatalogOrigin;
|
|
13
16
|
/** True for the skills Factory ships, including when the app overrides one. */
|
|
14
17
|
builtIn: boolean;
|
|
15
18
|
/** Set when the SKILL.md fails the runtime's parsing/validation, so the agent will not be able to load it. */
|
|
@@ -19,6 +22,11 @@ export interface FactorySkillInfo {
|
|
|
19
22
|
updatedBy: string;
|
|
20
23
|
updatedAt: string;
|
|
21
24
|
};
|
|
25
|
+
/** Set for a skill the project created (`origin: 'project'`): who saved it last, and when. */
|
|
26
|
+
created?: {
|
|
27
|
+
updatedBy: string;
|
|
28
|
+
updatedAt: string;
|
|
29
|
+
};
|
|
22
30
|
/** True when the code, folder, or bundled SKILL.md changed since the project's edit was made. */
|
|
23
31
|
originalChanged?: boolean;
|
|
24
32
|
}
|
|
@@ -35,11 +43,22 @@ export declare function hashSkillContent(raw: string): string;
|
|
|
35
43
|
* skills of the same name.
|
|
36
44
|
*/
|
|
37
45
|
export declare function readFactorySkillOriginals(codeSkills?: readonly InlineSkill[]): Promise<Map<string, FactorySkillOriginal>>;
|
|
46
|
+
/** The catalog entry of a skill the project created, from its stored row. */
|
|
47
|
+
export declare function createdSkillInfo(created: SkillOverrideRecord): FactorySkillInfo;
|
|
48
|
+
/** The catalog entry of a code, folder, or bundled skill, showing the project's `edit` of it when it has one. */
|
|
49
|
+
export declare function originalSkillInfo(name: string, { raw, origin }: FactorySkillOriginal, edit?: SkillOverrideRecord): FactorySkillInfo;
|
|
38
50
|
/**
|
|
39
51
|
* List the skills the Factory skill mount serves, sorted by name. With a
|
|
40
52
|
* project's `overrides`, edited skills show the edited text, who edited them,
|
|
41
|
-
* and whether the original changed since
|
|
42
|
-
*
|
|
53
|
+
* and whether the original changed since, and the project's created skills
|
|
54
|
+
* are listed with origin `project`. Edits of skills that no longer exist are
|
|
55
|
+
* not listed, matching what sessions load. A created skill whose name an app
|
|
56
|
+
* skill later takes is listed as that skill's edit.
|
|
43
57
|
*/
|
|
44
58
|
export declare function listFactorySkills(codeSkills?: readonly InlineSkill[], overrides?: readonly SkillOverrideRecord[]): Promise<FactorySkillInfo[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Reads the skills each project created, for its boards' runners. A created skill an app skill later
|
|
61
|
+
* shadows still counts: a runner naming it finds the app's skill.
|
|
62
|
+
*/
|
|
63
|
+
export declare function projectSkillNamesOf(storage: Pick<SkillOverridesStorage, 'ensureReady' | 'revision' | 'list'>): ProjectSkillNames;
|
|
45
64
|
//# sourceMappingURL=catalog.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../src/skills/catalog.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAIvD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAAC;
|
|
1
|
+
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../src/skills/catalog.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAIvD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAErE,OAAO,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AAQ7G,0HAA0H;AAC1H,MAAM,MAAM,kBAAkB,GAAG,SAAS,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE/D,2GAA2G;AAC3G,MAAM,MAAM,yBAAyB,GAAG,kBAAkB,GAAG,SAAS,CAAC;AAEvE,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,wDAAwD;IACxD,OAAO,EAAE,MAAM,CAAC;IAChB,oHAAoH;IACpH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,MAAM,EAAE,yBAAyB,CAAC;IAClC,+EAA+E;IAC/E,OAAO,EAAE,OAAO,CAAC;IACjB,8GAA8G;IAC9G,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oGAAoG;IACpG,MAAM,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAClD,8FAA8F;IAC9F,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IACnD,iGAAiG;IACjG,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,yFAAyF;AACzF,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,kBAAkB,CAAC;CAC5B;AAED,mHAAmH;AACnH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEpD;AAoCD;;;;GAIG;AACH,wBAAsB,yBAAyB,CAC7C,UAAU,GAAE,SAAS,WAAW,EAAO,GACtC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,CAqB5C;AAED,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,gBAAgB,CAQ/E;AAED,iHAAiH;AACjH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,oBAAoB,EACrC,IAAI,CAAC,EAAE,mBAAmB,GACzB,gBAAgB,CAWlB;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CACrC,UAAU,GAAE,SAAS,WAAW,EAAO,EACvC,SAAS,GAAE,SAAS,mBAAmB,EAAO,GAC7C,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAQ7B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,IAAI,CAAC,qBAAqB,EAAE,aAAa,GAAG,UAAU,GAAG,MAAM,CAAC,GACxE,iBAAiB,CAanB"}
|
package/dist/skills/catalog.js
CHANGED
|
@@ -80,41 +80,74 @@ async function readFactorySkillOriginals(codeSkills = []) {
|
|
|
80
80
|
}
|
|
81
81
|
return originals;
|
|
82
82
|
}
|
|
83
|
+
/** The catalog entry of a skill the project created, from its stored row. */
|
|
84
|
+
function createdSkillInfo(created) {
|
|
85
|
+
return {
|
|
86
|
+
name: created.skillName,
|
|
87
|
+
...parseSkillMarkdown(created.skillName, created.content),
|
|
88
|
+
origin: "project",
|
|
89
|
+
builtIn: false,
|
|
90
|
+
created: {
|
|
91
|
+
updatedBy: created.updatedBy,
|
|
92
|
+
updatedAt: created.updatedAt.toISOString()
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** The catalog entry of a code, folder, or bundled skill, showing the project's `edit` of it when it has one. */
|
|
97
|
+
function originalSkillInfo(name, { raw, origin }, edit) {
|
|
98
|
+
const builtIn = FACTORY_SKILL_NAMES.has(name);
|
|
99
|
+
if (!edit) return {
|
|
100
|
+
name,
|
|
101
|
+
...parseSkillMarkdown(name, raw),
|
|
102
|
+
origin,
|
|
103
|
+
builtIn
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
name,
|
|
107
|
+
...parseSkillMarkdown(name, edit.content),
|
|
108
|
+
origin,
|
|
109
|
+
builtIn,
|
|
110
|
+
edited: {
|
|
111
|
+
updatedBy: edit.updatedBy,
|
|
112
|
+
updatedAt: edit.updatedAt.toISOString()
|
|
113
|
+
},
|
|
114
|
+
originalChanged: hashSkillContent(raw) !== edit.baseHash
|
|
115
|
+
};
|
|
116
|
+
}
|
|
83
117
|
/**
|
|
84
118
|
* List the skills the Factory skill mount serves, sorted by name. With a
|
|
85
119
|
* project's `overrides`, edited skills show the edited text, who edited them,
|
|
86
|
-
* and whether the original changed since
|
|
87
|
-
*
|
|
120
|
+
* and whether the original changed since, and the project's created skills
|
|
121
|
+
* are listed with origin `project`. Edits of skills that no longer exist are
|
|
122
|
+
* not listed, matching what sessions load. A created skill whose name an app
|
|
123
|
+
* skill later takes is listed as that skill's edit.
|
|
88
124
|
*/
|
|
89
125
|
async function listFactorySkills(codeSkills = [], overrides = []) {
|
|
90
126
|
const edits = new Map(overrides.map((override) => [override.skillName, override]));
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
127
|
+
const originals = await readFactorySkillOriginals(codeSkills);
|
|
128
|
+
return [...overrides.filter((override) => override.kind === "created" && !originals.has(override.skillName)).map(createdSkillInfo), ...[...originals].map(([name, original]) => originalSkillInfo(name, original, edits.get(name)))].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Reads the skills each project created, for its boards' runners. A created skill an app skill later
|
|
132
|
+
* shadows still counts: a runner naming it finds the app's skill.
|
|
133
|
+
*/
|
|
134
|
+
function projectSkillNamesOf(storage) {
|
|
135
|
+
const projectScope = (scope) => ({
|
|
136
|
+
orgId: scope.orgId,
|
|
137
|
+
projectId: scope.factoryProjectId
|
|
138
|
+
});
|
|
139
|
+
return {
|
|
140
|
+
revision: async (scope) => {
|
|
141
|
+
await storage.ensureReady();
|
|
142
|
+
return storage.revision(projectScope(scope));
|
|
143
|
+
},
|
|
144
|
+
names: async (scope) => {
|
|
145
|
+
await storage.ensureReady();
|
|
146
|
+
const overrides = await storage.list(projectScope(scope));
|
|
147
|
+
return new Set(overrides.filter((override) => override.kind === "created").map((override) => override.skillName));
|
|
103
148
|
}
|
|
104
|
-
|
|
105
|
-
name,
|
|
106
|
-
...parseSkillMarkdown(name, edit.content),
|
|
107
|
-
origin,
|
|
108
|
-
builtIn,
|
|
109
|
-
edited: {
|
|
110
|
-
updatedBy: edit.updatedBy,
|
|
111
|
-
updatedAt: edit.updatedAt.toISOString()
|
|
112
|
-
},
|
|
113
|
-
originalChanged: hashSkillContent(raw) !== edit.baseHash
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
return skills;
|
|
149
|
+
};
|
|
117
150
|
}
|
|
118
|
-
export { hashSkillContent, listFactorySkills, readFactorySkillOriginals };
|
|
151
|
+
export { createdSkillInfo, hashSkillContent, listFactorySkills, originalSkillInfo, projectSkillNamesOf, readFactorySkillOriginals };
|
|
119
152
|
|
|
120
153
|
//# sourceMappingURL=catalog.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","names":[],"sources":["../../src/skills/catalog.ts"],"sourcesContent":["/**\n * Read-only catalog of the Factory skills.\n *\n * Lists every skill the Factory skill mount serves — the built-in skills the\n * pipeline invokes at each stage (triage, plan, review, …) and the app's own\n * skills from `MastraFactory({ skills })` or its `factory-skills/` folder. It\n * reads them through the same `FactorySkillSource` sessions use, so the\n * settings UI shows exactly what each skill instructs the agent to do — and\n * whether the runtime can load it.\n */\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { InlineSkill } from '@mastra/core/skills';\nimport { validateSkillContent } from '@mastra/core/skills';\nimport type { SkillSource } from '@mastra/core/workspace';\n\nimport type { SkillOverrideRecord } from '../storage/domains/skill-overrides/base.js';\nimport {\n FACTORY_SKILL_NAMES,\n FACTORY_SKILLS_MOUNT,\n FactorySkillSource,\n resolveLocalFactorySkillsPath,\n} from '../workspace.js';\n\n/** Where a skill comes from: shipped with Factory, the app's `factory-skills/` folder, or `MastraFactory({ skills })`. */\nexport type FactorySkillOrigin = 'bundled' | 'folder' | 'code';\n\nexport interface FactorySkillInfo {\n name: string;\n description: string;\n /** SKILL.md body with the frontmatter block removed. */\n content: string;\n /** Frontmatter fields besides `name` and `description` (license, user-invocable, …), so an editor can keep them. */\n frontmatter?: Record<string, unknown>;\n origin: FactorySkillOrigin;\n /** True for the skills Factory ships, including when the app overrides one. */\n builtIn: boolean;\n /** Set when the SKILL.md fails the runtime's parsing/validation, so the agent will not be able to load it. */\n error?: string;\n /** Set when the project has an edited copy; `description` and `content` then come from the edit. */\n edited?: { updatedBy: string; updatedAt: string };\n /** True when the code, folder, or bundled SKILL.md changed since the project's edit was made. */\n originalChanged?: boolean;\n}\n\n/** The SKILL.md a skill resolves to without any project edit, and where it came from. */\nexport interface FactorySkillOriginal {\n raw: string;\n origin: FactorySkillOrigin;\n}\n\n/** Fingerprint of an original SKILL.md, stored with an edit so the catalog can tell when the original moved on. */\nexport function hashSkillContent(raw: string): string {\n return createHash('sha256').update(raw).digest('hex');\n}\n\nfunction parseSkillMarkdown(\n name: string,\n raw: string,\n): Pick<FactorySkillInfo, 'description' | 'content' | 'frontmatter' | 'error'> {\n // Use the same parser and validation the runtime applies when loading skills,\n // so the catalog never shows a skill as healthy that the agent will drop.\n const result = validateSkillContent({ content: raw, directoryName: name });\n const description = typeof result.metadata?.description === 'string' ? result.metadata.description : '';\n const content = result.instructions ?? stripFrontmatter(raw);\n const extra = Object.entries(result.metadata ?? {}).filter(\n ([key, value]) => key !== 'name' && key !== 'description' && value !== undefined,\n );\n const frontmatter = extra.length > 0 ? { frontmatter: Object.fromEntries(extra) } : {};\n if (!result.valid) return { description, content, ...frontmatter, error: result.errors.join('\\n') };\n return { description, content, ...frontmatter };\n}\n\n/** Best-effort body extraction when the frontmatter cannot be parsed, so users can still read the file they need to fix. */\nfunction stripFrontmatter(raw: string): string {\n const match = raw.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/);\n return (match ? raw.slice(match[0].length) : raw).trim();\n}\n\nconst NO_REPOSITORY_SKILLS: SkillSource = {\n exists: async () => false,\n stat: async path => {\n throw new Error(`ENOENT: no such file or directory, '${path}'`);\n },\n readFile: async path => {\n throw new Error(`ENOENT: no such file or directory, '${path}'`);\n },\n readdir: async () => [],\n};\n\n/**\n * Read the original SKILL.md of every skill the Factory skill mount serves,\n * keyed by name. Code skills win over folder skills, which win over bundled\n * skills of the same name.\n */\nexport async function readFactorySkillOriginals(\n codeSkills: readonly InlineSkill[] = [],\n): Promise<Map<string, FactorySkillOriginal>> {\n const localRoot = resolveLocalFactorySkillsPath();\n const source = new FactorySkillSource(NO_REPOSITORY_SKILLS, [], localRoot, async () => true, codeSkills);\n const codeNames = new Set(codeSkills.map(skill => skill.name));\n const entries = (await source.readdir(FACTORY_SKILLS_MOUNT)).filter(entry => entry.type === 'directory');\n const originals = new Map<string, FactorySkillOriginal>();\n for (const name of entries.map(entry => entry.name).sort()) {\n let raw: string;\n try {\n raw = String(await source.readFile(join(FACTORY_SKILLS_MOUNT, name, 'SKILL.md')));\n } catch {\n continue;\n }\n const origin: FactorySkillOrigin = codeNames.has(name)\n ? 'code'\n : localRoot && existsSync(join(localRoot, name, 'SKILL.md'))\n ? 'folder'\n : 'bundled';\n originals.set(name, { raw, origin });\n }\n return originals;\n}\n\n/**\n * List the skills the Factory skill mount serves, sorted by name. With a\n * project's `overrides`, edited skills show the edited text, who edited them,\n * and whether the original changed since. Edits of skills that no longer\n * exist are not listed, matching what sessions load.\n */\nexport async function listFactorySkills(\n codeSkills: readonly InlineSkill[] = [],\n overrides: readonly SkillOverrideRecord[] = [],\n): Promise<FactorySkillInfo[]> {\n const edits = new Map(overrides.map(override => [override.skillName, override]));\n const skills: FactorySkillInfo[] = [];\n for (const [name, { raw, origin }] of await readFactorySkillOriginals(codeSkills)) {\n const edit = edits.get(name);\n const builtIn = FACTORY_SKILL_NAMES.has(name);\n if (!edit) {\n skills.push({ name, ...parseSkillMarkdown(name, raw), origin, builtIn });\n continue;\n }\n skills.push({\n name,\n ...parseSkillMarkdown(name, edit.content),\n origin,\n builtIn,\n edited: { updatedBy: edit.updatedBy, updatedAt: edit.updatedAt.toISOString() },\n originalChanged: hashSkillContent(raw) !== edit.baseHash,\n });\n }\n return skills;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsDA,SAAgB,iBAAiB,KAAqB;CACpD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK;AACtD;AAEA,SAAS,mBACP,MACA,KAC6E;CAG7E,MAAM,SAAS,qBAAqB;EAAE,SAAS;EAAK,eAAe;CAAK,CAAC;CACzE,MAAM,cAAc,OAAO,OAAO,UAAU,gBAAgB,WAAW,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EAC1D,IAAI;EACJ,IAAI;GACF,MAAM,OAAO,MAAM,OAAO,SAAS,KAAK,sBAAsB,MAAM,UAAU,CAAC,CAAC;EAClF,QAAQ;GACN;EACF;EACA,MAAM,SAA6B,UAAU,IAAI,IAAI,IACjD,SACA,aAAa,WAAW,KAAK,WAAW,MAAM,UAAU,CAAC,IACvD,WACA;EACN,UAAU,IAAI,MAAM;GAAE;GAAK;EAAO,CAAC;CACrC;CACA,OAAO;AACT;;;;;;;AAQA,eAAsB,kBACpB,aAAqC,CAAC,GACtC,YAA4C,CAAC,GAChB;CAC7B,MAAM,QAAQ,IAAI,IAAI,UAAU,KAAI,aAAY,CAAC,SAAS,WAAW,QAAQ,CAAC,CAAC;CAC/E,MAAM,SAA6B,CAAC;CACpC,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,aAAa,MAAM,0BAA0B,UAAU,GAAG;EACjF,MAAM,OAAO,MAAM,IAAI,IAAI;EAC3B,MAAM,UAAU,oBAAoB,IAAI,IAAI;EAC5C,IAAI,CAAC,MAAM;GACT,OAAO,KAAK;IAAE;IAAM,GAAG,mBAAmB,MAAM,GAAG;IAAG;IAAQ;GAAQ,CAAC;GACvE;EACF;EACA,OAAO,KAAK;GACV;GACA,GAAG,mBAAmB,MAAM,KAAK,OAAO;GACxC;GACA;GACA,QAAQ;IAAE,WAAW,KAAK;IAAW,WAAW,KAAK,UAAU,YAAY;GAAE;GAC7E,iBAAiB,iBAAiB,GAAG,MAAM,KAAK;EAClD,CAAC;CACH;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"catalog.js","names":[],"sources":["../../src/skills/catalog.ts"],"sourcesContent":["/**\n * Read-only catalog of the Factory skills.\n *\n * Lists every skill the Factory skill mount serves — the built-in skills the\n * pipeline invokes at each stage (triage, plan, review, …) and the app's own\n * skills from `MastraFactory({ skills })` or its `factory-skills/` folder. It\n * reads them through the same `FactorySkillSource` sessions use, so the\n * settings UI shows exactly what each skill instructs the agent to do — and\n * whether the runtime can load it.\n */\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { InlineSkill } from '@mastra/core/skills';\nimport { validateSkillContent } from '@mastra/core/skills';\nimport type { SkillSource } from '@mastra/core/workspace';\n\nimport type { ProjectSkillNames } from '../boards/project-boards.js';\nimport type { StoredBoardScope } from '../storage/domains/boards/base.js';\nimport type { SkillOverrideRecord, SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';\nimport {\n FACTORY_SKILL_NAMES,\n FACTORY_SKILLS_MOUNT,\n FactorySkillSource,\n resolveLocalFactorySkillsPath,\n} from '../workspace.js';\n\n/** Where a skill comes from: shipped with Factory, the app's `factory-skills/` folder, or `MastraFactory({ skills })`. */\nexport type FactorySkillOrigin = 'bundled' | 'folder' | 'code';\n\n/** Where a listed skill comes from: an original's origin, or `project` for a skill the project created. */\nexport type FactorySkillCatalogOrigin = FactorySkillOrigin | 'project';\n\nexport interface FactorySkillInfo {\n name: string;\n description: string;\n /** SKILL.md body with the frontmatter block removed. */\n content: string;\n /** Frontmatter fields besides `name` and `description` (license, user-invocable, …), so an editor can keep them. */\n frontmatter?: Record<string, unknown>;\n origin: FactorySkillCatalogOrigin;\n /** True for the skills Factory ships, including when the app overrides one. */\n builtIn: boolean;\n /** Set when the SKILL.md fails the runtime's parsing/validation, so the agent will not be able to load it. */\n error?: string;\n /** Set when the project has an edited copy; `description` and `content` then come from the edit. */\n edited?: { updatedBy: string; updatedAt: string };\n /** Set for a skill the project created (`origin: 'project'`): who saved it last, and when. */\n created?: { updatedBy: string; updatedAt: string };\n /** True when the code, folder, or bundled SKILL.md changed since the project's edit was made. */\n originalChanged?: boolean;\n}\n\n/** The SKILL.md a skill resolves to without any project edit, and where it came from. */\nexport interface FactorySkillOriginal {\n raw: string;\n origin: FactorySkillOrigin;\n}\n\n/** Fingerprint of an original SKILL.md, stored with an edit so the catalog can tell when the original moved on. */\nexport function hashSkillContent(raw: string): string {\n return createHash('sha256').update(raw).digest('hex');\n}\n\nfunction parseSkillMarkdown(\n name: string,\n raw: string,\n): Pick<FactorySkillInfo, 'description' | 'content' | 'frontmatter' | 'error'> {\n // Use the same parser and validation the runtime applies when loading skills,\n // so the catalog never shows a skill as healthy that the agent will drop.\n const result = validateSkillContent({ content: raw, directoryName: name });\n const description = typeof result.metadata?.description === 'string' ? result.metadata.description : '';\n const content = result.instructions ?? stripFrontmatter(raw);\n const extra = Object.entries(result.metadata ?? {}).filter(\n ([key, value]) => key !== 'name' && key !== 'description' && value !== undefined,\n );\n const frontmatter = extra.length > 0 ? { frontmatter: Object.fromEntries(extra) } : {};\n if (!result.valid) return { description, content, ...frontmatter, error: result.errors.join('\\n') };\n return { description, content, ...frontmatter };\n}\n\n/** Best-effort body extraction when the frontmatter cannot be parsed, so users can still read the file they need to fix. */\nfunction stripFrontmatter(raw: string): string {\n const match = raw.match(/^---\\r?\\n[\\s\\S]*?\\r?\\n---\\r?\\n?/);\n return (match ? raw.slice(match[0].length) : raw).trim();\n}\n\nconst NO_REPOSITORY_SKILLS: SkillSource = {\n exists: async () => false,\n stat: async path => {\n throw new Error(`ENOENT: no such file or directory, '${path}'`);\n },\n readFile: async path => {\n throw new Error(`ENOENT: no such file or directory, '${path}'`);\n },\n readdir: async () => [],\n};\n\n/**\n * Read the original SKILL.md of every skill the Factory skill mount serves,\n * keyed by name. Code skills win over folder skills, which win over bundled\n * skills of the same name.\n */\nexport async function readFactorySkillOriginals(\n codeSkills: readonly InlineSkill[] = [],\n): Promise<Map<string, FactorySkillOriginal>> {\n const localRoot = resolveLocalFactorySkillsPath();\n const source = new FactorySkillSource(NO_REPOSITORY_SKILLS, [], localRoot, async () => true, codeSkills);\n const codeNames = new Set(codeSkills.map(skill => skill.name));\n const entries = (await source.readdir(FACTORY_SKILLS_MOUNT)).filter(entry => entry.type === 'directory');\n const originals = new Map<string, FactorySkillOriginal>();\n for (const name of entries.map(entry => entry.name).sort()) {\n let raw: string;\n try {\n raw = String(await source.readFile(join(FACTORY_SKILLS_MOUNT, name, 'SKILL.md')));\n } catch {\n continue;\n }\n const origin: FactorySkillOrigin = codeNames.has(name)\n ? 'code'\n : localRoot && existsSync(join(localRoot, name, 'SKILL.md'))\n ? 'folder'\n : 'bundled';\n originals.set(name, { raw, origin });\n }\n return originals;\n}\n\n/** The catalog entry of a skill the project created, from its stored row. */\nexport function createdSkillInfo(created: SkillOverrideRecord): FactorySkillInfo {\n return {\n name: created.skillName,\n ...parseSkillMarkdown(created.skillName, created.content),\n origin: 'project',\n builtIn: false,\n created: { updatedBy: created.updatedBy, updatedAt: created.updatedAt.toISOString() },\n };\n}\n\n/** The catalog entry of a code, folder, or bundled skill, showing the project's `edit` of it when it has one. */\nexport function originalSkillInfo(\n name: string,\n { raw, origin }: FactorySkillOriginal,\n edit?: SkillOverrideRecord,\n): FactorySkillInfo {\n const builtIn = FACTORY_SKILL_NAMES.has(name);\n if (!edit) return { name, ...parseSkillMarkdown(name, raw), origin, builtIn };\n return {\n name,\n ...parseSkillMarkdown(name, edit.content),\n origin,\n builtIn,\n edited: { updatedBy: edit.updatedBy, updatedAt: edit.updatedAt.toISOString() },\n originalChanged: hashSkillContent(raw) !== edit.baseHash,\n };\n}\n\n/**\n * List the skills the Factory skill mount serves, sorted by name. With a\n * project's `overrides`, edited skills show the edited text, who edited them,\n * and whether the original changed since, and the project's created skills\n * are listed with origin `project`. Edits of skills that no longer exist are\n * not listed, matching what sessions load. A created skill whose name an app\n * skill later takes is listed as that skill's edit.\n */\nexport async function listFactorySkills(\n codeSkills: readonly InlineSkill[] = [],\n overrides: readonly SkillOverrideRecord[] = [],\n): Promise<FactorySkillInfo[]> {\n const edits = new Map(overrides.map(override => [override.skillName, override]));\n const originals = await readFactorySkillOriginals(codeSkills);\n const created = overrides.filter(override => override.kind === 'created' && !originals.has(override.skillName));\n return [\n ...created.map(createdSkillInfo),\n ...[...originals].map(([name, original]) => originalSkillInfo(name, original, edits.get(name))),\n ].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\n/**\n * Reads the skills each project created, for its boards' runners. A created skill an app skill later\n * shadows still counts: a runner naming it finds the app's skill.\n */\nexport function projectSkillNamesOf(\n storage: Pick<SkillOverridesStorage, 'ensureReady' | 'revision' | 'list'>,\n): ProjectSkillNames {\n const projectScope = (scope: StoredBoardScope) => ({ orgId: scope.orgId, projectId: scope.factoryProjectId });\n return {\n revision: async scope => {\n await storage.ensureReady();\n return storage.revision(projectScope(scope));\n },\n names: async scope => {\n await storage.ensureReady();\n const overrides = await storage.list(projectScope(scope));\n return new Set(overrides.filter(override => override.kind === 'created').map(override => override.skillName));\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA6DA,SAAgB,iBAAiB,KAAqB;CACpD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK;AACtD;AAEA,SAAS,mBACP,MACA,KAC6E;CAG7E,MAAM,SAAS,qBAAqB;EAAE,SAAS;EAAK,eAAe;CAAK,CAAC;CACzE,MAAM,cAAc,OAAO,OAAO,UAAU,gBAAgB,WAAW,OAAO,SAAS,cAAc;CACrG,MAAM,UAAU,OAAO,gBAAgB,iBAAiB,GAAG;CAC3D,MAAM,QAAQ,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,QACjD,CAAC,KAAK,WAAW,QAAQ,UAAU,QAAQ,iBAAiB,UAAU,KAAA,CACzE;CACA,MAAM,cAAc,MAAM,SAAS,IAAI,EAAE,aAAa,OAAO,YAAY,KAAK,EAAE,IAAI,CAAC;CACrF,IAAI,CAAC,OAAO,OAAO,OAAO;EAAE;EAAa;EAAS,GAAG;EAAa,OAAO,OAAO,OAAO,KAAK,IAAI;CAAE;CAClG,OAAO;EAAE;EAAa;EAAS,GAAG;CAAY;AAChD;;AAGA,SAAS,iBAAiB,KAAqB;CAC7C,MAAM,QAAQ,IAAI,MAAM,iCAAiC;CACzD,QAAQ,QAAQ,IAAI,MAAM,MA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AS,SAAS,CAAC,CAAC,KAAI,aAAY,SAAS,SAAS,CAAC;EAC9G;CACF;AACF"}
|
|
@@ -11,7 +11,7 @@ export declare const AUDIT_ACTIONS: {
|
|
|
11
11
|
readonly intake_order: readonly ['updated', 'evaluator_updated'];
|
|
12
12
|
readonly session: readonly ['owner_transferred'];
|
|
13
13
|
readonly board: readonly ['created', 'updated', 'deleted', 'reset'];
|
|
14
|
-
readonly skill: readonly ['updated', 'reverted'];
|
|
14
|
+
readonly skill: readonly ['created', 'updated', 'reverted', 'deleted'];
|
|
15
15
|
readonly intake_route: readonly ['created', 'updated', 'deleted', 'reordered', 'rerouted'];
|
|
16
16
|
readonly sandbox_env: readonly ['set', 'updated', 'deleted'];
|
|
17
17
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actions.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,aAAa;aACxB,SAAS,YAAG,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,qBAAqB,EAAE,mBAAmB;aACtG,GAAG,YAAG,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,OAAO,EAAE,QAAQ,EAAE,UAAU;aAChF,GAAG,YAAG,QAAQ,EAAE,MAAM,EAAE,WAAW;aACnC,KAAK,YAAG,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU;aACjD,MAAM,YAAG,gBAAgB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,cAAc;aACnF,YAAY,YAAG,SAAS,EAAE,mBAAmB;aAC7C,OAAO,YAAG,mBAAmB;aAC7B,KAAK,YAAG,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO;aAChD,KAAK,YAAG,SAAS,EAAE,UAAU;
|
|
1
|
+
{"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/audit/actions.ts"],"names":[],"mappings":"AAA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