← Catalog

@rubenjs/pi-gitlab-worker

GitLab issue automation for Pi: discover issues, create isolated worktrees, implement each issue with AI, commit, push and open merge requests serially.

Package

Install

Install with PiG

pig install npm:@rubenjs/pi-gitlab-worker

Install with Pi

pi install npm:@rubenjs/pi-gitlab-worker
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./extensions/gitlab-worker.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.2.0 (README.md). PiG does not review it.

pi-gitlab-worker

A Pi extension that turns a GitLab issue backlog into reviewed merge requests without babysitting: it discovers open issues, groups them into a handful of coherent merge requests, implements each work item with a nested Pi agent in one isolated git worktree per merge request, commits once per work item, pushes with GitLab push options (which opens the MR), and moves on to the next merge request — strictly one at a time.

Issue numbers are a reason to change code, not a boundary for a merge request: an MR is the review unit. Grouping follows the mr-grouping rules (cohesion, dependencies, sizing), and the whole plan is written and approved before any work starts, so an unattended run never stops halfway to ask a question.

Nothing lands on your default branch, nothing is merged automatically, and no work is ever thrown away without asking you.

CommandWhat it doesAI tokens
/gitlab authStore + validate a Personal (Free) or Project Access Tokenno
/gitlab statusToken, config, workspace and issue summaryno
/gitlab stopAbort a running work loopno
/check-storiesPlan MRs → worktree per MR → implement each item → commit per item → push → MRyes
/list-workspacesInventory of MR worktrees and their MR stateno
/cleanup-workspacesRemove clean worktrees whose MRs are mergedno
/create-storiesSplit TASK.md into GitLab issues, with feedback/review firstyes

1. Create an access token

Use whichever token your GitLab plan offers — the extension accepts both and stores them identically.

GitLab Free: Personal Access Token (the usual choice)

  1. Open your avatar → Edit profile → Access tokens (/-/user_settings/personal_access_tokens).
  2. Name it e.g. pi-gitlab-worker, set an expiry date.
  3. Scope: api. That is all you need — api covers the Issues / Merge requests REST calls and HTTPS pushes to your repositories.
  4. Create it and copy the glpat-… value (shown once).

A Personal Access Token acts as you: every issue comment and merge request is attributed to your account, and it can reach every project you are a member of. Because of that, keep it in ~/.pi/gitlab-token (which the extension does) and give it a short expiry.

Paid tiers: Project Access Token (least privilege)

Project → Settings → Access tokens → scopes api + write_repository, role Developer or higher. The bot user must be a project member; scope it to one project instead of your whole account.

Do I need write_repository?

Only for HTTPS pushes with a Project Access Token. git push over SSH authenticates with your SSH key, so the token never touches the push. The extension detects how your origin remote is configured and tells you which case applies after /gitlab auth.

Store and validate it

From your project root inside Pi:

/gitlab auth

Paste the token. It is validated with GET https://gitlab.com/api/v4/projects/:encodedProjectPath, then /gitlab auth reports the token's scopes, expiry and how pushes will authenticate, for example:

Token stored at /Users/you/.pi/agent/gitlab-token (chmod 600).
Project: you/student-manager, default branch: main.
Token check: token "pi-gitlab-worker" · scopes: api · expires 2026-01-01 (push over ssh).
Pushes go over SSH, so the token only needs API access (`api`).

The token is never written to .pi/gitlab-worker.json, never exported as an environment variable, and never passed on a command line — it only travels in the PRIVATE-TOKEN HTTP header and lives in ~/.pi/gitlab-token with mode 0600.

If ~/.pi/gitlab-token already holds a valid token, /gitlab auth reports success and exits (re-applying 0600). /gitlab auth clear removes the token. /gitlab status shows the stored token's scopes and expiry at any time.

Failure messages are specific:

GitLab responseMeaning
401token invalid, expired, or revoked — create a new one
403token lacks a required scope — add api (and write_repository for a Project token pushing over HTTPS)
404project path wrong, or the token's user/bot user is not a project member

