@mastra/factory 0.31.0-alpha.1 → 0.31.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/integrations/github/review-status-comment.d.ts +4 -0
- package/dist/integrations/github/review-status-comment.d.ts.map +1 -1
- package/dist/integrations/github/review-status-comment.js +24 -8
- package/dist/integrations/github/review-status-comment.js.map +1 -1
- package/dist/integrations/github/review-status-reporter.d.ts.map +1 -1
- package/dist/integrations/github/review-status-reporter.js +8 -1
- package/dist/integrations/github/review-status-reporter.js.map +1 -1
- package/dist/integrations/github/review-status.d.ts.map +1 -1
- package/dist/integrations/github/review-status.js +2 -1
- package/dist/integrations/github/review-status.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts +6 -0
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +22 -3
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +5 -1
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +3 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +5 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +12 -3
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts.map +1 -1
- package/dist/session/work-item-state-processor.js +7 -1
- package/dist/session/work-item-state-processor.js.map +1 -1
- package/factory-skills/factory-build/SKILL.md +1 -1
- package/factory-skills/factory-self-review/SKILL.md +1 -1
- package/factory-skills/factory-triage/SKILL.md +5 -3
- package/package.json +7 -7
|
@@ -24,6 +24,8 @@ export interface ReviewStatusState {
|
|
|
24
24
|
startedAt?: string;
|
|
25
25
|
/** The pull request head when the run started. */
|
|
26
26
|
head?: string;
|
|
27
|
+
/** The Factory UI link to the session running the review. Absent until the run starts. */
|
|
28
|
+
session?: string;
|
|
27
29
|
}
|
|
28
30
|
export interface ReviewStatusStats {
|
|
29
31
|
verdict?: 'approve' | 'request changes';
|
|
@@ -46,6 +48,8 @@ export interface ReviewStatusView {
|
|
|
46
48
|
}
|
|
47
49
|
/** Reads the hidden state line. Anything malformed reads as no state. */
|
|
48
50
|
export declare function parseReviewStatusState(body: string | null | undefined): ReviewStatusState | undefined;
|
|
51
|
+
/** An http(s) URL that is safe inside a markdown link target. */
|
|
52
|
+
export declare function isSessionUrl(value: unknown): value is string;
|
|
49
53
|
/**
|
|
50
54
|
* Whether `next` may overwrite a comment holding `existing`. A different run
|
|
51
55
|
* wins only when it was requested later. Within one run, steps only move
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status-comment.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/review-status-comment.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,4BAA4B,0CAA0C,CAAC;AAIpF,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,WAAW,GAAG,UAAU,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE3G,6FAA6F;AAC7F,MAAM,WAAW,iBAAiB;IAChC,gFAAgF;IAChF,GAAG,EAAE,MAAM,CAAC;IACZ,kEAAkE;IAClE,WAAW,EAAE,MAAM,CAAC;IACpB,sFAAsF;IACtF,UAAU,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,iBAAiB,CAAC;IACzB,yEAAyE;IACzE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kDAAkD;IAClD,IAAI,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"review-status-comment.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/review-status-comment.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,4BAA4B,0CAA0C,CAAC;AAIpF,MAAM,MAAM,iBAAiB,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AgB,sBAAsB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,SAAS,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAUhH;AAMD,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAQjD;AAwDD,wBAAgB,UAAU,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAEvD;AA8FD,gHAAgH;AAChH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAGxE"}
|
|
@@ -55,9 +55,20 @@ function parseReviewStatusState(body) {
|
|
|
55
55
|
attempt: value.attempt,
|
|
56
56
|
phase: value.phase,
|
|
57
57
|
...isTimestamp(value.startedAt) ? { startedAt: value.startedAt } : {},
|
|
58
|
-
...typeof value.head === "string" && COMMIT_SHA.test(value.head) ? { head: value.head } : {}
|
|
58
|
+
...typeof value.head === "string" && COMMIT_SHA.test(value.head) ? { head: value.head } : {},
|
|
59
|
+
...isSessionUrl(value.session) ? { session: value.session } : {}
|
|
59
60
|
};
|
|
60
61
|
}
|
|
62
|
+
/** An http(s) URL that is safe inside a markdown link target. */
|
|
63
|
+
function isSessionUrl(value) {
|
|
64
|
+
if (typeof value !== "string" || !/^https?:\/\/[^\s()<>"'`]+$/.test(value)) return false;
|
|
65
|
+
try {
|
|
66
|
+
new URL(value);
|
|
67
|
+
return true;
|
|
68
|
+
} catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
61
72
|
/**
|
|
62
73
|
* Whether `next` may overwrite a comment holding `existing`. A different run
|
|
63
74
|
* wins only when it was requested later. Within one run, steps only move
|
|
@@ -111,15 +122,19 @@ function commitLink(sha, repository) {
|
|
|
111
122
|
return repository && REPOSITORY_SLUG.test(repository) ? `[${code}](https://github.com/${repository}/commit/${sha})` : code;
|
|
112
123
|
}
|
|
113
124
|
/**
|
|
114
|
-
* A quiet line under
|
|
115
|
-
*
|
|
125
|
+
* A quiet line under the status: the commit and how long a finished run took, and the link to
|
|
126
|
+
* the session running the review once it has started. Only a recorded verdict's commit is called
|
|
127
|
+
* reviewed; otherwise it is the head the run started on.
|
|
116
128
|
*/
|
|
117
129
|
function footer(view) {
|
|
118
130
|
const { stats = {}, state } = view;
|
|
119
131
|
const parts = [];
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
|
|
132
|
+
if (state.phase === "completed" || state.phase === "failed" || state.phase === "cancelled") {
|
|
133
|
+
if (stats.reviewedHeadSha && stats.verdict && state.phase === "completed") parts.push(`Reviewed ${commitLink(stats.reviewedHeadSha, view.repository)}`);
|
|
134
|
+
else if (state.head) parts.push(`Started on ${commitLink(state.head, view.repository)}`);
|
|
135
|
+
if (stats.durationMs !== void 0) parts.push(`took ${formatDuration(stats.durationMs)}`);
|
|
136
|
+
}
|
|
137
|
+
if (state.session) parts.push(`[Factory session](${state.session})`);
|
|
123
138
|
if (parts.length === 0) return [];
|
|
124
139
|
const line = parts.join(" · ");
|
|
125
140
|
return ["", `<sub>${line.charAt(0).toUpperCase()}${line.slice(1)}</sub>`];
|
|
@@ -178,7 +193,8 @@ function statusLines(view) {
|
|
|
178
193
|
"",
|
|
179
194
|
...animation(view),
|
|
180
195
|
"",
|
|
181
|
-
`${reviewerName} is reviewing this pull request${head}${since}. This comment updates when the review finishes
|
|
196
|
+
`${reviewerName} is reviewing this pull request${head}${since}. This comment updates when the review finishes.`,
|
|
197
|
+
...footer(view)
|
|
182
198
|
];
|
|
183
199
|
}
|
|
184
200
|
case "completed": return [
|
|
@@ -212,6 +228,6 @@ function renderReviewStatusComment(view) {
|
|
|
212
228
|
...quoted
|
|
213
229
|
].join("\n")}\n`;
|
|
214
230
|
}
|
|
215
|
-
export { REVIEW_STATUS_COMMENT_MARKER, formatDuration, gifAltText, parseReviewStatusState, renderReviewStatusComment, supersedesReviewStatus };
|
|
231
|
+
export { REVIEW_STATUS_COMMENT_MARKER, formatDuration, gifAltText, isSessionUrl, parseReviewStatusState, renderReviewStatusComment, supersedesReviewStatus };
|
|
216
232
|
|
|
217
233
|
//# sourceMappingURL=review-status-comment.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status-comment.js","names":[],"sources":["../../../src/integrations/github/review-status-comment.ts"],"sourcesContent":["/**\n * The one status comment Factory keeps on a pull request while it reviews it.\n * The host writes it from the review run's lifecycle, so a crashed or failed\n * run still resolves the comment instead of leaving it claiming work is live.\n *\n * The comment carries its own state in a hidden line. That state orders writes:\n * a newer review run takes the comment over, and a late write from an older run\n * (or an earlier step of the same run) is dropped instead of overwriting it.\n */\n\nexport const REVIEW_STATUS_COMMENT_MARKER = '<!-- mastra-factory-review-status -->';\nconst STATE_PREFIX = '<!-- mastra-factory-review-status:state ';\nconst STATE_SUFFIX = ' -->';\n\nexport type ReviewStatusPhase = 'queued' | 'reviewing' | 'retrying' | 'completed' | 'failed' | 'cancelled';\n\n/** What the hidden state line records; everything else in the comment is derived from it. */\nexport interface ReviewStatusState {\n /** The review run: the dispatcher decision that started it. Retries keep it. */\n run: string;\n /** When the run was requested; orders runs against each other. */\n requestedAt: string;\n /** The dispatcher delivery generation; grows on every retry, manual ones included. */\n generation: number;\n /** The dispatcher attempt, shown to readers. A manual retry restarts it. */\n attempt: number;\n phase: ReviewStatusPhase;\n /** When the agent was handed the review. Absent until the run starts. */\n startedAt?: string;\n /** The pull request head when the run started. */\n head?: string;\n}\n\nexport interface ReviewStatusStats {\n verdict?: 'approve' | 'request changes';\n /** The commit the recorded verdict covers. */\n reviewedHeadSha?: string;\n durationMs?: number;\n}\n\nexport interface ReviewStatusView {\n state: ReviewStatusState;\n stats?: ReviewStatusStats;\n /** Why the run failed or will retry; already sanitized by the dispatcher. */\n reason?: string;\n reviewerName: string;\n /** `owner/name` of the pull request's repository, used to link the commit in the footer. */\n repository?: string;\n /** The animation shown while reviewing; also the fallback for readers without a theme preference. */\n gifUrl: string;\n /** The same animation drawn for GitHub's dark theme, swapped in with `prefers-color-scheme`. */\n gifDarkUrl?: string;\n}\n\nconst PHASE_RANK: Record<ReviewStatusPhase, number> = {\n queued: 0,\n reviewing: 1,\n retrying: 2,\n completed: 3,\n failed: 3,\n cancelled: 3,\n};\n\nconst SAFE_TOKEN = /^[A-Za-z0-9:._-]{1,200}$/;\nconst COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;\n\nfunction isPhase(value: unknown): value is ReviewStatusPhase {\n return typeof value === 'string' && value in PHASE_RANK;\n}\n\nfunction isTimestamp(value: unknown): value is string {\n return typeof value === 'string' && SAFE_TOKEN.test(value) && !Number.isNaN(Date.parse(value));\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0;\n}\n\n/** Reads the hidden state line. Anything malformed reads as no state. */\nexport function parseReviewStatusState(body: string | null | undefined): ReviewStatusState | undefined {\n if (!body) return undefined;\n const start = body.indexOf(STATE_PREFIX);\n if (start < 0) return undefined;\n const end = body.indexOf(STATE_SUFFIX, start + STATE_PREFIX.length);\n if (end < 0) return undefined;\n let raw: unknown;\n try {\n raw = JSON.parse(body.slice(start + STATE_PREFIX.length, end));\n } catch {\n return undefined;\n }\n if (!raw || typeof raw !== 'object') return undefined;\n const value = raw as Record<string, unknown>;\n if (typeof value.run !== 'string' || !SAFE_TOKEN.test(value.run)) return undefined;\n if (!isTimestamp(value.requestedAt) || !isPhase(value.phase)) return undefined;\n if (!isCount(value.generation) || !isCount(value.attempt)) return undefined;\n return {\n run: value.run,\n requestedAt: value.requestedAt,\n generation: value.generation,\n attempt: value.attempt,\n phase: value.phase,\n ...(isTimestamp(value.startedAt) ? { startedAt: value.startedAt } : {}),\n ...(typeof value.head === 'string' && COMMIT_SHA.test(value.head) ? { head: value.head } : {}),\n };\n}\n\n/**\n * Whether `next` may overwrite a comment holding `existing`. A different run\n * wins only when it was requested later. Within one run, steps only move\n * forward: a later delivery generation, or a later phase of the same one. So a\n * duplicate or late write never rewinds the comment, and a final status is only\n * replaced when the run is retried.\n */\nexport function supersedesReviewStatus(existing: ReviewStatusState | undefined, next: ReviewStatusState): boolean {\n if (!existing) return true;\n if (existing.run !== next.run) {\n const existingAt = Date.parse(existing.requestedAt);\n const nextAt = Date.parse(next.requestedAt);\n return nextAt > existingAt || (nextAt === existingAt && next.run > existing.run);\n }\n if (next.generation !== existing.generation) return next.generation > existing.generation;\n if (next.attempt !== existing.attempt) return next.attempt > existing.attempt;\n return PHASE_RANK[next.phase] > PHASE_RANK[existing.phase];\n}\n\nfunction shortSha(sha: string): string {\n return sha.slice(0, 7);\n}\n\nexport function formatDuration(ms: number): string {\n const totalSeconds = Math.max(0, Math.round(ms / 1000));\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n if (hours > 0) return `${hours}h ${minutes}m`;\n if (minutes > 0) return `${minutes}m ${seconds}s`;\n return `${seconds}s`;\n}\n\n/** Plain, single-line text that cannot break out of the code span it is rendered in. */\nfunction inlineCode(text: string, max = 300): string {\n const flat = text\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/`/g, \"'\")\n .trim();\n const clipped = flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n return `\\`${clipped}\\``;\n}\n\nfunction stateLine(state: ReviewStatusState): string {\n return `${STATE_PREFIX}${JSON.stringify(state)}${STATE_SUFFIX}`;\n}\n\nfunction finalHeading(view: ReviewStatusView): string {\n const { phase } = view.state;\n if (phase === 'failed') return '### ❌ Review failed';\n if (phase === 'cancelled') return '### ⏹️ Review cancelled';\n const verdict = view.stats?.verdict;\n if (verdict === 'approve') return '### ✅ Review complete: approved';\n if (verdict === 'request changes') return '### 🔁 Review complete: changes requested';\n return '### ☑️ Review finished';\n}\n\nconst REPOSITORY_SLUG = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction commitLink(sha: string, repository: string | undefined): string {\n const code = `\\`${shortSha(sha)}\\``;\n return repository && REPOSITORY_SLUG.test(repository)\n ? `[${code}](https://github.com/${repository}/commit/${sha})`\n : code;\n}\n\n/**\n * A quiet line under a finished status: the commit and how long the run took. Only a recorded\n * verdict's commit is called reviewed; otherwise it is the head the run started on.\n */\nfunction footer(view: ReviewStatusView): string[] {\n const { stats = {}, state } = view;\n const parts: string[] = [];\n if (stats.reviewedHeadSha && stats.verdict && state.phase === 'completed')\n parts.push(`Reviewed ${commitLink(stats.reviewedHeadSha, view.repository)}`);\n else if (state.head) parts.push(`Started on ${commitLink(state.head, view.repository)}`);\n if (stats.durationMs !== undefined) parts.push(`took ${formatDuration(stats.durationMs)}`);\n if (parts.length === 0) return [];\n const line = parts.join(' · ');\n return ['', `<sub>${line.charAt(0).toUpperCase()}${line.slice(1)}</sub>`];\n}\n\nexport function gifAltText(reviewerName: string): string {\n return `Animated ASCII factory with smoke puffing from its chimneys: ${reviewerName} is reviewing this pull request`;\n}\n\nfunction htmlAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n}\n\n/** Display width for the 468px-wide animation; GitHub keeps the aspect ratio when only the width is set. */\nconst ANIMATION_WIDTH = 360;\n\n/** The reviewing animation, matched to the reader's GitHub theme when a dark variant is configured. */\nfunction animation(view: ReviewStatusView): string[] {\n const img = `<img src=\"${htmlAttribute(view.gifUrl)}\" alt=\"${htmlAttribute(gifAltText(view.reviewerName))}\" width=\"${ANIMATION_WIDTH}\">`;\n if (!view.gifDarkUrl) return [img];\n return [\n '<picture>',\n ` <source media=\"(prefers-color-scheme: dark)\" srcset=\"${htmlAttribute(view.gifDarkUrl)}\">`,\n ` <source media=\"(prefers-color-scheme: light)\" srcset=\"${htmlAttribute(view.gifUrl)}\">`,\n ` ${img}`,\n '</picture>',\n ];\n}\n\ntype AlertType = 'NOTE' | 'TIP' | 'IMPORTANT' | 'WARNING' | 'CAUTION';\n\n/** The GitHub alert that colors each status: blue while waiting or running, green for approval, purple for a result to act on, yellow for a retry or cancellation, red for a failure. */\nfunction alertType(view: ReviewStatusView): AlertType {\n switch (view.state.phase) {\n case 'queued':\n case 'reviewing':\n return 'NOTE';\n case 'retrying':\n case 'cancelled':\n return 'WARNING';\n case 'failed':\n return 'CAUTION';\n case 'completed':\n return view.stats?.verdict === 'approve' ? 'TIP' : 'IMPORTANT';\n }\n}\n\n/** The status content for one lifecycle step, before it is wrapped in its alert. */\nfunction statusLines(view: ReviewStatusView): string[] {\n const { state, reviewerName } = view;\n switch (state.phase) {\n case 'queued':\n return [\n '### ⏳ Review queued',\n '',\n `${reviewerName} accepted the review request. The review has not started yet; this comment updates when it does.`,\n ];\n case 'retrying':\n return [\n '### ⏳ Review queued for retry',\n '',\n `The last attempt did not finish${view.reason ? `: ${inlineCode(view.reason)}` : '.'}`,\n `${reviewerName} retries automatically; this comment updates when the next attempt starts.`,\n ];\n case 'reviewing': {\n const since = state.startedAt ? ` since ${state.startedAt.replace(/\\.\\d+Z$/, 'Z')}` : '';\n const head = state.head ? ` on \\`${shortSha(state.head)}\\`` : '';\n return [\n '### Reviewing…',\n '',\n ...animation(view),\n '',\n `${reviewerName} is reviewing this pull request${head}${since}. This comment updates when the review finishes.`,\n ];\n }\n case 'completed':\n return [\n finalHeading(view),\n ...(view.stats?.verdict ? [] : ['', 'The review run ended without recording a verdict for this pass.']),\n ...footer(view),\n ];\n case 'failed':\n return [\n finalHeading(view),\n '',\n `The review did not finish${view.reason ? `: ${inlineCode(view.reason)}` : '.'}`,\n '',\n `Request a review from ${reviewerName} again to retry.`,\n ...footer(view),\n ];\n case 'cancelled':\n return [\n finalHeading(view),\n '',\n 'This review pass was replaced before it finished, either by a newer review request or because the pull request moved on.',\n ...footer(view),\n ];\n }\n}\n\n/** The whole comment body for one lifecycle step: the hidden markers, then the status inside a GitHub alert. */\nexport function renderReviewStatusComment(view: ReviewStatusView): string {\n const quoted = statusLines(view).map(line => (line ? `> ${line}` : '>'));\n return `${[REVIEW_STATUS_COMMENT_MARKER, stateLine(view.state), `> [!${alertType(view)}]`, ...quoted].join('\\n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AO,UAAU,CAAC,IAAI,CAAC,IAAI,iEAAiE;GACrG,GAAG,OAAO,IAAI;EAChB;EACF,KAAK,UACH,OAAO;GACL,aAAa,IAAI;GACjB;GACA,4BAA4B,KAAK,SAAS,KAAK,WAAW,KAAK,MAAM,MAAM;GAC3E;GACA,yBAAyB,aAAa;GACtC,GAAG,OAAO,IAAI;EAChB;EACF,KAAK,aACH,OAAO;GACL,aAAa,IAAI;GACjB;GACA;GACA,GAAG,OAAO,IAAI;EAChB;CACJ;AACF;;AAGA,SAAgB,0BAA0B,MAAgC;CACxE,MAAM,SAAS,YAAY,IAAI,CAAC,CAAC,KAAI,SAAS,OAAO,KAAK,SAAS,GAAI;CACvE,OAAO,GAAG;EAAC;EAA8B,UAAU,KAAK,KAAK;EAAG,OAAO,UAAU,IAAI,EAAE;EAAI,GAAG;CAAM,CAAC,CAAC,KAAK,IAAI,EAAE;AACnH"}
|
|
1
|
+
{"version":3,"file":"review-status-comment.js","names":[],"sources":["../../../src/integrations/github/review-status-comment.ts"],"sourcesContent":["/**\n * The one status comment Factory keeps on a pull request while it reviews it.\n * The host writes it from the review run's lifecycle, so a crashed or failed\n * run still resolves the comment instead of leaving it claiming work is live.\n *\n * The comment carries its own state in a hidden line. That state orders writes:\n * a newer review run takes the comment over, and a late write from an older run\n * (or an earlier step of the same run) is dropped instead of overwriting it.\n */\n\nexport const REVIEW_STATUS_COMMENT_MARKER = '<!-- mastra-factory-review-status -->';\nconst STATE_PREFIX = '<!-- mastra-factory-review-status:state ';\nconst STATE_SUFFIX = ' -->';\n\nexport type ReviewStatusPhase = 'queued' | 'reviewing' | 'retrying' | 'completed' | 'failed' | 'cancelled';\n\n/** What the hidden state line records; everything else in the comment is derived from it. */\nexport interface ReviewStatusState {\n /** The review run: the dispatcher decision that started it. Retries keep it. */\n run: string;\n /** When the run was requested; orders runs against each other. */\n requestedAt: string;\n /** The dispatcher delivery generation; grows on every retry, manual ones included. */\n generation: number;\n /** The dispatcher attempt, shown to readers. A manual retry restarts it. */\n attempt: number;\n phase: ReviewStatusPhase;\n /** When the agent was handed the review. Absent until the run starts. */\n startedAt?: string;\n /** The pull request head when the run started. */\n head?: string;\n /** The Factory UI link to the session running the review. Absent until the run starts. */\n session?: string;\n}\n\nexport interface ReviewStatusStats {\n verdict?: 'approve' | 'request changes';\n /** The commit the recorded verdict covers. */\n reviewedHeadSha?: string;\n durationMs?: number;\n}\n\nexport interface ReviewStatusView {\n state: ReviewStatusState;\n stats?: ReviewStatusStats;\n /** Why the run failed or will retry; already sanitized by the dispatcher. */\n reason?: string;\n reviewerName: string;\n /** `owner/name` of the pull request's repository, used to link the commit in the footer. */\n repository?: string;\n /** The animation shown while reviewing; also the fallback for readers without a theme preference. */\n gifUrl: string;\n /** The same animation drawn for GitHub's dark theme, swapped in with `prefers-color-scheme`. */\n gifDarkUrl?: string;\n}\n\nconst PHASE_RANK: Record<ReviewStatusPhase, number> = {\n queued: 0,\n reviewing: 1,\n retrying: 2,\n completed: 3,\n failed: 3,\n cancelled: 3,\n};\n\nconst SAFE_TOKEN = /^[A-Za-z0-9:._-]{1,200}$/;\nconst COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;\n\nfunction isPhase(value: unknown): value is ReviewStatusPhase {\n return typeof value === 'string' && value in PHASE_RANK;\n}\n\nfunction isTimestamp(value: unknown): value is string {\n return typeof value === 'string' && SAFE_TOKEN.test(value) && !Number.isNaN(Date.parse(value));\n}\n\nfunction isCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0;\n}\n\n/** Reads the hidden state line. Anything malformed reads as no state. */\nexport function parseReviewStatusState(body: string | null | undefined): ReviewStatusState | undefined {\n if (!body) return undefined;\n const start = body.indexOf(STATE_PREFIX);\n if (start < 0) return undefined;\n const end = body.indexOf(STATE_SUFFIX, start + STATE_PREFIX.length);\n if (end < 0) return undefined;\n let raw: unknown;\n try {\n raw = JSON.parse(body.slice(start + STATE_PREFIX.length, end));\n } catch {\n return undefined;\n }\n if (!raw || typeof raw !== 'object') return undefined;\n const value = raw as Record<string, unknown>;\n if (typeof value.run !== 'string' || !SAFE_TOKEN.test(value.run)) return undefined;\n if (!isTimestamp(value.requestedAt) || !isPhase(value.phase)) return undefined;\n if (!isCount(value.generation) || !isCount(value.attempt)) return undefined;\n return {\n run: value.run,\n requestedAt: value.requestedAt,\n generation: value.generation,\n attempt: value.attempt,\n phase: value.phase,\n ...(isTimestamp(value.startedAt) ? { startedAt: value.startedAt } : {}),\n ...(typeof value.head === 'string' && COMMIT_SHA.test(value.head) ? { head: value.head } : {}),\n ...(isSessionUrl(value.session) ? { session: value.session } : {}),\n };\n}\n\n/** An http(s) URL that is safe inside a markdown link target. */\nexport function isSessionUrl(value: unknown): value is string {\n if (typeof value !== 'string' || !/^https?:\\/\\/[^\\s()<>\"'`]+$/.test(value)) return false;\n try {\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Whether `next` may overwrite a comment holding `existing`. A different run\n * wins only when it was requested later. Within one run, steps only move\n * forward: a later delivery generation, or a later phase of the same one. So a\n * duplicate or late write never rewinds the comment, and a final status is only\n * replaced when the run is retried.\n */\nexport function supersedesReviewStatus(existing: ReviewStatusState | undefined, next: ReviewStatusState): boolean {\n if (!existing) return true;\n if (existing.run !== next.run) {\n const existingAt = Date.parse(existing.requestedAt);\n const nextAt = Date.parse(next.requestedAt);\n return nextAt > existingAt || (nextAt === existingAt && next.run > existing.run);\n }\n if (next.generation !== existing.generation) return next.generation > existing.generation;\n if (next.attempt !== existing.attempt) return next.attempt > existing.attempt;\n return PHASE_RANK[next.phase] > PHASE_RANK[existing.phase];\n}\n\nfunction shortSha(sha: string): string {\n return sha.slice(0, 7);\n}\n\nexport function formatDuration(ms: number): string {\n const totalSeconds = Math.max(0, Math.round(ms / 1000));\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n if (hours > 0) return `${hours}h ${minutes}m`;\n if (minutes > 0) return `${minutes}m ${seconds}s`;\n return `${seconds}s`;\n}\n\n/** Plain, single-line text that cannot break out of the code span it is rendered in. */\nfunction inlineCode(text: string, max = 300): string {\n const flat = text\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/`/g, \"'\")\n .trim();\n const clipped = flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n return `\\`${clipped}\\``;\n}\n\nfunction stateLine(state: ReviewStatusState): string {\n return `${STATE_PREFIX}${JSON.stringify(state)}${STATE_SUFFIX}`;\n}\n\nfunction finalHeading(view: ReviewStatusView): string {\n const { phase } = view.state;\n if (phase === 'failed') return '### ❌ Review failed';\n if (phase === 'cancelled') return '### ⏹️ Review cancelled';\n const verdict = view.stats?.verdict;\n if (verdict === 'approve') return '### ✅ Review complete: approved';\n if (verdict === 'request changes') return '### 🔁 Review complete: changes requested';\n return '### ☑️ Review finished';\n}\n\nconst REPOSITORY_SLUG = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction commitLink(sha: string, repository: string | undefined): string {\n const code = `\\`${shortSha(sha)}\\``;\n return repository && REPOSITORY_SLUG.test(repository)\n ? `[${code}](https://github.com/${repository}/commit/${sha})`\n : code;\n}\n\n/**\n * A quiet line under the status: the commit and how long a finished run took, and the link to\n * the session running the review once it has started. Only a recorded verdict's commit is called\n * reviewed; otherwise it is the head the run started on.\n */\nfunction footer(view: ReviewStatusView): string[] {\n const { stats = {}, state } = view;\n const parts: string[] = [];\n const final = state.phase === 'completed' || state.phase === 'failed' || state.phase === 'cancelled';\n if (final) {\n if (stats.reviewedHeadSha && stats.verdict && state.phase === 'completed')\n parts.push(`Reviewed ${commitLink(stats.reviewedHeadSha, view.repository)}`);\n else if (state.head) parts.push(`Started on ${commitLink(state.head, view.repository)}`);\n if (stats.durationMs !== undefined) parts.push(`took ${formatDuration(stats.durationMs)}`);\n }\n if (state.session) parts.push(`[Factory session](${state.session})`);\n if (parts.length === 0) return [];\n const line = parts.join(' · ');\n return ['', `<sub>${line.charAt(0).toUpperCase()}${line.slice(1)}</sub>`];\n}\n\nexport function gifAltText(reviewerName: string): string {\n return `Animated ASCII factory with smoke puffing from its chimneys: ${reviewerName} is reviewing this pull request`;\n}\n\nfunction htmlAttribute(value: string): string {\n return value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');\n}\n\n/** Display width for the 468px-wide animation; GitHub keeps the aspect ratio when only the width is set. */\nconst ANIMATION_WIDTH = 360;\n\n/** The reviewing animation, matched to the reader's GitHub theme when a dark variant is configured. */\nfunction animation(view: ReviewStatusView): string[] {\n const img = `<img src=\"${htmlAttribute(view.gifUrl)}\" alt=\"${htmlAttribute(gifAltText(view.reviewerName))}\" width=\"${ANIMATION_WIDTH}\">`;\n if (!view.gifDarkUrl) return [img];\n return [\n '<picture>',\n ` <source media=\"(prefers-color-scheme: dark)\" srcset=\"${htmlAttribute(view.gifDarkUrl)}\">`,\n ` <source media=\"(prefers-color-scheme: light)\" srcset=\"${htmlAttribute(view.gifUrl)}\">`,\n ` ${img}`,\n '</picture>',\n ];\n}\n\ntype AlertType = 'NOTE' | 'TIP' | 'IMPORTANT' | 'WARNING' | 'CAUTION';\n\n/** The GitHub alert that colors each status: blue while waiting or running, green for approval, purple for a result to act on, yellow for a retry or cancellation, red for a failure. */\nfunction alertType(view: ReviewStatusView): AlertType {\n switch (view.state.phase) {\n case 'queued':\n case 'reviewing':\n return 'NOTE';\n case 'retrying':\n case 'cancelled':\n return 'WARNING';\n case 'failed':\n return 'CAUTION';\n case 'completed':\n return view.stats?.verdict === 'approve' ? 'TIP' : 'IMPORTANT';\n }\n}\n\n/** The status content for one lifecycle step, before it is wrapped in its alert. */\nfunction statusLines(view: ReviewStatusView): string[] {\n const { state, reviewerName } = view;\n switch (state.phase) {\n case 'queued':\n return [\n '### ⏳ Review queued',\n '',\n `${reviewerName} accepted the review request. The review has not started yet; this comment updates when it does.`,\n ];\n case 'retrying':\n return [\n '### ⏳ Review queued for retry',\n '',\n `The last attempt did not finish${view.reason ? `: ${inlineCode(view.reason)}` : '.'}`,\n `${reviewerName} retries automatically; this comment updates when the next attempt starts.`,\n ];\n case 'reviewing': {\n const since = state.startedAt ? ` since ${state.startedAt.replace(/\\.\\d+Z$/, 'Z')}` : '';\n const head = state.head ? ` on \\`${shortSha(state.head)}\\`` : '';\n return [\n '### Reviewing…',\n '',\n ...animation(view),\n '',\n `${reviewerName} is reviewing this pull request${head}${since}. This comment updates when the review finishes.`,\n ...footer(view),\n ];\n }\n case 'completed':\n return [\n finalHeading(view),\n ...(view.stats?.verdict ? [] : ['', 'The review run ended without recording a verdict for this pass.']),\n ...footer(view),\n ];\n case 'failed':\n return [\n finalHeading(view),\n '',\n `The review did not finish${view.reason ? `: ${inlineCode(view.reason)}` : '.'}`,\n '',\n `Request a review from ${reviewerName} again to retry.`,\n ...footer(view),\n ];\n case 'cancelled':\n return [\n finalHeading(view),\n '',\n 'This review pass was replaced before it finished, either by a newer review request or because the pull request moved on.',\n ...footer(view),\n ];\n }\n}\n\n/** The whole comment body for one lifecycle step: the hidden markers, then the status inside a GitHub alert. */\nexport function renderReviewStatusComment(view: ReviewStatusView): string {\n const quoted = statusLines(view).map(line => (line ? `> ${line}` : '>'));\n return `${[REVIEW_STATUS_COMMENT_MARKER, stateLine(view.state), `> [!${alertType(view)}]`, ...quoted].join('\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,+BAA+B;AAC5C,MAAM,eAAe;AACrB,MAAM,eAAe;AA4CrB,MAAM,aAAgD;CACpD,QAAQ;CACR,WAAW;CACX,UAAU;CACV,WAAW;CACX,QAAQ;CACR,WAAW;AACb;AAEA,MAAM,aAAa;AACnB,MAAM,aAAa;AAEnB,SAAS,QAAQ,OAA4C;CAC3D,OAAO,OAAO,UAAU,YAAY,SAAS;AAC/C;AAEA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,WAAW,KAAK,KAAK,KAAK,CAA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aAAa,IAAI;GACjB,GAAI,KAAK,OAAO,UAAU,CAAC,IAAI,CAAC,IAAI,iEAAiE;GACrG,GAAG,OAAO,IAAI;EAChB;EACF,KAAK,UACH,OAAO;GACL,aAAa,IAAI;GACjB;GACA,4BAA4B,KAAK,SAAS,KAAK,WAAW,KAAK,MAAM,MAAM;GAC3E;GACA,yBAAyB,aAAa;GACtC,GAAG,OAAO,IAAI;EAChB;EACF,KAAK,aACH,OAAO;GACL,aAAa,IAAI;GACjB;GACA;GACA,GAAG,OAAO,IAAI;EAChB;CACJ;AACF;;AAGA,SAAgB,0BAA0B,MAAgC;CACxE,MAAM,SAAS,YAAY,IAAI,CAAC,CAAC,KAAI,SAAS,OAAO,KAAK,SAAS,GAAI;CACvE,OAAO,GAAG;EAAC;EAA8B,UAAU,KAAK,KAAK;EAAG,OAAO,UAAU,IAAI,EAAE;EAAI,GAAG;CAAM,CAAC,CAAC,KAAK,IAAI,EAAE;AACnH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status-reporter.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/review-status-reporter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,uCAAuC,CAAC;
|
|
1
|
+
{"version":3,"file":"review-status-reporter.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/review-status-reporter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,uCAAuC,CAAC;AAE5F,OAAO,KAAK,EAA4B,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACvG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAC/F,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0CAA0C,CAAC;AAQrE,eAAO,MAAM,6BAA6B,wHAAgD,CAAC;AAC3F,eAAO,MAAM,kCAAkC,uHAA+C,CAAC;AAE/F;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG;IACrF,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAKA;AAID,MAAM,WAAW,8BAA8B;IAC7C,MAAM,EAAE;QACN,cAAc,EAAE,cAAc,CAAC;QAC/B,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC;KACnE,CAAC;IACF,aAAa,EAAE,0BAA0B,CAAC;IAC1C,SAAS,EAAE;QAAE,GAAG,CAAC,KAAK,EAAE;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,CAAA;KAAE,CAAC;IAC/E,2DAA2D;IAC3D,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAMD;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAAC,IAAI,EAAE,8BAA8B,GAAG,2BAA2B,CAqDlH"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { pullRequestSourceNumber, reviewedPullRequest } from "../../work-items/change-requests.js";
|
|
2
2
|
import "../../boards/index.js";
|
|
3
|
+
import { factorySessionUrl } from "../../links.js";
|
|
3
4
|
import { resolveRepository } from "./acceptance-labels.js";
|
|
5
|
+
import { isSessionUrl } from "./review-status-comment.js";
|
|
4
6
|
import { publishReviewStatus } from "./review-status.js";
|
|
5
7
|
// src/integrations/github/review-status-reporter.ts
|
|
6
8
|
const REVIEW_STATUS_ASSETS = "https://raw.githubusercontent.com/mastra-ai/mastra/main/mastracode/factory/assets/review-status";
|
|
@@ -60,6 +62,10 @@ function createGithubReviewStatusReporter(deps) {
|
|
|
60
62
|
pullRequestId: String(number)
|
|
61
63
|
};
|
|
62
64
|
const head = event.phase === "reviewing" ? commitSha(item.metadata?.pullRequestHeadSha) : void 0;
|
|
65
|
+
const session = event.session ? factorySessionUrl({
|
|
66
|
+
factoryProjectId: event.factoryProjectId,
|
|
67
|
+
...event.session
|
|
68
|
+
}) : void 0;
|
|
63
69
|
const state = {
|
|
64
70
|
run: event.run,
|
|
65
71
|
requestedAt: event.requestedAt.toISOString(),
|
|
@@ -67,7 +73,8 @@ function createGithubReviewStatusReporter(deps) {
|
|
|
67
73
|
attempt: event.attempt,
|
|
68
74
|
phase: event.phase,
|
|
69
75
|
...event.startedAt ? { startedAt: event.startedAt.toISOString() } : {},
|
|
70
|
-
...head ? { head } : {}
|
|
76
|
+
...head ? { head } : {},
|
|
77
|
+
...isSessionUrl(session) ? { session } : {}
|
|
71
78
|
};
|
|
72
79
|
const final = event.phase === "completed" || event.phase === "failed" || event.phase === "cancelled";
|
|
73
80
|
await publishReviewStatus(deps.github.versionControl, ref, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status-reporter.js","names":[],"sources":["../../../src/integrations/github/review-status-reporter.ts"],"sourcesContent":["import { pullRequestSourceNumber, reviewedPullRequest } from '../../boards/index.js';\nimport type { PullRequestRef, VersionControl } from '../../capabilities/version-control.js';\nimport type { FactoryReviewStatusEvent, FactoryReviewStatusReporter } from '../../rules/dispatcher.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { Card } from '../../storage/domains/work-items/base.js';\nimport { resolveRepository } from './acceptance-labels.js';\nimport type { ReviewStatusState, ReviewStatusStats } from './review-status-comment.js';\nimport { publishReviewStatus } from './review-status.js';\n\nconst REVIEW_STATUS_ASSETS =\n 'https://raw.githubusercontent.com/mastra-ai/mastra/main/mastracode/factory/assets/review-status';\nexport const DEFAULT_REVIEW_STATUS_GIF_URL = `${REVIEW_STATUS_ASSETS}/reviewing-light.gif`;\nexport const DEFAULT_REVIEW_STATUS_GIF_DARK_URL = `${REVIEW_STATUS_ASSETS}/reviewing-dark.gif`;\n\n/**\n * Where the reviewing animation is served from. By default both theme variants\n * come from this repository. A self-hosted `FACTORY_REVIEW_STATUS_GIF_URL` is\n * used for every theme unless `FACTORY_REVIEW_STATUS_GIF_DARK_URL` adds a dark\n * variant for it; a custom image is never paired with a stock one.\n */\nexport function reviewStatusAnimationFromEnv(env: Record<string, string | undefined>): {\n gifUrl: string;\n gifDarkUrl?: string;\n} {\n const gifUrl = env.FACTORY_REVIEW_STATUS_GIF_URL?.trim();\n const gifDarkUrl = env.FACTORY_REVIEW_STATUS_GIF_DARK_URL?.trim();\n if (!gifUrl) return { gifUrl: DEFAULT_REVIEW_STATUS_GIF_URL, gifDarkUrl: DEFAULT_REVIEW_STATUS_GIF_DARK_URL };\n return gifDarkUrl ? { gifUrl, gifDarkUrl } : { gifUrl };\n}\n\nconst COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;\n\nexport interface GithubReviewStatusReporterDeps {\n github: {\n versionControl: VersionControl;\n isFactoryCommentAuthor(login: string | null | undefined): boolean;\n };\n sourceControl: SourceControlStorageHandle;\n workItems: { get(input: { orgId: string; id: string }): Promise<Card | null> };\n /** How the comment names the reviewer, e.g. \"Shipyard\". */\n reviewerName: string;\n gifUrl: string;\n gifDarkUrl?: string;\n}\n\nfunction commitSha(value: unknown): string | undefined {\n return typeof value === 'string' && COMMIT_SHA.test(value.toLowerCase()) ? value.toLowerCase() : undefined;\n}\n\n/**\n * Keeps the review-status comment on a GitHub pull request in step with the\n * dispatcher's review runs. Every number it shows is read, not estimated:\n * duration from the dispatcher's own clock, the verdict and commit only when\n * this run recorded them, inline comments counted on GitHub. Anything it cannot\n * read is left out. Never throws.\n */\nexport function createGithubReviewStatusReporter(deps: GithubReviewStatusReporterDeps): FactoryReviewStatusReporter {\n const isFactoryAuthor = (login: string | null | undefined) => deps.github.isFactoryCommentAuthor(login);\n return async event => {\n try {\n const item = await deps.workItems.get({ orgId: event.orgId, id: event.workItemId });\n if (!item || item.externalSource?.integrationId !== 'github') return;\n // An issue card reviews the pull request attached to it.\n const attached = item.externalSource.type === 'pull-request' ? undefined : reviewedPullRequest(item);\n if (item.externalSource.type !== 'pull-request' && attached?.integrationId !== 'github') return;\n const repositoryId = attached?.metadata?.githubRepositoryId ?? item.workItem.metadata?.githubRepositoryId;\n const number = attached ? pullRequestSourceNumber(attached) : item.workItem.metadata?.githubPullRequestNumber;\n if (typeof repositoryId !== 'number' || typeof number !== 'number' || number < 1) return;\n const target = await resolveRepository(deps.sourceControl, event.orgId, event.factoryProjectId, repositoryId);\n if (!target) return;\n const ref: PullRequestRef = {\n connection: { type: 'app-installation', installationId: target.installationId },\n sourceId: target.slug,\n pullRequestId: String(number),\n };\n const head = event.phase === 'reviewing' ? commitSha(item.metadata?.pullRequestHeadSha) : undefined;\n const state: ReviewStatusState = {\n run: event.run,\n requestedAt: event.requestedAt.toISOString(),\n generation: event.generation,\n attempt: event.attempt,\n phase: event.phase,\n ...(event.startedAt ? { startedAt: event.startedAt.toISOString() } : {}),\n ...(head ? { head } : {}),\n };\n const final = event.phase === 'completed' || event.phase === 'failed' || event.phase === 'cancelled';\n await publishReviewStatus(\n deps.github.versionControl,\n ref,\n {\n state,\n reviewerName: deps.reviewerName,\n repository: target.slug,\n gifUrl: deps.gifUrl,\n ...(deps.gifDarkUrl ? { gifDarkUrl: deps.gifDarkUrl } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.replayed ? { continuesRun: true } : {}),\n ...(final ? { stats: recorded => readStats(item, event, recorded) } : {}),\n },\n isFactoryAuthor,\n );\n } catch (error) {\n console.warn(`[factory] could not update the review status for work item ${event.workItemId}:`, error);\n }\n };\n}\n\nasync function readStats(\n item: Card,\n event: FactoryReviewStatusEvent,\n state: ReviewStatusState,\n): Promise<ReviewStatusStats> {\n // A run that never started reviewed nothing: no duration or verdict to show.\n if (!state.startedAt) return {};\n const startedAt = Date.parse(state.startedAt);\n const stats: ReviewStatusStats = {};\n if (event.endedAt) stats.durationMs = Math.max(0, event.endedAt.getTime() - startedAt);\n // The card keeps the latest verdict; it is this run's only if recorded after the run started.\n const verdict = item.metadata?.reviewVerdict;\n const reviewedAt = item.metadata?.reviewedAt;\n if (\n event.phase === 'completed' &&\n (verdict === 'approve' || verdict === 'request changes') &&\n typeof reviewedAt === 'string' &&\n Date.parse(reviewedAt) >= startedAt\n ) {\n stats.verdict = verdict;\n const reviewedHeadSha = commitSha(item.metadata?.reviewedHeadSha);\n if (reviewedHeadSha) stats.reviewedHeadSha = reviewedHeadSha;\n }\n return stats;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"review-status-reporter.js","names":[],"sources":["../../../src/integrations/github/review-status-reporter.ts"],"sourcesContent":["import { pullRequestSourceNumber, reviewedPullRequest } from '../../boards/index.js';\nimport type { PullRequestRef, VersionControl } from '../../capabilities/version-control.js';\nimport { factorySessionUrl } from '../../links.js';\nimport type { FactoryReviewStatusEvent, FactoryReviewStatusReporter } from '../../rules/dispatcher.js';\nimport type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';\nimport type { Card } from '../../storage/domains/work-items/base.js';\nimport { resolveRepository } from './acceptance-labels.js';\nimport { isSessionUrl } from './review-status-comment.js';\nimport type { ReviewStatusState, ReviewStatusStats } from './review-status-comment.js';\nimport { publishReviewStatus } from './review-status.js';\n\nconst REVIEW_STATUS_ASSETS =\n 'https://raw.githubusercontent.com/mastra-ai/mastra/main/mastracode/factory/assets/review-status';\nexport const DEFAULT_REVIEW_STATUS_GIF_URL = `${REVIEW_STATUS_ASSETS}/reviewing-light.gif`;\nexport const DEFAULT_REVIEW_STATUS_GIF_DARK_URL = `${REVIEW_STATUS_ASSETS}/reviewing-dark.gif`;\n\n/**\n * Where the reviewing animation is served from. By default both theme variants\n * come from this repository. A self-hosted `FACTORY_REVIEW_STATUS_GIF_URL` is\n * used for every theme unless `FACTORY_REVIEW_STATUS_GIF_DARK_URL` adds a dark\n * variant for it; a custom image is never paired with a stock one.\n */\nexport function reviewStatusAnimationFromEnv(env: Record<string, string | undefined>): {\n gifUrl: string;\n gifDarkUrl?: string;\n} {\n const gifUrl = env.FACTORY_REVIEW_STATUS_GIF_URL?.trim();\n const gifDarkUrl = env.FACTORY_REVIEW_STATUS_GIF_DARK_URL?.trim();\n if (!gifUrl) return { gifUrl: DEFAULT_REVIEW_STATUS_GIF_URL, gifDarkUrl: DEFAULT_REVIEW_STATUS_GIF_DARK_URL };\n return gifDarkUrl ? { gifUrl, gifDarkUrl } : { gifUrl };\n}\n\nconst COMMIT_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;\n\nexport interface GithubReviewStatusReporterDeps {\n github: {\n versionControl: VersionControl;\n isFactoryCommentAuthor(login: string | null | undefined): boolean;\n };\n sourceControl: SourceControlStorageHandle;\n workItems: { get(input: { orgId: string; id: string }): Promise<Card | null> };\n /** How the comment names the reviewer, e.g. \"Shipyard\". */\n reviewerName: string;\n gifUrl: string;\n gifDarkUrl?: string;\n}\n\nfunction commitSha(value: unknown): string | undefined {\n return typeof value === 'string' && COMMIT_SHA.test(value.toLowerCase()) ? value.toLowerCase() : undefined;\n}\n\n/**\n * Keeps the review-status comment on a GitHub pull request in step with the\n * dispatcher's review runs. Every number it shows is read, not estimated:\n * duration from the dispatcher's own clock, the verdict and commit only when\n * this run recorded them, inline comments counted on GitHub. Anything it cannot\n * read is left out. Never throws.\n */\nexport function createGithubReviewStatusReporter(deps: GithubReviewStatusReporterDeps): FactoryReviewStatusReporter {\n const isFactoryAuthor = (login: string | null | undefined) => deps.github.isFactoryCommentAuthor(login);\n return async event => {\n try {\n const item = await deps.workItems.get({ orgId: event.orgId, id: event.workItemId });\n if (!item || item.externalSource?.integrationId !== 'github') return;\n // An issue card reviews the pull request attached to it.\n const attached = item.externalSource.type === 'pull-request' ? undefined : reviewedPullRequest(item);\n if (item.externalSource.type !== 'pull-request' && attached?.integrationId !== 'github') return;\n const repositoryId = attached?.metadata?.githubRepositoryId ?? item.workItem.metadata?.githubRepositoryId;\n const number = attached ? pullRequestSourceNumber(attached) : item.workItem.metadata?.githubPullRequestNumber;\n if (typeof repositoryId !== 'number' || typeof number !== 'number' || number < 1) return;\n const target = await resolveRepository(deps.sourceControl, event.orgId, event.factoryProjectId, repositoryId);\n if (!target) return;\n const ref: PullRequestRef = {\n connection: { type: 'app-installation', installationId: target.installationId },\n sourceId: target.slug,\n pullRequestId: String(number),\n };\n const head = event.phase === 'reviewing' ? commitSha(item.metadata?.pullRequestHeadSha) : undefined;\n const session = event.session\n ? factorySessionUrl({ factoryProjectId: event.factoryProjectId, ...event.session })\n : undefined;\n const state: ReviewStatusState = {\n run: event.run,\n requestedAt: event.requestedAt.toISOString(),\n generation: event.generation,\n attempt: event.attempt,\n phase: event.phase,\n ...(event.startedAt ? { startedAt: event.startedAt.toISOString() } : {}),\n ...(head ? { head } : {}),\n ...(isSessionUrl(session) ? { session } : {}),\n };\n const final = event.phase === 'completed' || event.phase === 'failed' || event.phase === 'cancelled';\n await publishReviewStatus(\n deps.github.versionControl,\n ref,\n {\n state,\n reviewerName: deps.reviewerName,\n repository: target.slug,\n gifUrl: deps.gifUrl,\n ...(deps.gifDarkUrl ? { gifDarkUrl: deps.gifDarkUrl } : {}),\n ...(event.reason ? { reason: event.reason } : {}),\n ...(event.replayed ? { continuesRun: true } : {}),\n ...(final ? { stats: recorded => readStats(item, event, recorded) } : {}),\n },\n isFactoryAuthor,\n );\n } catch (error) {\n console.warn(`[factory] could not update the review status for work item ${event.workItemId}:`, error);\n }\n };\n}\n\nasync function readStats(\n item: Card,\n event: FactoryReviewStatusEvent,\n state: ReviewStatusState,\n): Promise<ReviewStatusStats> {\n // A run that never started reviewed nothing: no duration or verdict to show.\n if (!state.startedAt) return {};\n const startedAt = Date.parse(state.startedAt);\n const stats: ReviewStatusStats = {};\n if (event.endedAt) stats.durationMs = Math.max(0, event.endedAt.getTime() - startedAt);\n // The card keeps the latest verdict; it is this run's only if recorded after the run started.\n const verdict = item.metadata?.reviewVerdict;\n const reviewedAt = item.metadata?.reviewedAt;\n if (\n event.phase === 'completed' &&\n (verdict === 'approve' || verdict === 'request changes') &&\n typeof reviewedAt === 'string' &&\n Date.parse(reviewedAt) >= startedAt\n ) {\n stats.verdict = verdict;\n const reviewedHeadSha = commitSha(item.metadata?.reviewedHeadSha);\n if (reviewedHeadSha) stats.reviewedHeadSha = reviewedHeadSha;\n }\n return stats;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,uBACJ;AACF,MAAa,gCAAgC,GAAG,qBAAqB;AACrE,MAAa,qCAAqC,GAAG,qBAAqB;;;;;;;AAQ1E,SAAgB,6BAA6B,KAG3C;CACA,MAAM,SAAS,IAAI,+BAA+B,KAAK;CACvD,MAAM,aAAa,IAAI,oCAAoC,KAAK;CAChE,IAAI,CAAC,QAAQ,OAAO;EAAE,QAAQ;EAA+B,YAAY;CAAmC;CAC5G,OAAO,aAAa;EAAE;EAAQ;CAAW,IAAI,EAAE,OAAO;AACxD;AAEA,MAAM,aAAa;AAenB,SAAS,UAAU,OAAoC;CACrD,OAAO,OAAO,UAAU,YAAY,WAAW,KAAK,MAAM,YAAY,CAAC,IAAI,MAAM,YAAY,IAAI,KAAA;AACnG;;;;;;;;AASA,SAAgB,iCAAiC,MAAmE;CAClH,MAAM,mBAAmB,UAAqC,KAAK,OAAO,uBAAuB,KAAK;CACtG,OAAO,OAAM,UAAS;EACpB,IAAI;GACF,MAAM,OAAO,MAAM,KAAK,UAAU,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,MAAM;GAAW,CAAC;GAClF,IAAI,CAAC,QAAQ,KAAK,gBAAgB,kBAAkB,UAAU;GAE9D,MAAM,WAAW,KAAK,eAAe,SAAS,iBAAiB,KAAA,IAAY,oBAAoB,IAAI;GACnG,IAAI,KAAK,eAAe,SAAS,kBAAkB,UAAU,kBAAkB,UAAU;GACzF,MAAM,eAAe,UAAU,UAAU,sBAAsB,KAAK,SAAS,UAAU;GACvF,MAAM,SAAS,WAAW,wBAAwB,QAAQ,IAAI,KAAK,SAAS,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QAAQ,KAAK,8DAA8D,MAAM,WAAW,IAAI,KAAK;EACvG;CACF;AACF;AAEA,eAAe,UACb,MACA,OACA,OAC4B;CAE5B,IAAI,CAAC,MAAM,WAAW,OAAO,CAAC;CAC9B,MAAM,YAAY,KAAK,MAAM,MAAM,SAAS;CAC5C,MAAM,QAA2B,CAAC;CAClC,IAAI,MAAM,SAAS,MAAM,aAAa,KAAK,IAAI,GAAG,MAAM,QAAQ,QAAQ,IAAI,SAAS;CAErF,MAAM,UAAU,KAAK,UAAU;CAC/B,MAAM,aAAa,KAAK,UAAU;CAClC,IACE,MAAM,UAAU,gBACf,YAAY,aAAa,YAAY,sBACtC,OAAO,eAAe,YACtB,KAAK,MAAM,UAAU,KAAK,WAC1B;EACA,MAAM,UAAU;EAChB,MAAM,kBAAkB,UAAU,KAAK,UAAU,eAAe;EAChE,IAAI,iBAAiB,MAAM,kBAAkB;CAC/C;CACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/review-status.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAsB,cAAc,EAAE,cAAc,EAAE,MAAM,uCAAuC,CAAC;AAOhH,OAAO,KAAK,EAEV,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EACjB,MAAM,4BAA4B,CAAC;AAEpC,KAAK,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,cAAc,GAAG,eAAe,GAAG,eAAe,GAAG,eAAe,CAAC,CAAC;AAE9G,MAAM,MAAM,yBAAyB,GACjC;IAAE,MAAM,EAAE,SAAS,GAAG,SAAS,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACjE;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,CAAC;AAK1B,MAAM,WAAW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IACjE,kGAAkG;IAClG,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB;AAoBD;;;;;GAKG;AACH,wBAAsB,mBAAmB,CACvC,cAAc,EAAE,WAAW,EAC3B,GAAG,EAAE,cAAc,EACnB,IAAI,EAAE,gBAAgB,EACtB,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,KAAK,OAAO,GAC7D,OAAO,CAAC,yBAAyB,CAAC,CA0DpC"}
|
|
@@ -57,7 +57,8 @@ async function publishReviewStatus(versionControl, ref, step, isFactoryAuthor) {
|
|
|
57
57
|
const state = existing?.run === step.state.run && (existing.attempt === step.state.attempt || step.continuesRun === true) && !FRESH_ATTEMPT_PHASES.has(step.state.phase) ? {
|
|
58
58
|
...step.state,
|
|
59
59
|
...step.state.startedAt ?? existing.startedAt ? { startedAt: step.state.startedAt ?? existing.startedAt } : {},
|
|
60
|
-
...step.state.head ?? existing.head ? { head: step.state.head ?? existing.head } : {}
|
|
60
|
+
...step.state.head ?? existing.head ? { head: step.state.head ?? existing.head } : {},
|
|
61
|
+
...step.state.session ?? existing.session ? { session: step.state.session ?? existing.session } : {}
|
|
61
62
|
} : step.state;
|
|
62
63
|
if (!CREATING_PHASES.has(state.phase) && existing?.run !== state.run) return { action: "skipped" };
|
|
63
64
|
const { stats: readStats, continuesRun: _continuesRun, ...view } = step;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"review-status.js","names":[],"sources":["../../../src/integrations/github/review-status.ts"],"sourcesContent":["import type { PullRequestComment, PullRequestRef, VersionControl } from '../../capabilities/version-control.js';\nimport {\n parseReviewStatusState,\n renderReviewStatusComment,\n REVIEW_STATUS_COMMENT_MARKER,\n supersedesReviewStatus,\n} from './review-status-comment.js';\nimport type {\n ReviewStatusPhase,\n ReviewStatusState,\n ReviewStatusStats,\n ReviewStatusView,\n} from './review-status-comment.js';\n\ntype CommentPort = Pick<VersionControl, 'listComments' | 'createComment' | 'updateComment' | 'deleteComment'>;\n\nexport type ReviewStatusPublishResult =\n | { action: 'created' | 'updated'; commentId: string; url: string }\n | { action: 'stale'; commentId: string }\n | { action: 'skipped' };\n\nconst CREATING_PHASES = new Set<ReviewStatusPhase>(['queued', 'reviewing', 'retrying', 'failed']);\nconst FRESH_ATTEMPT_PHASES = new Set<ReviewStatusPhase>(['queued', 'retrying']);\n\nexport interface ReviewStatusStep extends Omit<ReviewStatusView, 'stats'> {\n /** Stats for a final step, read once the start time and head of the run are known. */\n stats?: (state: ReviewStatusState) => Promise<ReviewStatusStats>;\n /** Ends the run an earlier attempt started, so that attempt's start time and head still apply. */\n continuesRun?: boolean;\n}\n\nasync function listAll<T>(page: (cursor?: string) => Promise<{ items: T[]; nextCursor: string | null }>): Promise<T[]> {\n const items: T[] = [];\n let cursor: string | undefined;\n do {\n const next = await page(cursor);\n items.push(...next.items);\n cursor = next.nextCursor ?? undefined;\n } while (cursor);\n return items;\n}\n\nfunction byId(left: PullRequestComment, right: PullRequestComment): number {\n const a = Number(left.id);\n const b = Number(right.id);\n if (Number.isFinite(a) && Number.isFinite(b)) return a - b;\n return left.id.localeCompare(right.id);\n}\n\n/**\n * Writes one lifecycle step into the pull request's Factory review-status\n * comment: edits the oldest one Factory authored, or creates it. A step older\n * than what the comment already shows is dropped. Extra marked comments left by\n * a creation race are deleted so the pull request settles on one.\n */\nexport async function publishReviewStatus(\n versionControl: CommentPort,\n ref: PullRequestRef,\n step: ReviewStatusStep,\n isFactoryAuthor: (login: string | null | undefined) => boolean,\n): Promise<ReviewStatusPublishResult> {\n const comments = await listAll(async cursor => {\n const page = await versionControl.listComments({ ...ref, ...(cursor ? { cursor } : {}) });\n return { items: page.comments, nextCursor: page.nextCursor };\n });\n const marked = comments\n .filter(comment => comment.body.includes(REVIEW_STATUS_COMMENT_MARKER) && isFactoryAuthor(comment.author))\n .sort(byId);\n const [canonical, ...duplicates] = marked;\n for (const duplicate of duplicates) {\n try {\n await versionControl.deleteComment({\n connection: ref.connection,\n sourceId: ref.sourceId,\n commentId: duplicate.id,\n });\n } catch (error) {\n console.warn(`[factory] could not delete duplicate review-status comment ${duplicate.id}:`, error);\n }\n }\n const existing = canonical ? parseReviewStatusState(canonical.body) : undefined;\n if (canonical && !supersedesReviewStatus(existing, step.state)) {\n return { action: 'stale', commentId: canonical.id };\n }\n // Later steps of an attempt carry only what changed; the start time and
|
|
1
|
+
{"version":3,"file":"review-status.js","names":[],"sources":["../../../src/integrations/github/review-status.ts"],"sourcesContent":["import type { PullRequestComment, PullRequestRef, VersionControl } from '../../capabilities/version-control.js';\nimport {\n parseReviewStatusState,\n renderReviewStatusComment,\n REVIEW_STATUS_COMMENT_MARKER,\n supersedesReviewStatus,\n} from './review-status-comment.js';\nimport type {\n ReviewStatusPhase,\n ReviewStatusState,\n ReviewStatusStats,\n ReviewStatusView,\n} from './review-status-comment.js';\n\ntype CommentPort = Pick<VersionControl, 'listComments' | 'createComment' | 'updateComment' | 'deleteComment'>;\n\nexport type ReviewStatusPublishResult =\n | { action: 'created' | 'updated'; commentId: string; url: string }\n | { action: 'stale'; commentId: string }\n | { action: 'skipped' };\n\nconst CREATING_PHASES = new Set<ReviewStatusPhase>(['queued', 'reviewing', 'retrying', 'failed']);\nconst FRESH_ATTEMPT_PHASES = new Set<ReviewStatusPhase>(['queued', 'retrying']);\n\nexport interface ReviewStatusStep extends Omit<ReviewStatusView, 'stats'> {\n /** Stats for a final step, read once the start time and head of the run are known. */\n stats?: (state: ReviewStatusState) => Promise<ReviewStatusStats>;\n /** Ends the run an earlier attempt started, so that attempt's start time and head still apply. */\n continuesRun?: boolean;\n}\n\nasync function listAll<T>(page: (cursor?: string) => Promise<{ items: T[]; nextCursor: string | null }>): Promise<T[]> {\n const items: T[] = [];\n let cursor: string | undefined;\n do {\n const next = await page(cursor);\n items.push(...next.items);\n cursor = next.nextCursor ?? undefined;\n } while (cursor);\n return items;\n}\n\nfunction byId(left: PullRequestComment, right: PullRequestComment): number {\n const a = Number(left.id);\n const b = Number(right.id);\n if (Number.isFinite(a) && Number.isFinite(b)) return a - b;\n return left.id.localeCompare(right.id);\n}\n\n/**\n * Writes one lifecycle step into the pull request's Factory review-status\n * comment: edits the oldest one Factory authored, or creates it. A step older\n * than what the comment already shows is dropped. Extra marked comments left by\n * a creation race are deleted so the pull request settles on one.\n */\nexport async function publishReviewStatus(\n versionControl: CommentPort,\n ref: PullRequestRef,\n step: ReviewStatusStep,\n isFactoryAuthor: (login: string | null | undefined) => boolean,\n): Promise<ReviewStatusPublishResult> {\n const comments = await listAll(async cursor => {\n const page = await versionControl.listComments({ ...ref, ...(cursor ? { cursor } : {}) });\n return { items: page.comments, nextCursor: page.nextCursor };\n });\n const marked = comments\n .filter(comment => comment.body.includes(REVIEW_STATUS_COMMENT_MARKER) && isFactoryAuthor(comment.author))\n .sort(byId);\n const [canonical, ...duplicates] = marked;\n for (const duplicate of duplicates) {\n try {\n await versionControl.deleteComment({\n connection: ref.connection,\n sourceId: ref.sourceId,\n commentId: duplicate.id,\n });\n } catch (error) {\n console.warn(`[factory] could not delete duplicate review-status comment ${duplicate.id}:`, error);\n }\n }\n const existing = canonical ? parseReviewStatusState(canonical.body) : undefined;\n if (canonical && !supersedesReviewStatus(existing, step.state)) {\n return { action: 'stale', commentId: canonical.id };\n }\n // Later steps of an attempt carry only what changed; the start time, head and\n // session link come from the step that recorded them. A new attempt (queued or waiting to\n // retry) starts clean, so it never reports an earlier attempt's timing, unless\n // it is only ending the run that earlier attempt started.\n const state =\n existing?.run === step.state.run &&\n (existing.attempt === step.state.attempt || step.continuesRun === true) &&\n !FRESH_ATTEMPT_PHASES.has(step.state.phase)\n ? {\n ...step.state,\n ...((step.state.startedAt ?? existing.startedAt)\n ? { startedAt: step.state.startedAt ?? existing.startedAt }\n : {}),\n ...((step.state.head ?? existing.head) ? { head: step.state.head ?? existing.head } : {}),\n ...((step.state.session ?? existing.session) ? { session: step.state.session ?? existing.session } : {}),\n }\n : step.state;\n // A run only ends a comment it opened: a run cancelled or finished before it\n // ever showed progress leaves no trace, and never replaces another run's result.\n if (!CREATING_PHASES.has(state.phase) && existing?.run !== state.run) return { action: 'skipped' };\n const { stats: readStats, continuesRun: _continuesRun, ...view } = step;\n const stats = readStats ? await readStats(state) : undefined;\n const body = renderReviewStatusComment({ ...view, state, ...(stats ? { stats } : {}) });\n if (!canonical) {\n const created = await versionControl.createComment({ ...ref, body });\n return { action: 'created', commentId: created.id, url: created.url };\n }\n const updated = await versionControl.updateComment({\n connection: ref.connection,\n sourceId: ref.sourceId,\n commentId: canonical.id,\n body,\n });\n return { action: 'updated', commentId: updated.id, url: updated.url };\n}\n"],"mappings":";;AAqBA,MAAM,kCAAkB,IAAI,IAAuB;CAAC;CAAU;CAAa;CAAY;AAAQ,CAAC;AAChG,MAAM,uCAAuB,IAAI,IAAuB,CAAC,UAAU,UAAU,CAAC;AAS9E,eAAe,QAAW,MAA6F;CACrH,MAAM,QAAa,CAAC;CACpB,IAAI;CACJ,GAAG;EACD,MAAM,OAAO,MAAM,KAAK,MAAM;EAC9B,MAAM,KAAK,GAAG,KAAK,KAAK;EACxB,SAAS,KAAK,cAAc,KAAA;CAC9B,SAAS;CACT,OAAO;AACT;AAEA,SAAS,KAAK,MAA0B,OAAmC;CACzE,MAAM,IAAI,OAAO,KAAK,EAAE;CACxB,MAAM,IAAI,OAAO,MAAM,EAAE;CACzB,IAAI,OAAO,SAAS,CAAC,KAAK,OAAO,SAAS,CAAC,GAAG,OAAO,IAAI;CACzD,OAAO,KAAK,GAAG,cAAc,MAAM,EAAE;AACvC;;;;;;;AAQA,eAAsB,oBACpB,gBACA,KACA,MACA,iBACoC;CAQpC,MAAM,CAAC,WAAW,GAAG,eAHN,MAJQ,QAAQ,OAAM,WAAU;EAC7C,MAAM,OAAO,MAAM,eAAe,aAAa;GAAE,GAAG;GAAK,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAG,CAAC;EACxF,OAAO;GAAE,OAAO,KAAK;GAAU,YAAY,KAAK;EAAW;CAC7D,C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,CAAC;CAAG,CAAC;CACtF,IAAI,CAAC,WAAW;EACd,MAAM,UAAU,MAAM,eAAe,cAAc;GAAE,GAAG;GAAK;EAAK,CAAC;EACnE,OAAO;GAAE,QAAQ;GAAW,WAAW,QAAQ;GAAI,KAAK,QAAQ;EAAI;CACtE;CACA,MAAM,UAAU,MAAM,eAAe,cAAc;EACjD,YAAY,IAAI;EAChB,UAAU,IAAI;EACd,WAAW,UAAU;EACrB;CACF,CAAC;CACD,OAAO;EAAE,QAAQ;EAAW,WAAW,QAAQ;EAAI,KAAK,QAAQ;CAAI;AACtE"}
|
|
@@ -2,6 +2,12 @@ import type { RequestContext } from '@mastra/core/request-context';
|
|
|
2
2
|
import type { GithubIntegration } from './integration.js';
|
|
3
3
|
export declare function subscribeCurrentSessionToPullRequest(requestContext: RequestContext, pullRequest: number | string, source: 'auto-gh-pr-create' | 'explicit-tool', github: GithubIntegration): Promise<number | undefined>;
|
|
4
4
|
export declare function unsubscribeCurrentSessionFromPullRequest(requestContext: RequestContext, pullRequest: number | string, github: GithubIntegration): Promise<number>;
|
|
5
|
+
/**
|
|
6
|
+
* The triage handoff with the link to the session that wrote it as its last
|
|
7
|
+
* line. The host adds it, so every pending and final handoff carries it no
|
|
8
|
+
* matter what the agent wrote; a footer already in the body is replaced.
|
|
9
|
+
*/
|
|
10
|
+
export declare function withSessionFooter(body: string, sessionUrl: string | undefined): string;
|
|
5
11
|
export declare function upsertFactoryTriageComment(requestContext: RequestContext, input: {
|
|
6
12
|
issueNumber: number;
|
|
7
13
|
body: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-subscriptions.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/session-subscriptions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"session-subscriptions.d.ts","sourceRoot":"","sources":["../../../src/integrations/github/session-subscriptions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAUnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AA0L1D,wBAAsB,oCAAoC,CACxD,cAAc,EAAE,cAAc,EAC9B,WAAW,EAAE,MAAM,GAAG,MAAM,EAC5B,MAAM,EAAE,mBAAmB,GAAG,eAAe,EAC7C,MAAM,EAAE,iBAAiB,+BAoC1B;AAED,wBAAsB,wCAAwC,CAC5D,cAAc,EAAE,cAAc,EAC9B,WAAW,EAAE,MAAM,GAAG,MAAM,EAC5B,MAAM,EAAE,iBAAiB,mBAM1B;AAMD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAItF;AAED,wBAAsB,0BAA0B,CAC9C,cAAc,EAAE,cAAc,EAC9B,KAAK,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAC5C,MAAM,EAAE,iBAAiB,uEA2B1B;AAED,wBAAsB,kBAAkB,CAAC,cAAc,EAAE,cAAc,EAAE,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAgCjH;AAED,wBAAgB,6BAA6B,CAAC,cAAc,EAAE,cAAc,EAAE,MAAM,EAAE,iBAAiB;;;;;;;;;;;EA8CtG;AAID,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,sBAgBA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from "../../auth.js";
|
|
2
|
+
import { factorySessionUrl } from "../../links.js";
|
|
2
3
|
import { findEnvironmentRepository, resolveSessionRepositories } from "../../session/environment-repositories.js";
|
|
3
4
|
import { runsPullRequestCreate } from "../../session/shell-commands.js";
|
|
4
5
|
import { getGithubPat } from "./pat.js";
|
|
@@ -86,7 +87,9 @@ async function resolveSessionTarget(requestContext, github) {
|
|
|
86
87
|
}
|
|
87
88
|
}),
|
|
88
89
|
orgId,
|
|
89
|
-
userId
|
|
90
|
+
userId,
|
|
91
|
+
factoryProjectId,
|
|
92
|
+
threadId: context.threadId
|
|
90
93
|
};
|
|
91
94
|
}
|
|
92
95
|
/**
|
|
@@ -178,6 +181,18 @@ async function unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequ
|
|
|
178
181
|
await unsubscribeFromPullRequest(subscriptionInput(target, resolved), github.integrationStorage);
|
|
179
182
|
return resolved.number;
|
|
180
183
|
}
|
|
184
|
+
const SESSION_FOOTER_MARKER = "<!-- mastra-factory-session -->";
|
|
185
|
+
const SESSION_FOOTER = new RegExp(`\n*${SESSION_FOOTER_MARKER}\\s*<sub>\\[Factory session\\]\\([^)\\s]*\\)</sub>\\s*$`);
|
|
186
|
+
/**
|
|
187
|
+
* The triage handoff with the link to the session that wrote it as its last
|
|
188
|
+
* line. The host adds it, so every pending and final handoff carries it no
|
|
189
|
+
* matter what the agent wrote; a footer already in the body is replaced.
|
|
190
|
+
*/
|
|
191
|
+
function withSessionFooter(body, sessionUrl) {
|
|
192
|
+
const content = body.replace(SESSION_FOOTER, "").trimEnd();
|
|
193
|
+
if (!sessionUrl) return content;
|
|
194
|
+
return `${content}\n\n${SESSION_FOOTER_MARKER}\n<sub>[Factory session](${sessionUrl})</sub>\n`;
|
|
195
|
+
}
|
|
181
196
|
async function upsertFactoryTriageComment(requestContext, input, github) {
|
|
182
197
|
const target = await resolveSessionTarget(requestContext, github);
|
|
183
198
|
const own = ownRepository(target);
|
|
@@ -193,7 +208,11 @@ async function upsertFactoryTriageComment(requestContext, input, github) {
|
|
|
193
208
|
installationId,
|
|
194
209
|
repository: own.repository.slug,
|
|
195
210
|
issueNumber: input.issueNumber,
|
|
196
|
-
body: input.body
|
|
211
|
+
body: withSessionFooter(input.body, factorySessionUrl({
|
|
212
|
+
factoryProjectId: target.factoryProjectId,
|
|
213
|
+
sessionId: target.context.sessionId,
|
|
214
|
+
threadId: target.threadId
|
|
215
|
+
}))
|
|
197
216
|
}));
|
|
198
217
|
}
|
|
199
218
|
async function refreshGithubToken(requestContext, github) {
|
|
@@ -276,6 +295,6 @@ function parseCreatedPullRequest(context) {
|
|
|
276
295
|
const urls = stdout.match(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g) ?? [];
|
|
277
296
|
return urls.length === 1 ? urls[0] : void 0;
|
|
278
297
|
}
|
|
279
|
-
export { createGithubSubscriptionTools, parseCreatedPullRequest, refreshGithubToken, subscribeCurrentSessionToPullRequest, unsubscribeCurrentSessionFromPullRequest, upsertFactoryTriageComment };
|
|
298
|
+
export { createGithubSubscriptionTools, parseCreatedPullRequest, refreshGithubToken, subscribeCurrentSessionToPullRequest, unsubscribeCurrentSessionFromPullRequest, upsertFactoryTriageComment, withSessionFooter };
|
|
280
299
|
|
|
281
300
|
//# sourceMappingURL=session-subscriptions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-subscriptions.js","names":[],"sources":["../../../src/integrations/github/session-subscriptions.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 { z } from 'zod';\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../../auth.js';\nimport { findEnvironmentRepository, resolveSessionRepositories } from '../../session/environment-repositories.js';\nimport type { EnvironmentRepository } from '../../session/environment-repositories.js';\nimport { runsPullRequestCreate } from '../../session/shell-commands.js';\nimport type { SourceControlInstallation, SourceControlSession } from '../../storage/domains/source-control/base.js';\nimport type { IntegrationTools } from '../base.js';\nimport type { GithubIntegration } from './integration.js';\nimport { getGithubPat } from './pat.js';\nimport { subscribeToPullRequest, unsubscribeFromPullRequest } from './subscriptions.js';\nimport { getGithubRefreshTarget, getRegisteredGithubPatKind, requireGithubTokenInjector } from './token-refresh.js';\n\ntype RepositorySessionState = { factoryProjectId?: string };\n\n/**\n * The host-authenticated user placed on the request context under the `user`\n * key, read through the host's own normalizer. A local mirror of that shape\n * used to live here; it silently missed the provider shapes the normalizer\n * knows about, which turned every subscription tool into a no-op for those\n * users instead of an error anybody could see.\n */\nfunction sessionUserId(requestContext: RequestContext): string | undefined {\n return getFactoryAuthUserId(getFactoryAuthUserFromContext(requestContext));\n}\n\nfunction sessionOrgId(requestContext: RequestContext): string | undefined {\n return getFactoryAuthOrgId(getFactoryAuthUserFromContext(requestContext));\n}\n\nconst pullRequestInputSchema = z.object({\n pullRequest: z.union([z.number().int().positive(), z.string().min(1)]),\n});\n\nconst TRIAGE_COMMENT_MARKER = '<!-- mastra-factory-triage -->';\nconst triageCommentInputSchema = z.object({\n issueNumber: z.number().int().positive(),\n body: z.string().startsWith(TRIAGE_COMMENT_MARKER),\n});\n\nconst triageCommentLocks = new Map<string, Promise<void>>();\n\nasync function serializeTriageComment<T>(key: string, operation: () => Promise<T>): Promise<T> {\n const previous = triageCommentLocks.get(key) ?? Promise.resolve();\n let release: (() => void) | undefined;\n const current = new Promise<void>(resolve => {\n release = resolve;\n });\n const queued = previous.then(() => current);\n triageCommentLocks.set(key, queued);\n await previous;\n try {\n return await operation();\n } finally {\n release!();\n if (triageCommentLocks.get(key) === queued) triageCommentLocks.delete(key);\n }\n}\n\n/**\n * The session a subscription request comes from: its factory row when the\n * session was created through a factory entry point (null for a controller\n * session that only carries `factoryProjectId`), and every repository it may\n * target, the environment list plus its own link.\n */\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n session: SourceControlSession | null;\n repositories: EnvironmentRepository[];\n orgId: string;\n userId: string;\n}\n\n/** One pull request of one environment repository, with the installation that reaches it. */\ninterface PullRequestTarget extends EnvironmentRepository {\n installation: SourceControlInstallation;\n number: number;\n}\n\nconst PULL_REQUEST_URL = /^https:\\/\\/github\\.com\\/([^/]+\\/[^/]+)\\/pull\\/(\\d+)\\/?$/i;\n\nfunction parsePullRequest(value: string): { slug: string; number: number } | undefined {\n const match = value.trim().match(PULL_REQUEST_URL);\n return match ? { slug: match[1]!, number: Number(match[2]) } : undefined;\n}\n\n/** The link the session is filed under, when the environment still carries it. */\nfunction ownRepository(target: SessionTarget): EnvironmentRepository | undefined {\n const ownId = target.session?.projectRepositoryId;\n return ownId ? target.repositories.find(candidate => candidate.link.id === ownId) : undefined;\n}\n\n/**\n * Whether the current request comes from a session that GitHub subscriptions\n * can ever apply to: an authenticated org user on a factory session with an\n * active thread. Mirrors the gate in `resolveSessionTarget` without throwing,\n * for passive callers that should no-op instead of erroring.\n */\nfunction isGithubProjectSession(requestContext: RequestContext): boolean {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n return Boolean(\n context?.threadId &&\n context.getState().factoryProjectId &&\n sessionOrgId(requestContext) &&\n sessionUserId(requestContext),\n );\n}\n\nasync function resolveSessionTarget(requestContext: RequestContext, github: GithubIntegration): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const orgId = sessionOrgId(requestContext);\n const userId = sessionUserId(requestContext);\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context || !context.threadId || !factoryProjectId || !orgId || !userId) {\n throw new Error('GitHub subscriptions require an authenticated repository session with an active thread.');\n }\n const sourceControl = github.sourceControlStorage;\n const session = await sourceControl.sessions.getBySessionId(context.sessionId);\n if (session && (session.orgId !== orgId || (session.factoryProjectId && session.factoryProjectId !== factoryProjectId))) {\n throw new Error('The active session does not belong to this Factory.');\n }\n const repositories = await resolveSessionRepositories({\n sourceControl,\n session: session ?? { orgId, factoryProjectId, projectRepositoryId: null },\n });\n return { context, session, repositories, orgId, userId };\n}\n\n/**\n * The environment repository a pull request reference names. A canonical URL\n * resolves against every repository the session may target; a bare number\n * only against the link the session is filed under.\n */\nasync function resolvePullRequest(\n target: SessionTarget,\n value: number | string,\n github: GithubIntegration,\n): Promise<PullRequestTarget> {\n let repository: EnvironmentRepository | undefined;\n let number: number;\n if (typeof value === 'number' || /^\\d+$/.test(value.trim())) {\n repository = ownRepository(target);\n if (!repository) {\n throw new Error('Pass the full pull request URL: this session is not filed under a single repository.');\n }\n number = Number(value);\n } else {\n const parsed = parsePullRequest(value);\n if (!parsed) throw new Error('Pull request must be a number or a canonical GitHub pull request URL.');\n repository = findEnvironmentRepository(target.repositories, parsed.slug);\n if (!repository) throw new Error(`Pull request ${value.trim()} is not in a repository linked to this Factory.`);\n number = parsed.number;\n }\n const installation = await github.sourceControlStorage.installations.get({\n orgId: target.orgId,\n id: repository.connection.installationId,\n });\n if (!installation) throw new Error('Source-control installation not found for this organization.');\n return { ...repository, installation, number };\n}\n\n/** Confirm the pull request lives in the repository its reference named; returns its head ref. */\nasync function verifyPullRequest(pullRequest: PullRequestTarget, github: GithubIntegration): Promise<string> {\n const [owner, repo] = pullRequest.repository.slug.split('/');\n if (!owner || !repo) throw new Error('GitHub repository is invalid.');\n const octokit = github.getInstallationOctokit(Number(pullRequest.installation.externalId));\n const { data } = await octokit.pulls.get({ owner, repo, pull_number: pullRequest.number });\n if (String(data.base.repo.id) !== pullRequest.repository.externalId)\n throw new Error('Pull request repository does not match the active project repository.');\n return data.head.ref;\n}\n\nfunction subscriptionInput(target: SessionTarget, pullRequest: PullRequestTarget) {\n return {\n orgId: target.orgId,\n installationExternalId: pullRequest.installation.externalId,\n projectRepositoryId: pullRequest.link.id,\n repositoryExternalId: pullRequest.repository.externalId,\n repositorySlug: pullRequest.repository.slug,\n changeRequestId: String(pullRequest.number),\n sessionId: target.context.session.id,\n ownerId: target.context.session.ownerId,\n resourceId: pullRequest.connection.factoryProjectId,\n threadId: target.context.threadId!,\n source: 'explicit-tool' as const,\n subscribedByUserId: target.userId,\n };\n}\n\nexport async function subscribeCurrentSessionToPullRequest(\n requestContext: RequestContext,\n pullRequest: number | string,\n source: 'auto-gh-pr-create' | 'explicit-tool',\n github: GithubIntegration,\n) {\n // The auto path observes every successful `gh pr create` in every session,\n // including local and non-GitHub-project sessions where subscriptions can\n // never apply. Skip silently there; only the explicit tool should surface\n // \"this session cannot subscribe\" as an error.\n if (source === 'auto-gh-pr-create' && !isGithubProjectSession(requestContext)) return undefined;\n const target = await resolveSessionTarget(requestContext, github);\n // A URL outside the environment on the auto path is the agent opening a PR\n // somewhere this Factory does not follow: observed, never subscribed.\n if (source === 'auto-gh-pr-create' && typeof pullRequest === 'string') {\n const parsed = parsePullRequest(pullRequest);\n if (parsed && !findEnvironmentRepository(target.repositories, parsed.slug)) {\n console.warn(\"[GitHub] Pull request URL is not in this Factory's environment; not subscribing\", {\n url: pullRequest.trim(),\n });\n return undefined;\n }\n }\n const resolved = await resolvePullRequest(target, pullRequest, github);\n const headRef = await verifyPullRequest(resolved, github);\n await subscribeToPullRequest({ ...subscriptionInput(target, resolved), source }, github.integrationStorage);\n // The session-repository row is the per-repository record of what this\n // session opened, so only a pull request from the session's own branch\n // lands there; subscribing to someone else's pull request leaves it alone.\n // An existing row keeps the branch its push wrote.\n if (target.session && headRef === target.session.branch) {\n await github.sourceControlStorage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: resolved.link.id,\n changeRequestId: String(resolved.number),\n changeRequestUrl: `https://github.com/${resolved.repository.slug}/pull/${resolved.number}`,\n fallbackBranch: headRef,\n });\n }\n return resolved.number;\n}\n\nexport async function unsubscribeCurrentSessionFromPullRequest(\n requestContext: RequestContext,\n pullRequest: number | string,\n github: GithubIntegration,\n) {\n const target = await resolveSessionTarget(requestContext, github);\n const resolved = await resolvePullRequest(target, pullRequest, github);\n await unsubscribeFromPullRequest(subscriptionInput(target, resolved), github.integrationStorage);\n return resolved.number;\n}\n\nexport async function upsertFactoryTriageComment(\n requestContext: RequestContext,\n input: { issueNumber: number; body: string },\n github: GithubIntegration,\n) {\n const target = await resolveSessionTarget(requestContext, github);\n const own = ownRepository(target);\n if (!own) throw new Error('The triage handoff needs a session filed under a single repository.');\n const installation = await github.sourceControlStorage.installations.get({\n orgId: target.orgId,\n id: own.connection.installationId,\n });\n if (!installation) throw new Error('Source-control installation not found for this organization.');\n const installationId = Number(installation.externalId);\n if (!Number.isSafeInteger(installationId) || installationId <= 0) throw new Error('GitHub installation is invalid.');\n return serializeTriageComment(`${installationId}:${own.repository.externalId}:${input.issueNumber}`, () =>\n github.upsertFactoryTriageComment({\n installationId,\n repository: own.repository.slug,\n issueNumber: input.issueNumber,\n body: input.body,\n }),\n );\n}\n\nexport async function refreshGithubToken(requestContext: RequestContext, github: GithubIntegration): Promise<void> {\n const inject = requireGithubTokenInjector(requestContext);\n // The workspace resolver records the target only after authorizing the\n // caller against the GitHub-backed session that owns this sandbox.\n const target = getGithubRefreshTarget(requestContext);\n if (!target) throw new Error('The active session is not backed by a GitHub workspace.');\n // `GH_TOKEN` feeds the `gh` CLI, so a configured org PAT wins over a minted\n // installation token (which 403s on integration-restricted endpoints). The\n // workspace records which PAT kind the sandbox was provisioned with, so a\n // review-board sandbox keeps its reviewer token on refresh.\n const pat = await getGithubPat(\n () => github.integrationStorage,\n target.orgId,\n getRegisteredGithubPatKind(requestContext),\n );\n if (pat) {\n inject(pat, true);\n return;\n }\n // The boot's own minter keeps the environment scope (and the agent's note\n // about it) in step with what `gh` reaches after a refresh.\n if (target.mint) {\n inject(await target.mint());\n return;\n }\n const access = await github.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repositoryId,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session.');\n inject(token);\n}\n\nexport function createGithubSubscriptionTools(requestContext: RequestContext, github: GithubIntegration) {\n const tools: IntegrationTools = {};\n if (getGithubRefreshTarget(requestContext)) {\n tools.github_refresh_token = createTool({\n id: 'github_refresh_token',\n description:\n 'Refresh GitHub CLI authentication in the active Factory sandbox. Use this after a gh command fails because authentication is expired, invalid, or missing. It installs a fresh GH_TOKEN for subsequent sandbox commands. After this tool succeeds, retry the failed gh command. Takes no arguments and never returns the token.',\n inputSchema: z.object({}),\n execute: async () => {\n await refreshGithubToken(requestContext, github);\n return { refreshed: true };\n },\n });\n }\n if (!isGithubProjectSession(requestContext)) return tools;\n\n return {\n ...tools,\n github_upsert_factory_triage_comment: createTool({\n id: 'github_upsert_factory_triage_comment',\n description:\n 'Create or update this Factory App’s canonical triage handoff comment on an issue in the active repository. Use this for every marked pending or final Factory triage handoff; never use gh to create or edit that handoff.',\n inputSchema: triageCommentInputSchema,\n execute: async input => upsertFactoryTriageComment(requestContext, input, github),\n }),\n github_subscribe_pr: createTool({\n id: 'github_subscribe_pr',\n description:\n 'Subscribe this thread to GitHub pull request activity. PRs created with gh pr create are subscribed automatically. Call this when you start working on an existing PR you did not create in this thread (reviewing it, fixing merge conflicts, addressing review comments, fixing CI, pushing to its branch), or to recover when automatic subscription did not occur. Closed or merged PRs are unsubscribed automatically. Accepts a canonical PR URL for any repository in this Factory; a bare PR number only when this session is filed under a single repository, so pass the URL when the Factory has more than one.',\n inputSchema: pullRequestInputSchema,\n execute: async ({ pullRequest }) => {\n const number = await subscribeCurrentSessionToPullRequest(requestContext, pullRequest, 'explicit-tool', github);\n return { subscribed: true, pullRequestNumber: number };\n },\n }),\n github_unsubscribe_pr: createTool({\n id: 'github_unsubscribe_pr',\n description:\n 'Manually unsubscribe this thread from GitHub pull request activity. You usually do not need this tool because closed or merged PRs are unsubscribed automatically. Use it to stop notifications before then. Accepts a canonical PR URL for any repository in this Factory, or a bare PR number when this session is filed under a single repository.',\n inputSchema: pullRequestInputSchema,\n execute: async ({ pullRequest }) => {\n const number = await unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github);\n return { subscribed: false, pullRequestNumber: number };\n },\n }),\n };\n}\n\nconst GITHUB_PULL_REQUEST_URL = /^https:\\/\\/github\\.com\\/[^\\s/]+\\/[^\\s/]+\\/pull\\/\\d+\\/?$/;\n\nexport function parseCreatedPullRequest(context: {\n toolName: string;\n input: unknown;\n output?: unknown;\n error?: unknown;\n}) {\n if (context.error) return undefined;\n // The provider-neutral change-request tool reports the created PR directly;\n // subscribe on it exactly as on a successful `gh pr create`.\n if (context.toolName === 'source_control_create_change_request') {\n const url = (context.output as { url?: unknown } | undefined)?.url;\n return typeof url === 'string' && GITHUB_PULL_REQUEST_URL.test(url) ? url.replace(/\\/$/, '') : undefined;\n }\n if (context.toolName !== 'execute_command') return undefined;\n const command = (context.input as { command?: unknown } | undefined)?.command;\n if (typeof command !== 'string' || !runsPullRequestCreate(command)) return undefined;\n const output = context.output as { stdout?: unknown; result?: unknown } | undefined;\n const stdout = typeof context.output === 'string' ? context.output : (output?.stdout ?? output?.result);\n if (typeof stdout !== 'string') return undefined;\n const urls = stdout.match(/https:\\/\\/github\\.com\\/[^\\s/]+\\/[^\\s/]+\\/pull\\/\\d+/g) ?? [];\n return urls.length === 1 ? urls[0] : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,SAAS,cAAc,gBAAoD;CACzE,OAAO,qBAAqB,8BAA8B,cAAc,CAAC;AAC3E;AAEA,SAAS,aAAa,gBAAoD;CACxE,OAAO,oBAAoB,8BAA8B,cAAc,CAAC;AAC1E;AAEA,MAAM,yBAAyB,EAAE,OAAO,EACtC,aAAa,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EACvE,CAAC;AAGD,MAAM,2BAA2B,EAAE,OAAO;CACxC,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CACvC,MAAM,EAAE,OAAO,CAAC,CAAC,WAAW,gCAAqB;AACnD,CAAC;AAED,MAAM,qCAAqB,IAAI,IAA2B;AAE1D,eAAe,uBAA0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D,MAAM,MAAO,QAAQ,QAA0C;EAC/D,OAAO,OAAO,QAAQ,YAAY,wBAAwB,KAAK,GAAG,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,KAAA;CACjG;CACA,IAAI,QAAQ,aAAa,mBAAmB,OAAO,KAAA;CACnD,MAAM,UAAW,QAAQ,OAA6C;CACtE,IAAI,OAAO,YAAY,YAAY,CAAC,sBAAsB,OAAO,GAAG,OAAO,KAAA;CAC3E,MAAM,SAAS,QAAQ;CACvB,MAAM,SAAS,OAAO,QAAQ,WAAW,WAAW,QAAQ,SAAU,QAAQ,UAAU,QAAQ;CAChG,IAAI,OAAO,WAAW,UAAU,OAAO,KAAA;CACvC,MAAM,OAAO,OAAO,MAAM,qDAAqD,KAAK,CAAC;CACrF,OAAO,KAAK,WAAW,IAAI,KAAK,KAAK,KAAA;AACvC"}
|
|
1
|
+
{"version":3,"file":"session-subscriptions.js","names":[],"sources":["../../../src/integrations/github/session-subscriptions.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 { z } from 'zod';\nimport { getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from '../../auth.js';\nimport { factorySessionUrl } from '../../links.js';\nimport { findEnvironmentRepository, resolveSessionRepositories } from '../../session/environment-repositories.js';\nimport type { EnvironmentRepository } from '../../session/environment-repositories.js';\nimport { runsPullRequestCreate } from '../../session/shell-commands.js';\nimport type { SourceControlInstallation, SourceControlSession } from '../../storage/domains/source-control/base.js';\nimport type { IntegrationTools } from '../base.js';\nimport type { GithubIntegration } from './integration.js';\nimport { getGithubPat } from './pat.js';\nimport { subscribeToPullRequest, unsubscribeFromPullRequest } from './subscriptions.js';\nimport { getGithubRefreshTarget, getRegisteredGithubPatKind, requireGithubTokenInjector } from './token-refresh.js';\n\ntype RepositorySessionState = { factoryProjectId?: string };\n\n/**\n * The host-authenticated user placed on the request context under the `user`\n * key, read through the host's own normalizer. A local mirror of that shape\n * used to live here; it silently missed the provider shapes the normalizer\n * knows about, which turned every subscription tool into a no-op for those\n * users instead of an error anybody could see.\n */\nfunction sessionUserId(requestContext: RequestContext): string | undefined {\n return getFactoryAuthUserId(getFactoryAuthUserFromContext(requestContext));\n}\n\nfunction sessionOrgId(requestContext: RequestContext): string | undefined {\n return getFactoryAuthOrgId(getFactoryAuthUserFromContext(requestContext));\n}\n\nconst pullRequestInputSchema = z.object({\n pullRequest: z.union([z.number().int().positive(), z.string().min(1)]),\n});\n\nconst TRIAGE_COMMENT_MARKER = '<!-- mastra-factory-triage -->';\nconst triageCommentInputSchema = z.object({\n issueNumber: z.number().int().positive(),\n body: z.string().startsWith(TRIAGE_COMMENT_MARKER),\n});\n\nconst triageCommentLocks = new Map<string, Promise<void>>();\n\nasync function serializeTriageComment<T>(key: string, operation: () => Promise<T>): Promise<T> {\n const previous = triageCommentLocks.get(key) ?? Promise.resolve();\n let release: (() => void) | undefined;\n const current = new Promise<void>(resolve => {\n release = resolve;\n });\n const queued = previous.then(() => current);\n triageCommentLocks.set(key, queued);\n await previous;\n try {\n return await operation();\n } finally {\n release!();\n if (triageCommentLocks.get(key) === queued) triageCommentLocks.delete(key);\n }\n}\n\n/**\n * The session a subscription request comes from: its factory row when the\n * session was created through a factory entry point (null for a controller\n * session that only carries `factoryProjectId`), and every repository it may\n * target, the environment list plus its own link.\n */\ninterface SessionTarget {\n context: AgentControllerRequestContext<RepositorySessionState>;\n session: SourceControlSession | null;\n repositories: EnvironmentRepository[];\n orgId: string;\n userId: string;\n factoryProjectId: string;\n threadId: string;\n}\n\n/** One pull request of one environment repository, with the installation that reaches it. */\ninterface PullRequestTarget extends EnvironmentRepository {\n installation: SourceControlInstallation;\n number: number;\n}\n\nconst PULL_REQUEST_URL = /^https:\\/\\/github\\.com\\/([^/]+\\/[^/]+)\\/pull\\/(\\d+)\\/?$/i;\n\nfunction parsePullRequest(value: string): { slug: string; number: number } | undefined {\n const match = value.trim().match(PULL_REQUEST_URL);\n return match ? { slug: match[1]!, number: Number(match[2]) } : undefined;\n}\n\n/** The link the session is filed under, when the environment still carries it. */\nfunction ownRepository(target: SessionTarget): EnvironmentRepository | undefined {\n const ownId = target.session?.projectRepositoryId;\n return ownId ? target.repositories.find(candidate => candidate.link.id === ownId) : undefined;\n}\n\n/**\n * Whether the current request comes from a session that GitHub subscriptions\n * can ever apply to: an authenticated org user on a factory session with an\n * active thread. Mirrors the gate in `resolveSessionTarget` without throwing,\n * for passive callers that should no-op instead of erroring.\n */\nfunction isGithubProjectSession(requestContext: RequestContext): boolean {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n return Boolean(\n context?.threadId &&\n context.getState().factoryProjectId &&\n sessionOrgId(requestContext) &&\n sessionUserId(requestContext),\n );\n}\n\nasync function resolveSessionTarget(requestContext: RequestContext, github: GithubIntegration): Promise<SessionTarget> {\n const context = requestContext.get('controller') as AgentControllerRequestContext<RepositorySessionState> | undefined;\n const orgId = sessionOrgId(requestContext);\n const userId = sessionUserId(requestContext);\n const factoryProjectId = context?.getState().factoryProjectId;\n if (!context || !context.threadId || !factoryProjectId || !orgId || !userId) {\n throw new Error('GitHub subscriptions require an authenticated repository session with an active thread.');\n }\n const sourceControl = github.sourceControlStorage;\n const session = await sourceControl.sessions.getBySessionId(context.sessionId);\n if (\n session &&\n (session.orgId !== orgId || (session.factoryProjectId && session.factoryProjectId !== factoryProjectId))\n ) {\n throw new Error('The active session does not belong to this Factory.');\n }\n const repositories = await resolveSessionRepositories({\n sourceControl,\n session: session ?? { orgId, factoryProjectId, projectRepositoryId: null },\n });\n return { context, session, repositories, orgId, userId, factoryProjectId, threadId: context.threadId };\n}\n\n/**\n * The environment repository a pull request reference names. A canonical URL\n * resolves against every repository the session may target; a bare number\n * only against the link the session is filed under.\n */\nasync function resolvePullRequest(\n target: SessionTarget,\n value: number | string,\n github: GithubIntegration,\n): Promise<PullRequestTarget> {\n let repository: EnvironmentRepository | undefined;\n let number: number;\n if (typeof value === 'number' || /^\\d+$/.test(value.trim())) {\n repository = ownRepository(target);\n if (!repository) {\n throw new Error('Pass the full pull request URL: this session is not filed under a single repository.');\n }\n number = Number(value);\n } else {\n const parsed = parsePullRequest(value);\n if (!parsed) throw new Error('Pull request must be a number or a canonical GitHub pull request URL.');\n repository = findEnvironmentRepository(target.repositories, parsed.slug);\n if (!repository) throw new Error(`Pull request ${value.trim()} is not in a repository linked to this Factory.`);\n number = parsed.number;\n }\n const installation = await github.sourceControlStorage.installations.get({\n orgId: target.orgId,\n id: repository.connection.installationId,\n });\n if (!installation) throw new Error('Source-control installation not found for this organization.');\n return { ...repository, installation, number };\n}\n\n/** Confirm the pull request lives in the repository its reference named; returns its head ref. */\nasync function verifyPullRequest(pullRequest: PullRequestTarget, github: GithubIntegration): Promise<string> {\n const [owner, repo] = pullRequest.repository.slug.split('/');\n if (!owner || !repo) throw new Error('GitHub repository is invalid.');\n const octokit = github.getInstallationOctokit(Number(pullRequest.installation.externalId));\n const { data } = await octokit.pulls.get({ owner, repo, pull_number: pullRequest.number });\n if (String(data.base.repo.id) !== pullRequest.repository.externalId)\n throw new Error('Pull request repository does not match the active project repository.');\n return data.head.ref;\n}\n\nfunction subscriptionInput(target: SessionTarget, pullRequest: PullRequestTarget) {\n return {\n orgId: target.orgId,\n installationExternalId: pullRequest.installation.externalId,\n projectRepositoryId: pullRequest.link.id,\n repositoryExternalId: pullRequest.repository.externalId,\n repositorySlug: pullRequest.repository.slug,\n changeRequestId: String(pullRequest.number),\n sessionId: target.context.session.id,\n ownerId: target.context.session.ownerId,\n resourceId: pullRequest.connection.factoryProjectId,\n threadId: target.context.threadId!,\n source: 'explicit-tool' as const,\n subscribedByUserId: target.userId,\n };\n}\n\nexport async function subscribeCurrentSessionToPullRequest(\n requestContext: RequestContext,\n pullRequest: number | string,\n source: 'auto-gh-pr-create' | 'explicit-tool',\n github: GithubIntegration,\n) {\n // The auto path observes every successful `gh pr create` in every session,\n // including local and non-GitHub-project sessions where subscriptions can\n // never apply. Skip silently there; only the explicit tool should surface\n // \"this session cannot subscribe\" as an error.\n if (source === 'auto-gh-pr-create' && !isGithubProjectSession(requestContext)) return undefined;\n const target = await resolveSessionTarget(requestContext, github);\n // A URL outside the environment on the auto path is the agent opening a PR\n // somewhere this Factory does not follow: observed, never subscribed.\n if (source === 'auto-gh-pr-create' && typeof pullRequest === 'string') {\n const parsed = parsePullRequest(pullRequest);\n if (parsed && !findEnvironmentRepository(target.repositories, parsed.slug)) {\n console.warn(\"[GitHub] Pull request URL is not in this Factory's environment; not subscribing\", {\n url: pullRequest.trim(),\n });\n return undefined;\n }\n }\n const resolved = await resolvePullRequest(target, pullRequest, github);\n const headRef = await verifyPullRequest(resolved, github);\n await subscribeToPullRequest({ ...subscriptionInput(target, resolved), source }, github.integrationStorage);\n // The session-repository row is the per-repository record of what this\n // session opened, so only a pull request from the session's own branch\n // lands there; subscribing to someone else's pull request leaves it alone.\n // An existing row keeps the branch its push wrote.\n if (target.session && headRef === target.session.branch) {\n await github.sourceControlStorage.sessionRepositories.upsert({\n sessionId: target.session.sessionId,\n projectRepositoryId: resolved.link.id,\n changeRequestId: String(resolved.number),\n changeRequestUrl: `https://github.com/${resolved.repository.slug}/pull/${resolved.number}`,\n fallbackBranch: headRef,\n });\n }\n return resolved.number;\n}\n\nexport async function unsubscribeCurrentSessionFromPullRequest(\n requestContext: RequestContext,\n pullRequest: number | string,\n github: GithubIntegration,\n) {\n const target = await resolveSessionTarget(requestContext, github);\n const resolved = await resolvePullRequest(target, pullRequest, github);\n await unsubscribeFromPullRequest(subscriptionInput(target, resolved), github.integrationStorage);\n return resolved.number;\n}\n\nconst SESSION_FOOTER_MARKER = '<!-- mastra-factory-session -->';\n\nconst SESSION_FOOTER = new RegExp(`\\n*${SESSION_FOOTER_MARKER}\\\\s*<sub>\\\\[Factory session\\\\]\\\\([^)\\\\s]*\\\\)</sub>\\\\s*$`);\n\n/**\n * The triage handoff with the link to the session that wrote it as its last\n * line. The host adds it, so every pending and final handoff carries it no\n * matter what the agent wrote; a footer already in the body is replaced.\n */\nexport function withSessionFooter(body: string, sessionUrl: string | undefined): string {\n const content = body.replace(SESSION_FOOTER, '').trimEnd();\n if (!sessionUrl) return content;\n return `${content}\\n\\n${SESSION_FOOTER_MARKER}\\n<sub>[Factory session](${sessionUrl})</sub>\\n`;\n}\n\nexport async function upsertFactoryTriageComment(\n requestContext: RequestContext,\n input: { issueNumber: number; body: string },\n github: GithubIntegration,\n) {\n const target = await resolveSessionTarget(requestContext, github);\n const own = ownRepository(target);\n if (!own) throw new Error('The triage handoff needs a session filed under a single repository.');\n const installation = await github.sourceControlStorage.installations.get({\n orgId: target.orgId,\n id: own.connection.installationId,\n });\n if (!installation) throw new Error('Source-control installation not found for this organization.');\n const installationId = Number(installation.externalId);\n if (!Number.isSafeInteger(installationId) || installationId <= 0) throw new Error('GitHub installation is invalid.');\n return serializeTriageComment(`${installationId}:${own.repository.externalId}:${input.issueNumber}`, () =>\n github.upsertFactoryTriageComment({\n installationId,\n repository: own.repository.slug,\n issueNumber: input.issueNumber,\n body: withSessionFooter(\n input.body,\n factorySessionUrl({\n factoryProjectId: target.factoryProjectId,\n sessionId: target.context.sessionId,\n threadId: target.threadId,\n }),\n ),\n }),\n );\n}\n\nexport async function refreshGithubToken(requestContext: RequestContext, github: GithubIntegration): Promise<void> {\n const inject = requireGithubTokenInjector(requestContext);\n // The workspace resolver records the target only after authorizing the\n // caller against the GitHub-backed session that owns this sandbox.\n const target = getGithubRefreshTarget(requestContext);\n if (!target) throw new Error('The active session is not backed by a GitHub workspace.');\n // `GH_TOKEN` feeds the `gh` CLI, so a configured org PAT wins over a minted\n // installation token (which 403s on integration-restricted endpoints). The\n // workspace records which PAT kind the sandbox was provisioned with, so a\n // review-board sandbox keeps its reviewer token on refresh.\n const pat = await getGithubPat(\n () => github.integrationStorage,\n target.orgId,\n getRegisteredGithubPatKind(requestContext),\n );\n if (pat) {\n inject(pat, true);\n return;\n }\n // The boot's own minter keeps the environment scope (and the agent's note\n // about it) in step with what `gh` reaches after a refresh.\n if (target.mint) {\n inject(await target.mint());\n return;\n }\n const access = await github.versionControl.getRepositoryAccess({\n orgId: target.orgId,\n repositoryId: target.repositoryId,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session.');\n inject(token);\n}\n\nexport function createGithubSubscriptionTools(requestContext: RequestContext, github: GithubIntegration) {\n const tools: IntegrationTools = {};\n if (getGithubRefreshTarget(requestContext)) {\n tools.github_refresh_token = createTool({\n id: 'github_refresh_token',\n description:\n 'Refresh GitHub CLI authentication in the active Factory sandbox. Use this after a gh command fails because authentication is expired, invalid, or missing. It installs a fresh GH_TOKEN for subsequent sandbox commands. After this tool succeeds, retry the failed gh command. Takes no arguments and never returns the token.',\n inputSchema: z.object({}),\n execute: async () => {\n await refreshGithubToken(requestContext, github);\n return { refreshed: true };\n },\n });\n }\n if (!isGithubProjectSession(requestContext)) return tools;\n\n return {\n ...tools,\n github_upsert_factory_triage_comment: createTool({\n id: 'github_upsert_factory_triage_comment',\n description:\n 'Create or update this Factory App’s canonical triage handoff comment on an issue in the active repository. Use this for every marked pending or final Factory triage handoff; never use gh to create or edit that handoff.',\n inputSchema: triageCommentInputSchema,\n execute: async input => upsertFactoryTriageComment(requestContext, input, github),\n }),\n github_subscribe_pr: createTool({\n id: 'github_subscribe_pr',\n description:\n 'Subscribe this thread to GitHub pull request activity. PRs created with gh pr create are subscribed automatically. Call this when you start working on an existing PR you did not create in this thread (reviewing it, fixing merge conflicts, addressing review comments, fixing CI, pushing to its branch), or to recover when automatic subscription did not occur. Closed or merged PRs are unsubscribed automatically. Accepts a canonical PR URL for any repository in this Factory; a bare PR number only when this session is filed under a single repository, so pass the URL when the Factory has more than one.',\n inputSchema: pullRequestInputSchema,\n execute: async ({ pullRequest }) => {\n const number = await subscribeCurrentSessionToPullRequest(requestContext, pullRequest, 'explicit-tool', github);\n return { subscribed: true, pullRequestNumber: number };\n },\n }),\n github_unsubscribe_pr: createTool({\n id: 'github_unsubscribe_pr',\n description:\n 'Manually unsubscribe this thread from GitHub pull request activity. You usually do not need this tool because closed or merged PRs are unsubscribed automatically. Use it to stop notifications before then. Accepts a canonical PR URL for any repository in this Factory, or a bare PR number when this session is filed under a single repository.',\n inputSchema: pullRequestInputSchema,\n execute: async ({ pullRequest }) => {\n const number = await unsubscribeCurrentSessionFromPullRequest(requestContext, pullRequest, github);\n return { subscribed: false, pullRequestNumber: number };\n },\n }),\n };\n}\n\nconst GITHUB_PULL_REQUEST_URL = /^https:\\/\\/github\\.com\\/[^\\s/]+\\/[^\\s/]+\\/pull\\/\\d+\\/?$/;\n\nexport function parseCreatedPullRequest(context: {\n toolName: string;\n input: unknown;\n output?: unknown;\n error?: unknown;\n}) {\n if (context.error) return undefined;\n // The provider-neutral change-request tool reports the created PR directly;\n // subscribe on it exactly as on a successful `gh pr create`.\n if (context.toolName === 'source_control_create_change_request') {\n const url = (context.output as { url?: unknown } | undefined)?.url;\n return typeof url === 'string' && GITHUB_PULL_REQUEST_URL.test(url) ? url.replace(/\\/$/, '') : undefined;\n }\n if (context.toolName !== 'execute_command') return undefined;\n const command = (context.input as { command?: unknown } | undefined)?.command;\n if (typeof command !== 'string' || !runsPullRequestCreate(command)) return undefined;\n const output = context.output as { stdout?: unknown; result?: unknown } | undefined;\n const stdout = typeof context.output === 'string' ? context.output : (output?.stdout ?? output?.result);\n if (typeof stdout !== 'string') return undefined;\n const urls = stdout.match(/https:\\/\\/github\\.com\\/[^\\s/]+\\/[^\\s/]+\\/pull\\/\\d+/g) ?? [];\n return urls.length === 1 ? urls[0] : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyBA,SAAS,cAAc,gBAAoD;CACzE,OAAO,qBAAqB,8BAA8B,cAAc,CAAC;AAC3E;AAEA,SAAS,aAAa,gBAAoD;CACxE,OAAO,oBAAoB,8BAA8B,cAAc,CAAC;AAC1E;AAEA,MAA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AAqD,KAAK,CAAC;CACrF,OAAO,KAAK,WAAW,IAAI,KAAK,KAAK,KAAA;AACvC"}
|
|
@@ -14,7 +14,11 @@ export declare class FactoryDispatchError extends Error {
|
|
|
14
14
|
/** A transition the board's rules rejected while a decision was being applied. */
|
|
15
15
|
export declare class FactoryRuleRejectedError extends Error {
|
|
16
16
|
readonly code: FactoryRuleRejectionCode;
|
|
17
|
-
|
|
17
|
+
/** Every retry would replay this same refusal, so only a person can move the work on. */
|
|
18
|
+
readonly settled: boolean;
|
|
19
|
+
constructor(code: FactoryRuleRejectionCode, reason: string,
|
|
20
|
+
/** Every retry would replay this same refusal, so only a person can move the work on. */
|
|
21
|
+
settled?: boolean);
|
|
18
22
|
}
|
|
19
23
|
export declare function factoryDispatchFailureCode(error: unknown): FactoryDispatchFailureCode;
|
|
20
24
|
export declare function factoryDispatchFailureMetadata(code: StoredFactoryDispatchFailureCode | null): FactoryDispatchFailureMetadata;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispatch-errors.d.ts","sourceRoot":"","sources":["../../src/rules/dispatch-errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,gCAAgC,EACjC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAE3D,UAAU,8BAA8B;IACtC,8CAA8C;IAC9C,QAAQ,EAAE,OAAO,CAAC;IAClB,oGAAoG;IACpG,SAAS,CAAC,EAAE,KAAK,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAwCD,qBAAa,oBAAqB,SAAQ,KAAK;IAE3C,QAAQ,CAAC,IAAI,EAAE,0BAA0B;IAD3C,YACW,IAAI,EAAE,0BAA0B,EACzC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,YAAY,EAIvB;CACF;AAED,kFAAkF;AAClF,qBAAa,wBAAyB,SAAQ,KAAK;IAE/C,QAAQ,CAAC,IAAI,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"dispatch-errors.d.ts","sourceRoot":"","sources":["../../src/rules/dispatch-errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,gCAAgC,EACjC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAE3D,UAAU,8BAA8B;IACtC,8CAA8C;IAC9C,QAAQ,EAAE,OAAO,CAAC;IAClB,oGAAoG;IACpG,SAAS,CAAC,EAAE,KAAK,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAwCD,qBAAa,oBAAqB,SAAQ,KAAK;IAE3C,QAAQ,CAAC,IAAI,EAAE,0BAA0B;IAD3C,YACW,IAAI,EAAE,0BAA0B,EACzC,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,YAAY,EAIvB;CACF;AAED,kFAAkF;AAClF,qBAAa,wBAAyB,SAAQ,KAAK;IAE/C,QAAQ,CAAC,IAAI,EAAE,wBAAwB;IAEvC,yFAAyF;IACzF,QAAQ,CAAC,OAAO;IAJlB,YACW,IAAI,EAAE,wBAAwB,EACvC,MAAM,EAAE,MAAM;IACd,yFAAyF;IAChF,OAAO,UAAQ,EAIzB;CACF;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,CAErF;AAED,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,gCAAgC,GAAG,IAAI,GAC5C,8BAA8B,CAEhC"}
|
|
@@ -121,9 +121,11 @@ var FactoryDispatchError = class extends Error {
|
|
|
121
121
|
/** A transition the board's rules rejected while a decision was being applied. */
|
|
122
122
|
var FactoryRuleRejectedError = class extends Error {
|
|
123
123
|
code;
|
|
124
|
-
|
|
124
|
+
settled;
|
|
125
|
+
constructor(code, reason, settled = false) {
|
|
125
126
|
super(`${code}: ${reason}`);
|
|
126
127
|
this.code = code;
|
|
128
|
+
this.settled = settled;
|
|
127
129
|
this.name = "FactoryRuleRejectedError";
|
|
128
130
|
}
|
|
129
131
|
};
|