@catladder/pipeline 3.14.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/constants.js CHANGED
@@ -4,5 +4,5 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.DOCKER_REGISTRY = exports.PIPELINE_IMAGE_TAG = void 0;
7
- exports.PIPELINE_IMAGE_TAG = "v3-14-0-fd3c74b3" || "latest";
7
+ exports.PIPELINE_IMAGE_TAG = "v3-15-0-a13103cb" || "latest";
8
8
  exports.DOCKER_REGISTRY = "git.panter.ch:5001/catladder/catladder" || "git.panter.ch:5001/catladder/catladder";
@@ -1,5 +1,22 @@
1
1
  import type { Config } from "../../types";
2
- import type { AgentContext } from "../../types/context";
2
+ export declare class AgentContext {
3
+ private readonly agentName;
4
+ private readonly config;
5
+ constructor(agentName: string, config: Config);
6
+ readonly type = "agent";
7
+ get name(): string;
8
+ get agentConfig(): import("../../types").AgentConfig;
9
+ get agentUser(): {
10
+ username: string;
11
+ userId: string;
12
+ };
13
+ get reviews(): {
14
+ byUser: Record<string, {
15
+ automatic: boolean;
16
+ }> | "all-automatic";
17
+ };
18
+ get fullConfig(): Config;
19
+ }
3
20
  export declare const createAgentContext: (ctx: {
4
21
  agentName: string;
5
22
  config: Config;
@@ -118,23 +118,70 @@ var __generator = this && this.__generator || function (thisArg, body) {
118
118
  Object.defineProperty(exports, "__esModule", {
119
119
  value: true
120
120
  });
121
- exports.createAgentContext = void 0;
122
- var createAgentContext = function (ctx) {
123
- return __awaiter(void 0, void 0, void 0, function () {
124
- var agentConfig;
125
- var _a;
126
- return __generator(this, function (_b) {
127
- agentConfig = (_a = ctx.config.agents) === null || _a === void 0 ? void 0 : _a[ctx.agentName];
121
+ exports.createAgentContext = exports.AgentContext = void 0;
122
+ var AgentContext = /** @class */function () {
123
+ function AgentContext(agentName, config) {
124
+ this.agentName = agentName;
125
+ this.config = config;
126
+ this.type = "agent";
127
+ }
128
+ Object.defineProperty(AgentContext.prototype, "name", {
129
+ get: function () {
130
+ return this.agentName;
131
+ },
132
+ enumerable: false,
133
+ configurable: true
134
+ });
135
+ Object.defineProperty(AgentContext.prototype, "agentConfig", {
136
+ get: function () {
137
+ var _a;
138
+ var agentConfig = (_a = this.config.agents) === null || _a === void 0 ? void 0 : _a[this.agentName];
128
139
  if (!agentConfig) {
129
- throw new Error("Agent ".concat(ctx.agentName, " not found in config"));
140
+ throw new Error("Agent ".concat(this.agentName, " not found in config"));
130
141
  }
131
- return [2 /*return*/, {
132
- type: "agent",
133
- name: ctx.agentName,
134
- //env: ctx.env,
135
- fullConfig: ctx.config,
136
- agentConfig: agentConfig
137
- }];
142
+ return agentConfig;
143
+ },
144
+ enumerable: false,
145
+ configurable: true
146
+ });
147
+ Object.defineProperty(AgentContext.prototype, "agentUser", {
148
+ get: function () {
149
+ var _a, _b, _c, _d;
150
+ return {
151
+ username: (_b = (_a = this.agentConfig.agentUser) === null || _a === void 0 ? void 0 : _a.username) !== null && _b !== void 0 ? _b : "agent.claude",
152
+ userId: (_d = (_c = this.agentConfig.agentUser) === null || _c === void 0 ? void 0 : _c.userId) !== null && _d !== void 0 ? _d : "$DEFAULT_AGENT_USER_ID"
153
+ };
154
+ },
155
+ enumerable: false,
156
+ configurable: true
157
+ });
158
+ Object.defineProperty(AgentContext.prototype, "reviews", {
159
+ get: function () {
160
+ var _a;
161
+ var _b, _c;
162
+ return {
163
+ byUser: (_c = (_b = this.agentConfig.reviews) === null || _b === void 0 ? void 0 : _b.byUser) !== null && _c !== void 0 ? _c : (_a = {}, _a[this.agentUser.username] = {
164
+ automatic: true
165
+ }, _a)
166
+ };
167
+ },
168
+ enumerable: false,
169
+ configurable: true
170
+ });
171
+ Object.defineProperty(AgentContext.prototype, "fullConfig", {
172
+ get: function () {
173
+ return this.config;
174
+ },
175
+ enumerable: false,
176
+ configurable: true
177
+ });
178
+ return AgentContext;
179
+ }();
180
+ exports.AgentContext = AgentContext;
181
+ var createAgentContext = function (ctx) {
182
+ return __awaiter(void 0, void 0, void 0, function () {
183
+ return __generator(this, function (_a) {
184
+ return [2 /*return*/, new AgentContext(ctx.agentName, ctx.config)];
138
185
  });
139
186
  });
140
187
  };
@@ -52,13 +52,29 @@ var utils_1 = require("./utils");
52
52
  var createAgentReviewJob = function (context) {
53
53
  var baseJob = (0, shared_1.createBaseAgentJob)(context);
54
54
  var agentUserName = (0, utils_1.getAgentUserName)(context);
55
+ var rules = context.reviews.byUser === "all-automatic" ? [__assign(__assign({}, rules_1.RULE_IS_MERGE_REQUEST), {
56
+ when: "always"
57
+ })] : Object.entries(context.reviews.byUser).filter(function (_a) {
58
+ var _b = __read(_a, 2),
59
+ _ = _b[0],
60
+ automatic = _b[1].automatic;
61
+ return automatic;
62
+ }).map(function (_a) {
63
+ var _b = __read(_a, 1),
64
+ username = _b[0];
65
+ return {
66
+ // GITLAB_USER_LOGIN is the username of the user who created the pipeline
67
+ if: "".concat(rules_1.RULE_IS_MERGE_REQUEST.if, " && $GITLAB_USER_LOGIN == \"").concat(username, "\""),
68
+ when: "always"
69
+ };
70
+ });
55
71
  return __assign(__assign({}, baseJob), {
56
72
  name: context.name + "-agent-review",
57
- rules: [__assign(__assign({}, rules_1.RULE_IS_MERGE_REQUEST), {
58
- when: "always"
73
+ rules: __spreadArray(__spreadArray([], __read(rules), false), [__assign(__assign({}, rules_1.RULE_IS_MERGE_REQUEST), {
74
+ when: "manual"
59
75
  }), {
60
76
  when: "never"
61
- }],
77
+ }], false),
62
78
  script: __spreadArray(__spreadArray([], __read(shared_1.baseSetupScript), false), __read((0, shared_1.callClaude)({
63
79
  prompt: (0, prompts_1.getMergeRequestPrompt)({
64
80
  agentUserName: agentUserName
@@ -1,10 +1,6 @@
1
1
  type Ctx = {
2
2
  agentUserName: string;
3
3
  };
4
- export declare const getEventPrompt: ({
5
- agentUserName
6
- }: Ctx) => string;
7
- export declare const getMergeRequestPrompt: ({
8
- agentUserName
9
- }: Ctx) => string;
4
+ export declare const getEventPrompt: (ctx: Ctx) => string;
5
+ export declare const getMergeRequestPrompt: (ctx: Ctx) => string;
10
6
  export {};
@@ -1,9 +1,13 @@
1
1
  "use strict";
2
2
 
3
+ // prompts.ts — MCP-only, DRY, review-first-then-push, CI logic, self-mention guard,
4
+ // event prompt supports review-on-demand via manual "agent-review" job or fallback MR review.
5
+ // Prevents double-runs: event-triggered work cancels any running "agent-review" job on the same MR.
3
6
  Object.defineProperty(exports, "__esModule", {
4
7
  value: true
5
8
  });
6
9
  exports.getMergeRequestPrompt = exports.getEventPrompt = void 0;
10
+ /* ---------- Shared blocks ---------- */
7
11
  var header = function () {
8
12
  return "\nProject ID: $CI_PROJECT_ID\nGitLab Host: $CI_SERVER_URL\n";
9
13
  };
@@ -13,54 +17,64 @@ var identity = function (_a) {
13
17
  };
14
18
  var goldenRules = function (_a) {
15
19
  var agentUserName = _a.agentUserName;
16
- return "\n## Golden Rules\n- Use the `gitlab-mcp` tool for ALL GitLab actions. If a needed action is missing, use GitLab REST/GraphQL API directly as a fallback.\n- NEVER mention yourself (\"@".concat(agentUserName, "\").\n- NEVER push to main/default or any protected branch. Always create a new branch and open a Merge Request (MR).\n- Do not create an MR for a **closed** issue.\n- Keep actions minimal and idempotent. Avoid duplicate comments or duplicate MRs.\n- Use ONE stable `source_branch` per run; do not regenerate its name later.\n");
20
+ return "\n## Golden Rules\n- Use the `gitlab-mcp` tool for ALL GitLab actions. Do not call any other APIs.\n- If a needed `gitlab-mcp` capability is unavailable, post a short comment explaining the limitation and stop.\n- NEVER mention yourself (\"@".concat(agentUserName, "\") anywhere (comments, descriptions, titles, commit messages).\n- NEVER push to main/default or any protected branch. Always create a new branch and open a Merge Request (MR).\n- Always assign yourself as the assignee of any MR you create.\n- Do not create an MR for a **closed** issue.\n- Keep actions minimal and idempotent. Avoid duplicate comments or duplicate MRs.\n- Use ONE stable `source_branch` per run; do not regenerate its name later.\n");
21
+ };
22
+ var selfMentionGuard = function (_a) {
23
+ var agentUserName = _a.agentUserName;
24
+ return "\n## Self-mention Guard (mandatory preflight for ALL writes)\nBefore ANY call that writes text (comment/create/update MR/issue/commit message), sanitize the text:\n\n- Remove all occurrences of your own handle:\n - Match case-insensitively: `/@?".concat(agentUserName, "\\b/gi`\n - Also strip variants inside parentheses or brackets if present.\n- Do NOT replace with another token; simply remove the self @-mention.\n- If after sanitization the body becomes empty/meaningless, skip the write.\n\nAdditionally:\n- If the last actor/author of the target item is you (\"").concat(agentUserName, "\"), **do not** post an acknowledgement comment (avoid loops on your own events).\n- To assign yourself, use the MCP assignee field(s). Do **not** mention yourself in the body to indicate assignment.\n");
17
25
  };
18
26
  var commentGuidelines = function () {
19
- return "\n## Comment Guidelines (flexible, not verbatim)\n- Keep tone professional, friendly, and concise.\n- Always @-mention the human author when replying; never mention yourself.\n- Acknowledgements: confirm you saw the request and you\u2019ll handle it.\n- MR updates: acknowledge feedback and say you\u2019ll apply/have applied the change.\n- Q&A: answer directly first; add context/links only if useful.\n- Avoid repeating identical boilerplate across comments.\n";
27
+ return "\n## Comment Guidelines (flexible, not verbatim)\n- Professional, friendly, concise.\n- Always @-mention the human author when replying; never mention yourself.\n- Acknowledgements: confirm you saw the request and you\u2019ll handle it.\n- MR updates: acknowledge feedback and say you\u2019ll apply/have applied the change.\n- Q&A: answer directly first; add context/links only if useful.\n- Avoid repeating identical boilerplate across comments.\n";
20
28
  };
21
- var mcpAndApi = function () {
22
- return "\n## Tools & API (MCP-first, REST/GraphQL fallback)\nUse these `gitlab-mcp` capabilities when available (names illustrative\u2014match the actual tool schema):\n\n- **Comments**\n - `gitlab-mcp.comment.create({ project_id: $CI_PROJECT_ID, target: \"issue\"|\"mr\", iid, body })`\n\n- **Branch**\n - `gitlab-mcp.branch.create({ project_id: $CI_PROJECT_ID, from: \"<default_branch>\", name: \"<source_branch>\" })`\n\n- **Commits & push**\n - `gitlab-mcp.commit.push({ project_id: $CI_PROJECT_ID, branch: \"<source_branch>\", message, files: [{ path, content | patch }] })`\n\n- **Merge Requests**\n - `gitlab-mcp.merge_request.create({ project_id: $CI_PROJECT_ID, source_branch, target_branch: \"<default_branch>\", title, description, assign_to_self: true })`\n - `gitlab-mcp.merge_request.update({ project_id: $CI_PROJECT_ID, mr_iid, ... })`\n - `gitlab-mcp.merge_request.rebase({ project_id: $CI_PROJECT_ID, mr_iid, onto: \"<default_branch>\" })`\n\n- **Read/verify**\n - `gitlab-mcp.project.get({ project_id: $CI_PROJECT_ID })` \u2192 default branch\n - `gitlab-mcp.repo.compare({ project_id: $CI_PROJECT_ID, from: \"<default_branch>\", to: \"<source_branch>\" })`\n - `gitlab-mcp.repo.branch.get({ project_id: $CI_PROJECT_ID, name: \"<source_branch>\" })`\n - `gitlab-mcp.repo.commits.list({ project_id: $CI_PROJECT_ID, ref_name: \"<source_branch>\", per_page: 1 })`\n\n### Fallback: Direct GitLab API\nIf MCP lacks an operation, call GitLab\u2019s REST/GraphQL API directly.\n\n- **Authentication** \n Use the environment variable `GITLAB_PERSONAL_ACCESS_TOKEN`. \n Send it in the HTTP header:\n ```\n Private-Token: $GITLAB_PERSONAL_ACCESS_TOKEN\n ```\n\n- **Host & project variables**\n - API base URL: `$CI_SERVER_URL/api/v4`\n - Project ID: `$CI_PROJECT_ID`\n\n- **Examples**\n - Get project (default branch): \n `GET $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID`\n - Get/create branch: \n `GET|POST $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/repository/branches`\n - Compare refs: \n `GET $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/repository/compare?from=<default>&to=<source>`\n - List commits: \n `GET $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/repository/commits?ref_name=<branch>&per_page=1`\n - Create comment on issue/MR: \n `POST $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/issues/:iid/notes` \n `POST $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/merge_requests/:iid/notes`\n - Create MR: \n `POST $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/merge_requests`\n - Get MR changes: \n `GET $CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/merge_requests/:iid/changes`\n";
29
+ /* Exact tool names from @zereight/mcp-gitlab (lean, indicative signatures) */
30
+ var mcpOnly = function () {
31
+ return "\n## gitlab-mcp Operations (exact tool names; indicative params)\n\n- **Comments / Notes**\n - create_note({ projectId, targetType: \"issue\"|\"merge_request\", iid, body })\n - create_issue_note({ projectId, issueIid, body })\n - create_merge_request_note({ projectId, mergeRequestIid, body })\n - update_issue_note({ projectId, issueIid, noteId, body })\n - update_merge_request_note({ projectId, mergeRequestIid, noteId, body })\n - mr_discussions({ projectId, mergeRequestIid })\n\n- **Issues**\n - create_issue({ projectId, title, description, assigneeUsernames?: string[] })\n - list_issues({ projectId, state?: \"opened\"|\"closed\", scope?: \"all\"|... })\n\n- **Branch & Files**\n - create_branch({ projectId, branchName, ref }) // ref = default branch or SHA\n - push_files({ projectId, branch, commitMessage, files: [{ filePath, content }] })\n - create_or_update_file({ projectId, branch, filePath, content, commitMessage })\n - get_file_contents({ projectId, ref, path })\n - get_branch_diffs({ projectId, from, to }) // compare refs\n\n- **Merge Requests**\n - create_merge_request({ projectId, sourceBranch, targetBranch, title, description, assigneeUsernames?: string[] })\n - get_merge_request({ projectId, mergeRequestIid? , branchName? })\n - get_merge_request_diffs({ projectId, mergeRequestIid? , branchName? })\n - list_merge_request_diffs({ projectId, mergeRequestIid? , branchName?, page?, perPage? })\n - update_merge_request({ projectId, mergeRequestIid? , branchName?, title?, description?, draft?, assigneeUsernames? })\n - merge_merge_request(...) // **Do NOT use** (never merge)\n\n- **Pipelines / Jobs** (requires env USE_PIPELINE=true)\n - list_pipeline_jobs({ projectId, pipelineId })\n - get_pipeline_job_output({ projectId, pipelineId, jobId })\n - retry_pipeline({ projectId, pipelineId })\n - retry_pipeline_job({ projectId, jobId })\n - play_pipeline_job({ projectId, jobId })\n - cancel_pipeline_job({ projectId, jobId })\n";
23
32
  };
24
33
  var outputDiscipline = function (_a) {
25
34
  var agentUserName = _a.agentUserName;
26
- return "\n## Output Discipline\n- Prefer `gitlab-mcp` tool calls. If unavailable, output direct API requests (endpoint, method, headers, JSON body).\n- Keep comments concise and professional.\n- Never include \"@".concat(agentUserName, "\" in any body.\n");
35
+ return "\n## Output Discipline\n- Output only `gitlab-mcp` tool calls and plain-text summaries where requested.\n- Keep comments concise and professional.\n- Never include \"@".concat(agentUserName, "\" in any body.\n");
27
36
  };
28
- // --- Event-specific sections ---
37
+ /* ---------- Event (webhook) specific ---------- */
29
38
  var eventSelfParse = function () {
30
- return "\n## Self-Parse the Raw Payload (no preprocessing available)\nFrom `event_json`, extract:\n- kind: \"issue\" | \"merge_request\" | \"note\"\n- target + iid from URL:\n - `/-/issues/<n>` \u2192 target=\"issue\", iid=<n>\n - `/-/merge_requests/<n>` \u2192 target=\"mr\", iid=<n>\n- note_id if present (`#note_<id>`)\n- description/body text, state, author `user_username`, timestamps\n- project id/path; detect default branch via tool/API when needed\n\nIf any key is missing, choose the safest minimal action or briefly explain via a comment.\n";
39
+ return "\n## Self-Parse the Raw Payload (no preprocessing available)\nFrom `event_json`, extract:\n- kind: \"issue\" | \"merge_request\" | \"note\"\n- target + iid from URL:\n - `/-/issues/<n>` \u2192 target=\"issue\", iid=<n>\n - `/-/merge_requests/<n>` \u2192 target=\"mr\", iid=<n>\n- note_id if present (`#note_<id>`)\n- description/body text, state, author `user_username`, timestamps\n- project id/path; detect default branch via `get_merge_request`/context as needed\n\nIf any key is missing, choose the safest minimal action or briefly explain via a comment.\n";
40
+ };
41
+ // NEW: Single-runner guard (event-triggered → existing MR)
42
+ var singleRunnerGuard = function () {
43
+ return "\n## Single-Runner Guard (event-triggered work on an existing MR)\nBefore entering MR Review Mode from an event:\n\n- **Goal:** Avoid two agents working the same MR. If a **running or pending** CI job whose name **ends with \"agent-review\"** is active for this MR, **cancel** it first.\n\n**Best-effort procedure (MCP-only):**\n1) If `$CI_PIPELINE_ID` is available (this event is executing inside a CI context for the same MR):\n - Call `list_pipeline_jobs({ projectId: $CI_PROJECT_ID, pipelineId: $CI_PIPELINE_ID })`.\n - Identify any job where `status` is `\"running\"` or `\"pending\"` **and** `name` **endsWith** `\"agent-review\"`.\n - For each match, call `cancel_pipeline_job({ projectId: $CI_PROJECT_ID, jobId })`.\n - Proceed with review immediately after issuing cancellations (do not wait).\n\n2) If `$CI_PIPELINE_ID` is **not** available, or jobs for this MR cannot be listed with available MCP calls:\n - Post a short MR note stating you are proceeding but **cannot verify/cancel** a running `agent-review` job due to missing capabilities.\n - Proceed with review.\n\n**Notes:**\n- Keep this guard **idempotent** (safe to run multiple times).\n- This guard only applies to **event-triggered** flows that decide to act on an **existing MR**.\n";
44
+ };
45
+ var reviewOnDemandFromEvents = function () {
46
+ return "\n## Review-on-Demand (from events)\nIf the issue/note text **asks for a review** (case-insensitive tokens like: \"review\", \"please review\", \"PTAL\", \"needs review\", \"can you look at\", \"LGTM?\"), then:\n\n1) **Check for pipeline review job**\n - List jobs for the current pipeline `$CI_PIPELINE_ID` via `list_pipeline_jobs`.\n - If any job has `status = \"manual\"` **and** its `name` ends with \"agent-review\":\n - Trigger it via `play_pipeline_job({ projectId: $CI_PROJECT_ID, jobId })`.\n - Post a short comment confirming you triggered the review job (sanitize).\n - **Stop** further review actions.\n\n2) **If no such job exists, resolve which MR to review**:\n - If the event target is an MR \u2192 use its `iid`.\n - Else, parse the text for MR references in order:\n - `!<iid>` (e.g., `!123`)\n - `/-/merge_requests/<iid>` in a path or URL\n - full GitLab MR URL\n - If no MR can be resolved, reply with a brief comment asking the user to reference an MR (sanitize) and **stop**.\n\n3) **Single-Runner Guard (cancel any running \"agent-review\" job)** // NEW: Single-runner guard\n - Execute the **Single-Runner Guard** steps above **before** MR Review Mode.\n\n4) **Enter MR Review Mode**: execute the **MR Review Bundle** below with the resolved `mr_iid`.\n";
31
47
  };
32
- var eventWorkflow = function () {
33
- return "\n## High-Reliability Workflow (sequence + postconditions)\nFollow this order for any change work:\n\n1) **Acknowledge** with a short comment on the issue/MR thread.\n2) **Discover default branch** (e.g., \"main\") via MCP or API.\n3) **Create a working branch** from default (stable name, e.g., `fix/issue-<iid>-<slug>` or `feat/issue-<iid>-<slug>`).\n4) **Write changes \u2192 commit \u2192 push to remote branch.**\n5) **Verify push landed**:\n - Fetch latest commit on `source_branch`; record its short SHA.\n - Compare default vs `source_branch` and ensure `diffs.length > 0`.\n6) **Create or update MR** ONLY if there is a non-empty diff.\n - Include `Closes #<issue_iid>` in MR description when applicable.\n - Assign yourself to the MR.\n7) **Follow-up comment** with branch name, commit short SHA, files changed count, and MR link.\n8) **If verification fails**:\n - Do NOT create the MR.\n - Comment the exact failure and retry once with a fresh branch name. If still failing, comment and stop.\n\nFor Q&A-only (no code changes), just post a concise, helpful answer on the same issue/MR.\n";
48
+ /** Regular event workflow for non-review work */
49
+ var eventWorkflow = function (_a) {
50
+ var agentUserName = _a.agentUserName;
51
+ return "\n## High-Reliability Workflow (sequence + postconditions)\nFollow this order for any change work:\n\n1) **Acknowledge** with a short comment on the issue/MR thread (`create_note`), **unless the last actor is you**.\n2) **Discover default branch** (e.g., \"main\") \u2014 infer from repo/MR context if needed.\n3) **Create a working branch** from default (stable name, e.g., `fix/issue-<iid>-<slug>` or `feat/issue-<iid>-<slug>`) via `create_branch`.\n4) **Write changes \u2192 commit \u2192 push to remote branch** via `push_files` (or `create_or_update_file`).\n5) **Verify push landed**:\n - Fetch latest state (optional: `get_file_contents`/log) and capture a short SHA from the branch head if exposed by the host.\n - Compare default vs `source_branch` via `get_branch_diffs({ from: \"<default>\", to: \"<source>\" })` and ensure there are diffs.\n6) **Create or update MR** ONLY if there is a non-empty diff via `create_merge_request`.\n - Include `Closes #<issue_iid>` in MR description when applicable.\n - **Assign the MR to yourself**: `assigneeUsernames: [\"".concat(agentUserName, "\"]`.\n7) **Follow-up comment** with branch name, any commit short SHA you can obtain, files changed count (approx by diffs), and MR link via `create_note`, **unless the last actor is you**.\n8) **If verification fails**:\n - Do NOT create the MR.\n - Comment the exact failure and retry once with a fresh branch name. If still failing, comment and stop.\n\nFor Q&A-only (no code changes), just post a concise, helpful answer on the same issue/MR (sanitize first).\n");
34
52
  };
35
- // --- MR-specific sections ---
53
+ /* ---------- MR-review specific (shared with both prompts) ---------- */
36
54
  var mrScope = function (_a) {
37
55
  var agentUserName = _a.agentUserName;
38
- return "\n## Identity & Scope\n- Your GitLab username is \"".concat(agentUserName, "\".\n- This prompt runs in the context of ONE MR (no webhook).\n- You may review, comment, rebase, and push updates **to the MR's source branch**.\n- You must **never merge** the MR yourself.\n");
56
+ return "\n## Identity & Scope\n- Your GitLab username is \"".concat(agentUserName, "\".\n- This prompt runs in the context of ONE MR.\n- You may review, comment, and push updates **to the MR's source branch**.\n- You must **never merge** the MR yourself.\n");
39
57
  };
40
58
  var mrWorkflow = function () {
41
- return "\n## High-Reliability Review Workflow\nFollow this sequence with verification at each step:\n\n1) **Collect context**\n - Get MR metadata (source_branch, target_branch, state, draft/WIP).\n - Fetch the full changeset/diffs and open discussions (notes, threads, unresolved discussions).\n - Read existing reviews/comments to avoid duplication.\n - (Optional) Fetch recent CI pipeline(s) for this MR SHA/branch).\n\n2) **Code review**\n - Identify required changes (bugs, tests, style, security, perf, docs).\n - If no meaningful changes are needed:\n - Post a concise review comment summarizing findings.\n - Ask for review by a **recent active human contributor** (not you).\n\n3) **If changes are needed**\n - Post a short acknowledgment comment on the MR.\n - **Rebase** the MR onto the target/default branch (resolve trivial conflicts).\n - Implement minimal, safe changes; keep commits small and clear.\n - **Push** to the MR's **source_branch**.\n - **Verify push landed** (latest commit short SHA; compare target vs source shows diffs > 0).\n - Comment summarizing what changed and why.\n\n4) **CI pipeline**\n - Check pipeline status for the new commit on the MR branch.\n - Retry/re-run if allowed on flaky failures; fix minimal issues; push again if needed.\n - If still failing, comment with failure summary and next steps.\n\n5) **Assign human reviewer if ready**\n - If discussions are resolved and CI is passing (or running), request review from a recent active human contributor (not you).\n\n6) **Stdout summary**\n - Print concise summary: commits pushed (short SHAs), files changed count, discussions resolved/left, CI status, and requested reviewers.\n";
59
+ return "\n## High-Reliability Review Workflow\nFollow this sequence with verification at each step:\n\n1) **Collect context**\n - Get MR metadata via `get_merge_request({ projectId: $CI_PROJECT_ID, mergeRequestIid })`.\n - Fetch the full changeset/diffs via `get_merge_request_diffs` (or `list_merge_request_diffs`) and open discussions via `mr_discussions`.\n - Read existing notes to avoid duplication.\n\n2) **Code review**\n - Identify required changes (bugs, tests, style, security, perf, docs).\n - Always **post your review comments first** using `create_merge_request_note` (ack + concrete notes). Sanitize before sending.\n - Set an internal intent flag:\n - `will_push_changes = true` if you will modify code/config.\n - `will_push_changes = false` if it\u2019s commentary-only.\n\n3) **Implement changes after review is posted (only if `will_push_changes = true`)**\n - If needed, create the working branch from the target/default (or use existing MR source branch).\n - Apply minimal, safe changes; keep commits small and clear.\n - **Push** to the MR's **source branch** via `push_files` (or `create_or_update_file`).\n - **Verify push landed** using `get_branch_diffs({ from: \"<target_branch>\", to: \"<source_branch>\" })` and ensure there are diffs.\n - Post a follow-up MR note summarizing what changed and why (sanitize).\n";
42
60
  };
43
- var fallbackApiAuth = function () {
44
- return "\n## Fallback API Auth (if MCP lacks a method)\n- Base URL: `$CI_SERVER_URL/api/v4`\n- Project: `$CI_PROJECT_ID`\n- Header: `Private-Token: $GITLAB_PERSONAL_ACCESS_TOKEN`\n";
61
+ var ciInspection = function () {
62
+ return "\n4) **CI jobs (current pipeline focus: diagnose first, retry only when useful)**\n - Inspect jobs for the **current pipeline**: `$CI_PIPELINE_ID` via `list_pipeline_jobs`.\n - Consider **only** jobs with `status = \"failed\"` and `allow_failure = false`.\n - For each such job:\n 1. Retrieve details (id, name, stage, status, allow_failure, web_url).\n 2. Fetch job output via `get_pipeline_job_output({ projectId: $CI_PROJECT_ID, pipelineId: $CI_PIPELINE_ID, jobId })`.\n 3. **Classify the failure**:\n - **Code-related (do not retry):** compiler/type/lint/test/build script errors.\n - **Likely transient (may retry):** network/timeouts/infra/cache/artifacts/5xx/429/etc.\n 4. **Decision**:\n - If `will_push_changes = true`:\n - **Do not retry** current pipeline (upcoming push will trigger a new one).\n - Post an MR note: brief diagnosis per failed job; note a new pipeline will validate the fix (sanitize).\n - If `will_push_changes = false`:\n - If transient \u21D2 `retry_pipeline_job({ projectId: $CI_PROJECT_ID, jobId })` (or `retry_pipeline` if job-level retry not available). \n Post a note stating you retried and why (sanitize).\n - If code-related \u21D2 do not retry; post a note with diagnosis and suggested fix (sanitize).\n - Retry-once policy: at most **one** retry per job in this run.\n\n5) **Assign human reviewer if ready**\n - If discussions are resolved and blocking CI issues are addressed or clearly triaged, request review from a recent active human contributor (not you), if supported by your environment.\n\n6) **Stdout summary**\n - Print concise summary: branch used, files changed count (approx by diffs), discussions resolved/left, **blocking failed jobs (names + stages)** with classification (code vs transient), which jobs were retried (if any), and requested reviewers.\n";
45
63
  };
46
- // ---------- Public builders ----------
47
- var getEventPrompt = function (_a) {
64
+ var outputDisciplineMR = function (_a) {
48
65
  var agentUserName = _a.agentUserName;
49
- return "\nYou are a GitLab assistant bot. You receive ONE raw GitLab webhook JSON payload.\n\n".concat(header(), "\n---\nevent_json:\n$(cat $TRIGGER_PAYLOAD)\n---\n\n").concat(identity({
50
- agentUserName: agentUserName
51
- }), "\n").concat(goldenRules({
52
- agentUserName: agentUserName
53
- }), "\n").concat(eventSelfParse(), "\n").concat(eventWorkflow(), "\n").concat(commentGuidelines(), "\n").concat(mcpAndApi(), "\n").concat(outputDiscipline({
54
- agentUserName: agentUserName
55
- }), "\n");
66
+ return "\n## Output Discipline (MR)\n- Output only `gitlab-mcp` tool calls and the final plain-text summary.\n- Do **not** merge the MR yourself under any circumstance.\n- Never include \"@".concat(agentUserName, "\" in any body.\n");
67
+ };
68
+ /* ---------- Shared bundle for MR review ---------- */
69
+ var mrReviewBundle = function (ctx) {
70
+ return "\n## MR Review Mode (execute ONLY when review intent is detected and an MR IID is resolved)\nResolved MR IID: <set this to the resolved `mr_iid` before executing>\n".concat(mrScope(ctx), "\n").concat(mrWorkflow(), "\n").concat(ciInspection(), "\n");
71
+ };
72
+ /* ---------- Public builders ---------- */
73
+ var getEventPrompt = function (ctx) {
74
+ return "\nYou are a GitLab assistant bot. You receive ONE raw GitLab webhook JSON payload.\n\n".concat(header(), "\n---\nevent_json:\n$(cat $TRIGGER_PAYLOAD)\n---\n\n").concat(identity(ctx), "\n").concat(goldenRules(ctx), "\n").concat(selfMentionGuard(ctx), "\n").concat(eventSelfParse(), "\n").concat(singleRunnerGuard(), " <!-- NEW: included so the agent can run it when acting on an existing MR -->\n").concat(reviewOnDemandFromEvents(), "\n").concat(mrReviewBundle(ctx), " <!-- Included so the agent can execute it when review intent is true -->\n").concat(eventWorkflow(ctx), "\n").concat(commentGuidelines(), "\n").concat(mcpOnly(), "\n").concat(outputDiscipline(ctx), "\n");
56
75
  };
57
76
  exports.getEventPrompt = getEventPrompt;
58
- var getMergeRequestPrompt = function (_a) {
59
- var agentUserName = _a.agentUserName;
60
- return "\nYou are a GitLab assistant bot reviewing and updating a single Merge Request (MR).\n\n".concat(header(), "\n---\nmerge_request_iid: $CI_MERGE_REQUEST_IID\ntitle: $CI_MERGE_REQUEST_TITLE\ndescription: $CI_MERGE_REQUEST_DESCRIPTION\n---\n\n").concat(mrScope({
61
- agentUserName: agentUserName
62
- }), "\n").concat(goldenRules({
63
- agentUserName: agentUserName
64
- }), "\n").concat(mrWorkflow(), "\n").concat(commentGuidelines(), "\n").concat(mcpAndApi(), "\n").concat(fallbackApiAuth(), "\n## Output Discipline (MR)\n- Prefer `gitlab-mcp` tool calls; if unavailable, provide explicit REST calls (method, url, headers, body).\n- At the end, print a **plain-text** summary to STDOUT including:\n - `source_branch` and `target_branch`\n - commits pushed (short SHAs)\n - number of files changed\n - CI status/result\n - reviewers requested (if any)\n- Do **not** merge the MR yourself under any circumstance.\n");
77
+ var getMergeRequestPrompt = function (ctx) {
78
+ return "\nYou are a GitLab assistant bot reviewing and updating a single Merge Request (MR).\n\n".concat(header(), "\n---\nmerge_request_iid: $CI_MERGE_REQUEST_IID\ntitle: $CI_MERGE_REQUEST_TITLE\ndescription: $CI_MERGE_REQUEST_DESCRIPTION\n---\n\n").concat(mrScope(ctx), "\n").concat(goldenRules(ctx), "\n").concat(selfMentionGuard(ctx), "\n").concat(mrWorkflow(), "\n").concat(ciInspection(), "\n").concat(commentGuidelines(), "\n").concat(mcpOnly(), "\n").concat(outputDisciplineMR(ctx), "\n");
65
79
  };
66
80
  exports.getMergeRequestPrompt = getMergeRequestPrompt;
@@ -19,11 +19,11 @@ var createBaseAgentJob = function (context) {
19
19
  };
20
20
  };
21
21
  exports.createBaseAgentJob = createBaseAgentJob;
22
- exports.baseSetupScript = ["apk update", "apk add --no-cache git curl bash", "npm install -g @anthropic-ai/claude-code", "claude mcp add gitlab --env GITLAB_PERSONAL_ACCESS_TOKEN=$GITLAB_PERSONAL_ACCESS_TOKEN --env GITLAB_API_URL=$GITLAB_API_URL -- npx -y @zereight/mcp-gitlab"];
22
+ exports.baseSetupScript = ["apk update", "apk add --no-cache git curl bash", "npm install -g @anthropic-ai/claude-code", "claude mcp add gitlab --env GITLAB_PERSONAL_ACCESS_TOKEN=$GITLAB_PERSONAL_ACCESS_TOKEN --env GITLAB_API_URL=$GITLAB_API_URL --env USE_PIPELINE='true' -- npx -y @zereight/mcp-gitlab"];
23
23
  var callClaude = function (_a) {
24
24
  var prompt = _a.prompt;
25
25
  return ["export PROMPT=\"".concat((0, bashEscape_1.escapeNewlines)((0, bashEscape_1.escapeDoubleQuotes)((0, bashEscape_1.escapeBackTicks)(prompt))), "\""),
26
26
  //'echo "$PROMPT"',
27
- "claude -p \"$PROMPT\" --permission-mode acceptEdits --allowedTools \"Bash(*) Read(*) Edit(*) Write(*) mcp__gitlab\" --verbose --debug"];
27
+ "claude -p \"$PROMPT\" --permission-mode acceptEdits --allowedTools \"Bash(*) Bash(git checkout:*) Read(*) Edit(*) Write(*) mcp__gitlab\" --verbose --debug"];
28
28
  };
29
29
  exports.callClaude = callClaude;