The extension also warns (without failing) when a token expires within 14 days, and errors early when read_api-only tokens would break issue comments, or when an HTTPS push has no write capability.

2. Install

# from npm (after publishing)
pi install npm:@rubenjs/pi-gitlab-worker

# from a local checkout / directory
pi install ./pi-gitlab-worker

# try it for one session without installing
pi -e ./pi-gitlab-worker/extensions/gitlab-worker.ts

Then /reload if Pi is already running. pi list shows installed packages; pi remove npm:@rubenjs/pi-gitlab-worker uninstalls.

The package declares @earendil-works/pi-coding-agent as a peer dependency ("*"), which Pi supplies to extensions. Older Pi documentation still shows the pre-rename package name @mariozechner/pi-coding-agent; use the @earendil-works name with current Pi releases.

3. Configure .pi/gitlab-worker.json

Create the file at your project root (it contains no secrets, so it is safe to commit):

{
  "gitlab": {
    "projectPath": "cidt2/student-manager",
    "filter": "none"
  },
  "workspace": {
    "baseDir": "../workspaces",
    "cleanupRequiresMerged": true
  }
}
FieldDefaultMeaning
gitlab.projectPathrequirednamespace/project (nested groups fine). A web or clone URL is accepted and normalized — see below
gitlab.filter"none""none" = every open issue; "label:<name>" = only issues with that label
gitlab.apiBaseUrl"https://gitlab.com/api/v4"override for self-managed GitLab
workspace.baseDir"../workspaces"where worktrees are created, resolved relative to the project root
workspace.cleanupRequiresMergedtrue/cleanup-workspaces only removes worktrees whose MR is merged

gitlab.projectPath accepts any of these — they all normalize to cidt2/student-manager (this is the most common auth mistake, so it is handled instead of rejected):

cidt2/student-manager
cidt2/student-manager.git
https://gitlab.com/cidt2/student-manager
https://gitlab.com/cidt2/student-manager/-/issues/42
git@gitlab.com:cidt2/student-manager.git
ssh://git@gitlab.com:2222/cidt2/student-manager.git

A self-managed host in that URL also sets the API base URL (https://gitlab.example.com/group/project → https://gitlab.example.com/api/v4), so gitlab.apiBaseUrl is only needed behind a proxy or a non-standard path. An explicit apiBaseUrl always wins.

Deliberately absent: no testCommand, no lintCommand (the AI inspects the project instead), no token field.

The default branch is never hardcoded. It comes from GET /projects/:id (default_branch) and is used both as the worktree base (origin/<default-branch>) and as the MR target.

4. Example workflow

/gitlab auth                 # once per machine
/create-stories              # optional: TASK.md → GitLab issues (asks first)
/check-stories               # work through every open issue, serially
/list-workspaces             # see what is in flight
#   … review and merge the MRs on GitLab yourself …
/cleanup-workspaces          # delete worktrees whose MRs are merged

Plan first, then run unattended

Planning (one AI call, once). Open issues are grouped into a handful of coherent MRs following the mr-grouping rules — same layer or vertical slice together, unrelated features apart, dependency order, ~3–7 work items per MR. The plan is printed as a table, then you approve it, ask for a revision in writing, or edit the JSON by hand. Approval is the last question: after it the loop runs to completion unattended.

Then, per merge request of the plan:

  1. Skip check (no tokens spent). A work item is skipped when a local branch already matches its legacy per-issue slug (feat/…, fix/…, …), when an MR already exists for one of those branches, or when the local state file records it as pushed/investigated/failed. The MR itself is skipped when its own mr-<n>-<capability> branch or MR already exists.
  2. Create the worktree (pure code) — one per MR.
    git fetch origin --prune
    git worktree add <baseDir>/<project>-mr-<n>-<capability> -b mr-<n>-<capability> origin/<default-branch>
    
  3. Implement work item by work item (AI tokens). For each issue of the MR a nested pi --mode json process runs in the shared worktree. Its prompt names the capability, the sibling work items and what is already committed, so the agent stays inside its own slice and never reverts sibling work.
  4. Commit per work item (pure code).
    git add -A
    git commit -m "<type>: <summary> (#<iid>)"
    
    The conventional type still comes from a cheap classification call per issue (feat, fix, hotfix, chore); if the model call fails, keyword heuristics decide, then feat.
  5. Investigate instead of guessing. If one work item is ambiguous or too large, the agent posts a structured comment on the GitLab issue (POST /projects/:id/issues/:iid/notes) and the MR stops: a half-finished stack is never pushed. A worktree with no commits is removed again; one with commits is kept for inspection.
  6. Push once, open one MR (pure code).
    git push -u origin mr-<n>-<capability> \
      -o merge_request.create \
      -o merge_request.target=<default-branch> \
      -o merge_request.title="<capability>" \
      -o merge_request.description="<capability> — closes #74, #75. Work items: #74, #75."
    
    GitLab creates the MR from the push options, then the description is replaced through PUT /projects/:id/merge_requests/:iid with the full body: work items, why they share one MR, dependencies on earlier MRs, the commit list and the test commands the worker ran. The worktree stays for your review and the loop starts the next MR.

Restrict a run to specific issues:

/check-stories --iids 42,43

Stop a run with /gitlab stop (aborts the running agent and ends the loop after the current step) or by interrupting Pi.

5. Command reference

/gitlab auth [clear]

Prompts for a Personal Access Token (GitLab Free, scope api) or a Project Access Token (paid tiers, api + write_repository), validates it against gitlab.projectPath, and stores it at ~/.pi/gitlab-token (chmod 600). Reports the project's default branch, the token's scopes and expiry, and whether pushes use SSH or HTTPS. clear deletes the token. Requires an interactive session; headless runs fail with instructions instead of hanging.

When the project has no .pi/gitlab-worker.json yet, and you typed a project path or URL during auth, it offers to create that file for you with the normalized path.

/gitlab status

Prints: token file + mode, token health (scopes, expiry, push transport), project path and config location, filter, workspace base directory, loop state, local workspace counts by status, and (when a token is present) the project's default branch and open issue count.

/gitlab stop

Aborts the active work loop (SIGTERM to the child agent, SIGKILL after 5s).

/check-stories [--iids N,M]

Plans the merge requests, asks once for approval (approve / written feedback → revised plan / edit the plan JSON / cancel), then runs the whole stack serially. At the end it prints a summary grouped into merge requests, needs-your-input (investigations), skipped work items and failed MRs, with MR URLs.

/list-workspaces

Lists every directory under workspace.baseDir with its label (MR 3 for a grouped worktree, #42 for a legacy per-issue one), the work items it holds, branch, path, dirty flag and status:

StatusMeaning
in-progressworktree exists, nothing pushed yet
pushedan MR is open for the branch
mergedthe MR is merged
investigationa comment was posted, no branch/MR
failedthe last attempt failed (reason shown)
unknowndirectory is not a worktree / branch unknown

MR state is read live from GitLab when a token is available; otherwise the recorded local state is shown with a warning.

/cleanup-workspaces

For every worktree under workspace.baseDir:

  1. re-checks git status --porcelain — dirty worktrees are never removed (the path and reason are reported instead);
  2. with cleanupRequiresMerged: true (default), skips anything whose MR is not merged;
  3. otherwise runs git worktree remove <path> + git worktree prune and drops the local state record.

With cleanupRequiresMerged: true a token is required; with false cleanup works offline (still refusing dirty worktrees).

/create-stories

Reads TASK.md from the project root, asks a read-only nested Pi session (--tools read,grep,find,ls) to split it into discrete issues (title, description, optional labels), and prints the proposals. Then you get a menu instead of a yes/no box:

  • Create these issues — POST /projects/:id/issues for each one.
  • Give feedback and get a revised split — type what should change ("merge 3 and 4", "split the UI work out", "drop the migration issue") and the AI re-splits with your feedback, keeping what was already good. Loop as long as you like.
  • Edit the issues JSON myself — the proposals open in the editor as JSON; invalid JSON is rejected and the draft is kept.
  • Cancel — nothing is created.

Only after you approve does it create the issues and print the created URLs.

6. How the AI is used

  • Branch classification runs in-process through ctx.modelRegistry.complete(), with your session model: one small JSON answer per work item. On any failure the extension falls back to keyword heuristics, then feat, so the loop never stalls on a classification.
  • Grouping runs as a read-only child pi session (--tools read,grep,find,ls) whose prompt vendors the mr-grouping rules. It answers with a JSON plan that is parsed, validated (every work item in exactly one MR, dependencies resolved, cycles broken) and renumbered into dependency order before you see it. If the answer is unusable, each work item becomes its own MR and the plan says so instead of failing the run.
  • The issue split (/create-stories) runs the same way, and can be re-run with your written feedback until the split is right.
  • Implementation runs as a child pi --mode json process (process.execPath
    • the Pi entry point, so it works for npm installs and Bun binaries alike). It inherits your model, providers, skills and extensions. Because it runs in the MR worktree, every work item gets its own session file: pi -c inside a worktree resumes that work item's conversation.
  • Result contract. The worker is told to write one JSON object to ~/.pi/gitlab-worker/runs/<project>/issue-<iid>-<timestamp>.json (outside the worktree, so it can never be committed) and to repeat it in its final message. Fields: decision (implemented | investigation), branchType, summary, details, testsRun, investigationComment. The orchestrator falls back to the final message if the file is missing.
  • Test/lint commands are never hardcoded. The worker inspects package.json, pyproject.toml, Makefile, Cargo.toml, go.mod, .gitlab-ci.yml, … and runs what the project actually uses, recording the commands it ran.

7. Files on disk

PathContents
~/.pi/gitlab-tokentoken, mode 0600
~/.pi/gitlab-worker/<project>/state.jsonper-work-item status, MR index/capability, branch, worktree path, MR URL
~/.pi/gitlab-worker/runs/<project>/issue-<iid>-<ts>.jsonworker result contract
.pi/gitlab-worker.json (project)config, no secrets
<baseDir>/<project>-mr-<n>-<capability>/the worktree of one merge request
<baseDir>/<project>-story-<iid>-<slug>/legacy per-issue worktree (still listed and cleaned up)

State lives under the agent directory (never inside a worktree), and is advisory: /list-workspaces merges it with git worktree list and live MR state, so a stale or deleted state file degrades gracefully. Delete the project's state directory to force a clean slate.

8. Guardrails

RuleImplementation
Stay inside baseDirSlugs are validated against [a-z0-9-]+ and rejected if they contain /, \ or ..; the resolved path must pass both a lexical prefix check and a symlink-resolving containment check against baseDir
Never touch main/masterBranches are only created by git worktree add -b mr-<n>-<capability> origin/<default>; every git command runs with an explicit cwd; a guard rejects a computed branch equal to the default branch
Do not merge MRsThe extension never calls a merge endpoint; you merge
Refuse cleanup with uncommitted changesgit status --porcelain is re-checked immediately before removal; dirty worktrees are kept and reported
One merge request at a timeSequential for … await loop; one agent process at a time
Never push a half-finished stackWhen a work item fails or needs investigation, the MR stops and nothing is pushed; the worktree is kept when it holds commits
Stop after pushState flips to pushed, the loop continues with the next MR without revisiting this one
No token in config/env/argvToken (Personal or Project) is read from ~/.pi/gitlab-token per command and sent only as a PRIVATE-TOKEN header; child processes get no token
No hardcoded test/lint commandsThe worker inspects the repo and decides
Reject path traversalSee the first row; a directory whose real path escapes baseDir is never listed or removed

9. Requirements and assumptions

  • Pi ≥ 1.5 (extension API with registerCommand, ctx.modelRegistry.complete, pi.sendMessage).
  • git on PATH, and a repository whose origin points at the GitLab project you configured.
  • A token with the api scope: a Personal Access Token works on every plan (including GitLab Free), a Project Access Token on paid tiers. write_repository is only needed for HTTPS pushes with a Project Access Token.
  • Push credentials are yours to provide: an SSH key/agent key without an interactive passphrase prompt, or a credential helper. Pushes run with GIT_TERMINAL_PROMPT=0, so an unusable credential fails fast instead of hanging the loop.
  • Issues, not Epics/Work Items. "Stories" means the Issues API (/projects/:id/issues). Epics and Work Items are not used.
  • gitlab.com by default; set gitlab.apiBaseUrl for self-managed instances.
  • MR creation via push options (merge_request.create) is used; this needs a GitLab server that supports push options (gitlab.com does).
  • Default branch from the API, never hardcoded.
  • Platform: macOS primary, Linux expected to work. No platform-specific commands are used beyond SIGTERM/SIGKILL process handling. Session persistence is Pi's/Zellij's business (run Pi inside Zellij as usual) and sleep prevention stays with your existing caffeinate/caffeine setup — this extension does not install or recommend anything else.

10. Troubleshooting

SymptomCause / fix
No GitLab token foundrun /gitlab auth
401 on any commandtoken expired/revoked — /gitlab auth clear then /gitlab auth
403Personal token: add the api scope. Project token: add api + write_repository
404 on /projects/...wrong gitlab.projectPath — note a https://gitlab.com/… web URL in your config is normalized automatically, so a 404 means the namespace/project itself is wrong — or the token's owner is not a project member
Push rejectedprotected branch, insufficient role, or an HTTPS push with a token that lacks write_repository; the loop marks the issue failed and keeps the commit in the worktree
read_api-only tokenit cannot post issue comments or create issues; recreate it with api
the worker produced no changesthe agent finished without modifying the worktree for that work item; the MR stops and the worktree is kept for inspection
MR N stopped at #xone work item of the MR failed or needed investigation, so the rest of that MR was not attempted and nothing was pushed
merge request already exists for mr-<n>-…the MR for that capability already exists; re-run after merging, or delete the branch to redo it
Push succeeded but no MRserver rejects push options; open the MR manually from the pushed branch
worktree path already existsleftover directory — inspect it, then git worktree remove it or delete the folder
/cleanup-workspaces refusesuncommitted changes (commit/stash them) or MR not merged
Loop seems stuck/gitlab stop; check for an interactive SSH key passphrase by pushing manually once
Stale statusesdelete ~/.pi/gitlab-worker/<project>/ and re-run /list-workspaces

11. Development

npm run typecheck     # tsc --noEmit (needs @types/node + the Pi package, both dev-only)
npm test              # 83 offline checks: helpers, git layer, workspaces, grouping, work loop

Releasing: bump package.json, commit, and push a matching v<version> tag. .gitlab-ci.yml runs the suites and publishes to npm on that tag only — see TESTPLAN.md for the token setup and checklist.

Layout:

pi-gitlab-worker/
├── package.json            # pi manifest, peer deps, keywords: ["pi-package"]
├── extensions/
│   └── gitlab-worker.ts    # command registration + UI + orchestration entry
├── src/
│   ├── agent.ts            # nested `pi --mode json` runner, classifier, result parsing
│   ├── auth.ts             # ~/.pi/gitlab-token read/write (0600)
│   ├── config.ts           # .pi/gitlab-worker.json loading + validation
│   ├── exec.ts             # child-process helpers (env control, streaming, timeouts)
│   ├── git.ts              # fetch / worktree / status / commit / push
│   ├── gitlab.ts           # fetch-based GitLab REST client
│   ├── grouping.ts         # mr-grouping rules → validated MR plan
│   ├── paths.ts            # symlink-safe path canonicalization + containment
│   ├── prompt.ts           # implementation + classification prompts, result schema
│   ├── review.ts           # approve / feedback / edit-JSON / cancel loop
│   ├── slug.ts             # slug generation, branch names, worktree paths
│   ├── state.ts            # per-project state file under the agent dir
│   ├── stories.ts          # TASK.md → issue proposals → creation
│   ├── workloop.ts         # the serial MR work loop
│   └── workspaces.ts       # inventory + guarded cleanup
└── tests/                  # offline smoke, git-layer, workspaces-layer, grouping-layer, workloop-layer

See TESTPLAN.md for how to verify every command without touching a project you care about.