Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(gitlab): ask glab for JSON with --output, not the -F shorthand that returns a table
Adam Eivy30edd9ec60be
diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxindex a40988500c..b528ad6806 100644--- a/client/src/components/apps/tabs/IssuesTab.jsx+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -388,7 +388,12 @@ export default function IssuesTab({ appId, appName }) {const forgeLabel = FORGE_LABEL[data?.forge] || 'Issues';// A transient failure keeps the "couldn't ask" framing — never the lie that- // the tracker is empty.+ // the tracker is empty. The SENTENCE comes from the server, beside the+ // classifier that produced the reason: the reason vocabulary is open-ended+ // (`gh-${status}`), and only the classifier knows whether the forge was+ // unreachable or merely answered in a dialect we couldn't parse. A client-side+ // reason→copy table can only shadow one entry of that, which is how an+ // authenticated user got told to authenticate.const unavailable = data?.transient === true;return (@@ -514,8 +519,8 @@ export default function IssuesTab({ appId, appName }) {{!error && unavailable && (<Banner tone="warning" size="md" icon={AlertTriangle}>- Couldn't reach {forgeLabel} ({data.reason})- {data.remedy ? ` — ${data.remedy}.` : ' — retry once the CLI is authenticated.'}+ {data.headline || `Couldn't reach ${forgeLabel}`} ({data.reason})+ {data.remedy ? ` — ${data.remedy}.` : ''}</Banner>)}diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsxindex 47283c96ec..2ee8ed5c42 100644--- a/client/src/components/apps/tabs/IssuesTab.test.jsx+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx@@ -376,7 +376,7 @@ describe('IssuesTab', () => {it('says "couldn\'t reach" for a transient failure — never "no open issues"', async () => {api.getAppIssues.mockResolvedValue({forge: 'github', fullName: 'acme/widget', issues: [],- reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login',+ reason: 'gh-unauthenticated', transient: true, headline: null, remedy: 'run gh auth login',});await renderTab();@@ -385,6 +385,40 @@ describe('IssuesTab', () => {expect(screen.queryByText(/No open issues on this tracker/)).not.toBeInTheDocument();});+ it('renders the server\'s headline verbatim instead of inferring one from the reason', async () => {+ // A glab whose JSON output flag moved answers with its human table at exit 0+ // — reachable, just unreadable. Only the server-side classifier can tell+ // those apart, so it ships the sentence; the client must not second-guess it+ // with a reason table, which is how an authenticated user got told to+ // authenticate.+ api.getAppIssues.mockResolvedValue({+ forge: 'gitlab', fullName: 'group/proj', issues: [],+ reason: 'glab-output-not-json', transient: true,+ headline: "Reached GitLab, but couldn't read its answer",+ remedy: 'update `glab` — its JSON output flag moved (check `glab issue list --help`)',+ });+ await renderTab();++ expect(await screen.findByText(/Reached GitLab, but couldn't read its answer/)).toBeInTheDocument();+ expect(screen.getByText(/its JSON output flag moved/)).toBeInTheDocument();+ expect(screen.queryByText(/Couldn't reach GitLab/)).not.toBeInTheDocument();+ expect(screen.queryByText(/retry once the CLI is authenticated/)).not.toBeInTheDocument();+ expect(screen.queryByText(/No open issues on this tracker/)).not.toBeInTheDocument();+ });++ it('falls back to the reachability framing when the server ships no headline', async () => {+ // Older reasons (and any the server adds without copy) still read sensibly+ // rather than rendering a blank banner.+ api.getAppIssues.mockResolvedValue({+ forge: 'gitlab', fullName: 'group/proj', issues: [],+ reason: 'some-new-reason', transient: true, headline: null, remedy: null,+ });+ await renderTab();++ expect(await screen.findByText(/Couldn't reach GitLab/)).toBeInTheDocument();+ expect(screen.getByText(/some-new-reason/)).toBeInTheDocument();+ });+it('explains a non-forge origin instead of showing an empty list', async () => {api.getAppIssues.mockResolvedValue({forge: null, fullName: null, issues: [], reason: 'unsupported-forge', transient: false, remedy: null,diff --git a/server/lib/README.md b/server/lib/README.mdindex 538c47e094..e9e6d93b68 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -217,6 +217,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). || `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. || `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |+| `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. || `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. || `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |diff --git a/server/lib/glabArgs.js b/server/lib/glabArgs.jsnew file mode 100644index 0000000000..c43fb56256--- /dev/null+++ b/server/lib/glabArgs.js@@ -0,0 +1,35 @@+/**+ * Pure argv conventions for the GitLab CLI (`glab`) — no child-process access,+ * so the three runners that drive `glab` (services/gitlab.js#execGlab,+ * perpetualWork.js#runCli, layeredIntelligence/runCli.js) can share one+ * definition without inheriting each other's timeout policy. Mirrors+ * `cliProviderArgs.js` / `gitArgs.js`.+ */++/**+ * The ONE spelling of "answer in JSON" that every `glab` subcommand accepts.+ *+ * `-F json` is a trap, and it is the trap PortOS fell into: `-F` does NOT mean+ * the same thing on every subcommand. On `mr list`, `mr view`, `issue view`,+ * `repo view` and `label list`, `-F` is the shorthand for `--output`+ * (text|json). On `glab issue list` it is the shorthand for a DIFFERENT flag,+ * `--output-format` (details|ids|urls), while `--output` selects text|json and+ * carries the shorthand `-O`. So `glab issue list -F json` is accepted,+ * silently ignored, and answers with the HUMAN TABLE at exit 0 — which every+ * caller parsed as "couldn't fetch", reporting an authentication problem to a+ * user whose `glab` was authenticated the whole time.+ *+ * The long `--output json` form means text-vs-json on all of them, so it is the+ * only form PortOS code uses. `glab mr list --state <x>` is the sibling trap:+ * there is no `--state` flag on `mr list` at all — state is selected by+ * presence flags (`--merged`, `--closed`, `--all`) and defaults to open.+ * `server/services/gitlab.glabFlags.test.js` walks the tree and fails on either+ * spelling, so this comment is enforced rather than merely asserted.+ *+ * Frozen because it is shared by every `glab` invocation in the process — an+ * importer that pushed onto it would poison all of them.+ */+export const GLAB_JSON_ARGS = Object.freeze(['--output', 'json']);++/** `args` plus the JSON output flag. See GLAB_JSON_ARGS for why not `-F json`. */+export const withGlabJson = (args) => [...args, ...GLAB_JSON_ARGS];diff --git a/server/lib/glabArgs.test.js b/server/lib/glabArgs.test.jsnew file mode 100644index 0000000000..ec4b7b11aa--- /dev/null+++ b/server/lib/glabArgs.test.js@@ -0,0 +1,42 @@+/**+ * The `glab` argv contract. One assertion per claim the module's doc makes —+ * the tree-wide enforcement that nobody re-spells the flag lives in+ * `server/services/gitlab.glabFlags.test.js`.+ */++import { describe, it, expect } from 'vitest';+import { GLAB_JSON_ARGS, withGlabJson } from './glabArgs.js';++describe('GLAB_JSON_ARGS', () => {+ it('is the long --output form, never the per-subcommand `-F` shorthand', () => {+ // `-F` is `--output-format` (details|ids|urls) on `glab issue list` and+ // `--output` (text|json) everywhere else, so the shorthand silently returns+ // the human table there. `--output` means text-vs-json on every subcommand.+ expect(GLAB_JSON_ARGS).toEqual(['--output', 'json']);+ });++ it('is frozen — it is shared by every glab invocation in the process', () => {+ expect(Object.isFrozen(GLAB_JSON_ARGS)).toBe(true);+ });+});++describe('withGlabJson', () => {+ it('appends the JSON flag', () => {+ expect(withGlabJson(['issue', 'list', '--per-page', '100']))+ .toEqual(['issue', 'list', '--per-page', '100', '--output', 'json']);+ });++ it("does not mutate the caller's args", () => {+ const args = ['issue', 'list'];+ withGlabJson(args);+ expect(args).toEqual(['issue', 'list']);+ });++ it('returns a fresh array each call, so one call site cannot poison another', () => {+ const a = withGlabJson(['mr', 'list']);+ const b = withGlabJson(['mr', 'list']);+ expect(a).not.toBe(b);+ a.push('--merged');+ expect(b).toEqual(['mr', 'list', '--output', 'json']);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex d166814842..a0b3b7881b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -210,6 +210,7 @@ export * from './ffmpegRenderGuard.js';export * from './gitArgs.js';export * from './gitCommitProbe.js';export * from './gitForge.js';+export * from './glabArgs.js';export * from './gitOutputParsers.js';export * from './gitRemote.js';export * from './githubRepoUrl.js';diff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex b80267a4d2..bc90be1980 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -276,7 +276,7 @@ ${forgeLabelContract}gitlab: `This app tracks autonomous work in **GitLab Issues** (via the \`glab\` CLI), NOT PLAN.md — do NOT edit PLAN.md.-- **Inventory:** From {repoPath}, confirm the forge (\`glab repo view\`) and list existing ${label} issues so you don't duplicate: \`glab issue list --label ${issueLabel} --per-page 100 -F json\` (also scan titles for the \`[${slugPrefix}…]\` slug). Collect the existing slugs. If \`glab\` is not authenticated or the remote is not GitLab, exit cleanly.+- **Inventory:** From {repoPath}, confirm the forge (\`glab repo view\`) and list existing ${label} issues so you don't duplicate: \`glab issue list --label ${issueLabel} --per-page 100 --output json\` (also scan titles for the \`[${slugPrefix}…]\` slug). Collect the existing slugs. If \`glab\` is not authenticated or the remote is not GitLab, exit cleanly.- **Record** each NEW proposal as a GitLab issue. Do not relabel or edit an existing issue you skipped as a duplicate. Keep the \`[<slug>]\` inventory tag in the title so later runs can de-duplicate; do NOT add \`[category]\` / \`[SEVERITY]\` / \`[model:…]\` / \`[effort:…]\` prefixes (those belong in labels).1. Ensure each label you will apply exists. Create the category label first (\`glab label create --name ${issueLabel} --color "#0366D6" --description "${labelDescription}" 2>/dev/null || true\`) and the same for \`plan\`. Then create each justified dispatch-hint label immediately before applying it (glab needs \`--name\` and \`#<hex>\`).2. ${DISPATCH_HINT_GUIDANCE.split('\n').join('\n ')}diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 3eb8d3fae6..0a5e8178e4 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -2553,7 +2553,7 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'? ` PR_URL=$(glab mr create --source-branch ${branch} --target-branch ${base} --title "<conventional title>" --description "<description>" | grep -Eo 'https?://[^[:space:]]+' | tail -n 1)`: ` PR_URL=$(gh pr create --base ${base} --head ${branch} --title "<conventional title>" --body "<description>")`,gitlab- ? ' PR_NUMBER=$(glab mr view "$PR_URL" -F json | jq -r .iid)'+ ? ' PR_NUMBER=$(glab mr view "$PR_URL" --output json | jq -r .iid)': ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',' ```',// `--fill` on a one-line commit produces an empty description; PortOS useddiff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex aff030bd57..700951a3cb 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -704,7 +704,7 @@ describe('buildLightContextPrompt', () => {{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });expect(prompt).toMatch(/PR_URL=\$\(glab mr create --source-branch claim\/issue-4363 --target-branch main/);- expect(prompt).toMatch(/PR_NUMBER=\$\(glab mr view "\$PR_URL" -F json \| jq -r \.iid\)/);+ expect(prompt).toMatch(/PR_NUMBER=\$\(glab mr view "\$PR_URL" --output json \| jq -r \.iid\)/);expect(prompt).toMatch(/glab mr diff \$PR_NUMBER/);expect(prompt).toMatch(/glab mr merge "\$PR_NUMBER" --yes --remove-source-branch/);expect(prompt).toMatch(/glab mr view "\$PR_NUMBER"/);diff --git a/server/services/appIssues.js b/server/services/appIssues.jsindex fd7dca47d7..add1e804bb 100644--- a/server/services/appIssues.js+++ b/server/services/appIssues.js@@ -18,12 +18,13 @@** Sentinel discipline (CLAUDE.md): "couldn't ask the forge" never collapses into* "there are no issues". A failed probe returns `issues: []` WITH- * `transient: true` and a `reason`, so the UI says "couldn't load" instead of- * the lie "no open issues".+ * `transient: true`, a `reason`, and the `headline`/`remedy` that describe it, so+ * the UI says "couldn't load" instead of the lie "no open issues" — and says WHY+ * without guessing, since the classifier is the only thing that knows.*/import { execGh, ensureForgeReachable } from './github.js';-import { execGlab } from './gitlab.js';+import { execGlabJson } from './gitlab.js';import { resolveAppForgeTarget } from '../lib/workTracker.js';import { safeJSONParse } from '../lib/fileUtils.js';@@ -67,11 +68,11 @@ function normalizeGithubIssue(issue) {}/**- * Normalize a raw `glab issue list -F json` row. GitLab keys the number on+ * Normalize a raw `glab issue list --output json` row. GitLab keys the number on* `iid` and assignees/author on `username`. Labels are plain strings on current- * `glab`, but the object form is tolerated too — the `-F json` label shape has- * varied across glab versions, and a silently-dropped label list is worse than- * an unused branch.+ * `glab`, but the object form is tolerated too — the JSON label shape has varied+ * across glab versions, and a silently-dropped label list is worse than an+ * unused branch.*/function normalizeGitlabIssue(issue) {return {@@ -95,14 +96,11 @@ function normalizeGitlabIssue(issue) {}/**- * Shared tail of both fetchers: parse the CLI's JSON and classify the answer.- * The absent-vs-empty split is the whole point — an unparseable/failed read is- * `fetch-failed` + transient, while a CLI that answered with zero rows is the- * definitive `no-open-issues`.+ * Classify an ANSWERED row list. The absent-vs-empty split is the whole point —+ * a CLI that answered with zero rows is the definitive `no-open-issues`, never+ * conflated with a read we couldn't make.*/-function toIssueResult(raw, normalize) {- const rows = safeJSONParse(raw, null);- if (!Array.isArray(rows)) return { issues: [], reason: 'fetch-failed', transient: true };+function toIssueResult(rows, normalize) {return { issues: rows.map(normalize), reason: rows.length ? 'ok' : 'no-open-issues', transient: false };}@@ -117,8 +115,8 @@ async function fetchGithubIssues(repoSpec, apiHost) {if (!forge.ok) {return { issues: [], reason: `gh-${forge.status}`, transient: true, remedy: forge.remedy || null };}- // execGh REJECTS on failure (execGlab resolves null), so this catch is what- // makes the two fetchers share the same "raw or null" contract below.+ // execGh REJECTS on failure; normalize to null so the parse below is the only+ // guard.const raw = await execGh(['issue', 'list', '--repo', repoSpec, '--state', 'open','--limit', String(GH_LIST_LIMIT),@@ -127,17 +125,43 @@ async function fetchGithubIssues(repoSpec, apiHost) {console.error(`❌ app-issues: gh issue list failed for ${repoSpec}: ${err.message}`);return null;});- return toIssueResult(raw, normalizeGithubIssue);+ const rows = safeJSONParse(raw, null);+ if (!Array.isArray(rows)) {+ return {+ issues: [], reason: 'fetch-failed', transient: true,+ headline: 'Couldn\'t read GitHub\'s issue list',+ remedy: 'run `gh issue list` in the repo to see what gh reports',+ };+ }+ return toIssueResult(rows, normalizeGithubIssue);}/*** Open issues from GitLab. `glab` resolves the project from the origin remote in* its working directory, so every call runs in `repoPath`.+ *+ * glab's two failure modes get two different sentences, because they send the+ * user to two different places: `cli-failed` really can be an unauthenticated or+ * unreachable CLI, while `not-json` means glab answered fine and only its output+ * flags moved. Collapsing the latter into the reachability framing is what told+ * an authenticated user to "retry once the CLI is authenticated".*/async function fetchGitlabIssues(repoPath) {// `glab issue list` defaults to OPEN issues.- const raw = await execGlab(['issue', 'list', '--per-page', String(GL_PER_PAGE), '-F', 'json'], repoPath);- return toIssueResult(raw, normalizeGitlabIssue);+ const { rows, reason } = await execGlabJson(['issue', 'list', '--per-page', String(GL_PER_PAGE)], repoPath);+ if (rows) return toIssueResult(rows, normalizeGitlabIssue);+ if (reason === 'not-json') {+ return {+ issues: [], reason: 'glab-output-not-json', transient: true,+ headline: "Reached GitLab, but couldn't read its answer",+ remedy: 'update `glab` — its JSON output flag moved (check `glab issue list --help`)',+ };+ }+ return {+ issues: [], reason: 'fetch-failed', transient: true,+ headline: "Couldn't reach GitLab",+ remedy: 'check `glab auth status` and that `glab` is installed and can reach the host',+ };}/**@@ -163,10 +187,10 @@ async function fetchGitlabIssues(repoPath) {* refuses to list anything for those, since a claim wouldn't touch it.** @param {object} app - managed app record (needs `repoPath`, `workTracker`)- * @returns {Promise<{forge:'github'|'gitlab'|null, tracker:string|null, fullName:string|null, issues:object[], reason:string, transient:boolean, remedy:string|null}>}+ * @returns {Promise<{forge:'github'|'gitlab'|null, tracker:string|null, fullName:string|null, issues:object[], reason:string, transient:boolean, headline:string|null, remedy:string|null}>}*/export async function listAppIssues(app) {- const base = { forge: null, tracker: null, fullName: null, issues: [], transient: false, remedy: null };+ const base = { forge: null, tracker: null, fullName: null, issues: [], transient: false, headline: null, remedy: null };if (!app?.repoPath) return { ...base, reason: 'no-repo-path' };const { tracker, target } = await resolveAppForgeTarget(app);@@ -192,6 +216,10 @@ export async function listAppIssues(app) {issues: result.issues,reason: result.reason,transient: result.transient,+ // Headline + remedy ride WITH the reason, so the sentence and the state it+ // describes cannot drift apart across the HTTP boundary (mirrors+ // github.js#ghRemedy). The client renders them; it never re-derives them.+ headline: result.headline || null,remedy: result.remedy || null,};}diff --git a/server/services/appIssues.test.js b/server/services/appIssues.test.jsindex 51287c4830..daadf74d23 100644--- a/server/services/appIssues.test.js+++ b/server/services/appIssues.test.js@@ -5,7 +5,7 @@ vi.mock('./github.js', () => ({execGh: vi.fn(async () => '[]'),ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),}));-vi.mock('./gitlab.js', () => ({ execGlab: vi.fn(async () => '[]') }));+vi.mock('./gitlab.js', () => ({ execGlabJson: vi.fn(async () => ({ rows: [], reason: 'ok' })) }));// gitRemote is the only effectful dependency of the real forge classifier, so// mock IT and let `resolveRepoForgeTarget` run for real — the github-vs-gitlab// routing under test is exactly that mapping.@@ -20,7 +20,7 @@ vi.mock('../lib/fileUtils.js', () => ({import { listAppIssues } from './appIssues.js';import { execGh } from './github.js';-import { execGlab } from './gitlab.js';+import { execGlabJson } from './gitlab.js';import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';// `workTracker: 'auto'` resolves to whatever the origin host is — the common case.@@ -38,7 +38,7 @@ beforeEach(() => {getOriginInfo.mockResolvedValue({ isGithub: true, host: 'github.com', fullName: 'acme/widget' });readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');execGh.mockResolvedValue('[]');- execGlab.mockResolvedValue('[]');+ execGlabJson.mockResolvedValue({ rows: [], reason: 'ok' });});describe('listAppIssues — GitHub', () => {@@ -131,7 +131,7 @@ describe('listAppIssues — GitHub', () => {describe('listAppIssues — GitLab', () => {it('normalizes iid / description / string labels / username assignees', async () => {useGitlabOrigin();- execGlab.mockResolvedValue(JSON.stringify([{+ execGlabJson.mockResolvedValue({ reason: 'ok', rows: [{iid: 7,title: 'Add export',description: 'We need CSV',@@ -143,7 +143,7 @@ describe('listAppIssues — GitLab', () => {milestone: { title: 'Sprint 3' },created_at: '2026-02-01T00:00:00Z',updated_at: '2026-02-02T00:00:00Z',- }]));+ }] });const result = await listAppIssues(APP);@@ -161,14 +161,37 @@ describe('listAppIssues — GitLab', () => {{ name: 'p2', color: null, description: '' },]);// glab resolves the project from its cwd, so the repo path is load-bearing.- expect(execGlab.mock.calls[0][1]).toBe('/repo');+ expect(execGlabJson.mock.calls[0][1]).toBe('/repo');+ // execGlabJson owns the output flag (lib/glabArgs.js); callers pass none.+ expect(execGlabJson.mock.calls[0][0]).toEqual(['issue', 'list', '--per-page', '100']);});- it('a null glab result (CLI missing / timed out) is transient', async () => {+ it('a failed glab call (CLI missing / unauthenticated / timed out) is transient', async () => {useGitlabOrigin();- execGlab.mockResolvedValue(null);+ execGlabJson.mockResolvedValue({ rows: null, reason: 'cli-failed' });const result = await listAppIssues(APP);expect(result).toMatchObject({ forge: 'gitlab', reason: 'fetch-failed', transient: true });+ // Every transient answer carries its own sentence — the client has no+ // fallback advice to guess with.+ expect(result.headline).toMatch(/Couldn't reach GitLab/);+ expect(result.remedy).toMatch(/glab auth status/);+ });++ it('a glab that ANSWERED with non-JSON gets its own headline + remedy, not the re-auth advice', async () => {+ useGitlabOrigin();+ execGlabJson.mockResolvedValue({ rows: null, reason: 'not-json' });+ const result = await listAppIssues(APP);+ expect(result).toMatchObject({ forge: 'gitlab', reason: 'glab-output-not-json', transient: true });+ // The sentence ships WITH the reason so the client never re-derives it.+ expect(result.headline).toMatch(/Reached GitLab/);+ expect(result.remedy).toMatch(/update `glab`/);+ });++ it('an ANSWERED empty list is the definitive no-open-issues, not a failed read', async () => {+ useGitlabOrigin();+ execGlabJson.mockResolvedValue({ rows: [], reason: 'ok' });+ const result = await listAppIssues(APP);+ expect(result).toMatchObject({ forge: 'gitlab', reason: 'no-open-issues', transient: false, issues: [] });});});@@ -177,7 +200,7 @@ describe('listAppIssues — non-forge apps', () => {const result = await listAppIssues({ id: 'app-2', name: 'No Repo' });expect(result).toMatchObject({ forge: null, reason: 'no-repo-path', transient: false, issues: [] });expect(execGh).not.toHaveBeenCalled();- expect(execGlab).not.toHaveBeenCalled();+ expect(execGlabJson).not.toHaveBeenCalled();});it('an unrecognized origin falls back to PLAN.md, which has no forge issue list', async () => {@@ -221,10 +244,10 @@ describe('listAppIssues — non-forge apps', () => {it('lists issues for a gitlab tracker explicitly pinned on a custom-hostname self-hosted origin', async () => {getOriginInfo.mockResolvedValue({ isGithub: false, host: 'git.example-corp.com', fullName: 'acme/widget' });readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');- execGlab.mockResolvedValue(JSON.stringify([{ iid: 3, title: 'Custom host works', labels: [], assignees: [] }]));+ execGlabJson.mockResolvedValue({ reason: 'ok', rows: [{ iid: 3, title: 'Custom host works', labels: [], assignees: [] }] });const result = await listAppIssues({ ...APP, workTracker: 'gitlab' });expect(result).toMatchObject({ forge: 'gitlab', tracker: 'gitlab', reason: 'ok' });- expect(execGlab.mock.calls[0][1]).toBe('/repo');+ expect(execGlabJson.mock.calls[0][1]).toBe('/repo');});});@@ -252,7 +275,7 @@ describe('listAppIssues — the list must match the tracker a claim would use',const result = await listAppIssues({ ...APP, workTracker: 'gitlab' });expect(result).toMatchObject({ forge: null, tracker: 'gitlab', reason: 'tracker-forge-mismatch' });expect(execGh).not.toHaveBeenCalled();- expect(execGlab).not.toHaveBeenCalled();+ expect(execGlabJson).not.toHaveBeenCalled();});it('honors an explicit github pin on a GitHub remote', async () => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 237c6c6f7a..52d44947d8 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -236,7 +236,7 @@ const COLLABORATOR_FORGE = {who: 'project members (direct, or inherited from the project\'s group)',membersCmd: 'glab api --paginate "projects/:id/members/all" -q ".[].username"',selfCmd: 'glab api user -q .username',- listHint: 'list open issues WITHOUT `--author` (`glab issue list -F json`, whose payload already carries the author) and keep only issues whose `.author.username`',+ listHint: 'list open issues WITHOUT `--author` (`glab issue list --output json`, whose payload already carries the author) and keep only issues whose `.author.username`',verb: 'opened',failHint: 'the account lacks access to the member list, or `glab` is unauthenticated'}diff --git a/server/services/gitlab.glabFlags.test.js b/server/services/gitlab.glabFlags.test.jsnew file mode 100644index 0000000000..791523a913--- /dev/null+++ b/server/services/gitlab.glabFlags.test.js@@ -0,0 +1,116 @@+/**+ * Tree-wide guard on the two `glab` flag traps.+ *+ * Both cost real user-visible time before this existed, and both are invisible+ * in review because the wrong spelling LOOKS like the right one:+ *+ * 1. `-F json` on `glab issue list`. `-F` is not one flag across subcommands:+ * on `mr list` / `mr view` / `issue view` / `repo view` / `label list` it is+ * the shorthand for `--output` (text|json), but on `issue list` it is+ * `--output-format` (details|ids|urls) while `--output` carries `-O`. So+ * `glab issue list -F json` is accepted, IGNORED, and answers with the+ * human table at exit 0 — parsed as "couldn't fetch", which is how the app+ * Issues tab told a user with a working, authenticated `glab` to+ * authenticate it.+ * 2. `--state <x>` on `glab mr list`. That flag does not exist; state is+ * selected by presence flags (`--merged`, `--closed`, `--all`) and defaults+ * to open. It exited non-zero on every call, so the GitLab arm of the+ * zombie-issue reconcile scan skipped every cycle in silence.+ *+ * Per-caller argv assertions cannot cover this: the offenders were spread over+ * five modules and three different CLI runners, and a NEW call site is exactly+ * when the guard needs to fire. So this walks the whole server tree rather than+ * listing known files — the same discover-don't-enumerate shape as+ * `spawnCwd.test.js` and `cliChildEnv.test.js`.+ */++import { describe, it, expect } from 'vitest';+import { collectServerSources, readServerSource } from '../lib/testHelper.js';++// `-F json` as CODE — an argv array element pair, either quote style. Prompt+// prose spells it `-F json` (space-separated inside a template literal), so this+// pattern is naturally scoped to real call sites.+const ARGV_SHORTHAND_JSON = /(['"])-F\1\s*,\s*(['"])json\2/;++// `glab issue list … -F json` as TEXT — the shell form handed to an agent in a+// prompt, on one line.+const PROSE_ISSUE_LIST_SHORTHAND = /glab\s+issue\s+ls?i?s?t?\b[^\n]*?(?:^|\s)-F\s+json/m;++// `glab mr list --state <x>`, in either code or prose.+const PROSE_MR_LIST_STATE = /glab\s+mr\s+ls?i?s?t?\b[^\n]*?--state\b/m;+const ARGV_MR_LIST_STATE = /(['"])mr\1\s*,\s*(['"])list\2[^\n]*?(['"])--state\3/;++/**+ * Drop the parts of a source file that only TALK about the traps, so a comment+ * explaining the flag collision (this file, lib/glabArgs.js, issueReconcile.js)+ * doesn't read as an instance of it. Deliberately conservative: JSDoc blocks and+ * comment-only lines, nothing else — over-stripping would hide a real offender,+ * which is the failure that matters here. Prompt bodies live in template+ * literals, so they survive untouched.+ */+const stripCommentary = (src) => src+ .replace(/\/\*\*[\s\S]*?\*\//g, '')+ .split('\n')+ .filter((line) => !/^\s*(\/\/|\*)/.test(line))+ .join('\n');++const PATTERNS = [+ ['-F json argv pair', ARGV_SHORTHAND_JSON],+ ['glab issue list … -F json', PROSE_ISSUE_LIST_SHORTHAND],+ ['glab mr list --state', PROSE_MR_LIST_STATE],+ ['glab mr list --state argv', ARGV_MR_LIST_STATE],+];++// Stored per-install prompt DEFAULTS, which cannot be corrected by editing the+// string alone: each edit needs a PROMPT_VERSIONS bump plus the outgoing body+// preserved in PREVIOUS_DEFAULT_PROMPTS, or other installs never pick the fix up+// (CLAUDE.md "Distribution model"). Tracked in issue #4685 — removing an entry+// here is the whole acceptance criterion for that work.+//+// `previousDefaults.js` is frozen history: those strings must keep matching what+// older installs actually stored, so they stay listed permanently.+const EXEMPT = new Map([+ ['services/taskPromptDefaults/prompts.js', 'stored prompt defaults — needs a PROMPT_VERSIONS bump (#4685)'],+ ['services/taskPromptDefaults/previousDefaults.js', 'frozen historical snapshots — must match what older installs stored'],+]);++const offendingPatterns = (src) => {+ const code = stripCommentary(src);+ return PATTERNS.filter(([, re]) => re.test(code)).map(([name]) => name);+};++describe('glab flag traps are gone tree-wide', () => {+ it('no server source outside the deferred prompt defaults spells either trap', () => {+ const offenders = collectServerSources()+ .filter((rel) => !EXEMPT.has(rel))+ .map((rel) => [rel, offendingPatterns(readServerSource(rel))])+ .filter(([, hits]) => hits.length > 0);++ expect(+ offenders,+ 'ask glab for JSON with withGlabJson()/execGlabJson (lib/glabArgs.js), and select MR state with --merged/--closed/--all',+ ).toEqual([]);+ });++ it('still matches the exempt files (guard is not vacuous)', () => {+ // If the patterns stop matching even the known-offending prompt bodies, the+ // scan broke — a rename, a reformat, a changed quote style — and the+ // assertion above would pass for the wrong reason.+ for (const [rel, why] of EXEMPT) {+ expect(+ offendingPatterns(readServerSource(rel)).length,+ `${rel} (${why}) no longer matches any pattern — the scan broke, or #4685 landed and this entry should be deleted`,+ ).toBeGreaterThan(0);+ }+ });++ it('the walk actually reaches the glab call sites (guard is not vacuous)', () => {+ // A scan that silently collected nothing would also report zero offenders.+ const sources = collectServerSources();+ expect(sources).toContain('services/gitlab.js');+ expect(sources).toContain('services/appIssues.js');+ expect(sources).toContain('services/issueReconcile.js');+ expect(sources).toContain('services/perpetualWork.js');+ expect(sources).toContain('services/layeredIntelligence/forgeFiler.js');+ });+});diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex 11bb9e5f8d..66630caecc 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -1,4 +1,6 @@import { spawn } from '../lib/childProcess.js';+import { safeJSONParse } from '../lib/fileUtils.js';+import { withGlabJson } from '../lib/glabArgs.js';// Mirrors execGh's DEFAULT_EXEC_GH_TIMEOUT_MS. `glab` hits the network, so a// stalled call (hung keychain prompt, dead VPN) would otherwise leave the@@ -16,12 +18,16 @@ const DEFAULT_EXEC_GLAB_TIMEOUT_MS = 60000;* — callers treat null as "unavailable / transient", mirroring the* `.catch(() => null)` pattern used around `execGh`.*- * @param {string[]} args - glab arguments (e.g. ['issue', 'list', '-F', 'json'])+ * Module-local on purpose: every PortOS caller wants JSON, so they go through+ * `execGlabJson`, which owns the output flag (see lib/glabArgs.js). Export this+ * only when a genuine non-JSON `glab` call appears.+ *+ * @param {string[]} args - glab arguments (e.g. ['issue', 'list', '--output', 'json'])* @param {string} cwd - repo root the glab command runs in* @param {number} [timeoutMs] - kills the child and resolves null past this* @returns {Promise<string|null>}*/-export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {+function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {return new Promise((resolve) => {const child = spawn('glab', args, { cwd, shell: false });let stdout = '';@@ -45,6 +51,40 @@ export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {});}+/**+ * Run a `glab … list` command and parse its JSON array. Three answers, not two —+ * the absent-vs-empty split every caller needs (CLAUDE.md):+ *+ * - `ok` — glab answered; `rows` is the (possibly empty) array.+ * - `cli-failed` — we could not ask (non-zero exit: unauthenticated, no+ * network, `glab` not installed, timed out).+ * - `not-json` — glab answered at exit 0 with something that is not a JSON+ * array, which means its output flags moved (lib/glabArgs.js)+ * and NOT that the user is logged out. It gets its own reason+ * so callers stop sending a working CLI to re-authenticate.+ *+ * `reason` is only meaningful when `rows` is null. `args` must NOT carry an+ * output flag — this appends the one correct spelling.+ *+ * @param {string[]} args - glab arguments without the JSON output flag+ * @param {string} cwd - repo root the glab command runs in+ * @param {number} [timeoutMs]+ * @returns {Promise<{rows: object[]|null, reason: 'ok'|'cli-failed'|'not-json'}>}+ */+export async function execGlabJson(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {+ const raw = await execGlab(withGlabJson(args), cwd, timeoutMs);+ if (raw === null) return { rows: null, reason: 'cli-failed' };+ // The `null` default is load-bearing: safeJSONParse only applies its+ // salvage-an-array-from-noisy-output affordance when the default IS an array,+ // and that path yields `[]` for prose — so passing `[]` here would parse+ // glab's human table into a trustworthy-looking empty list, re-creating the+ // very bug this function exists to catch.+ const rows = safeJSONParse(raw, null);+ if (Array.isArray(rows)) return { rows, reason: 'ok' };+ console.error(`❌ execGlabJson: 'glab ${args.join(' ')}' exited 0 without JSON — glab's output flags have changed; check 'glab ${args.slice(0, 2).join(' ')} --help'`);+ return { rows: null, reason: 'not-json' };+}+/*** Does a merge request exist for `branch`? The GitLab mirror of* `github.js#findPullRequestForBranch` (#3358), with the same three answers@@ -61,13 +101,14 @@ export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {*/export async function findMergeRequestForBranch(branch, cwd) {if (!branch || !cwd) return { status: 'unavailable', number: null, url: null, detail: 'no branch or repo path' };- const raw = await execGlab(['mr', 'list', '--source-branch', branch, '--all', '-P', '1', '-F', 'json'], cwd);- if (raw === null) return { status: 'unavailable', number: null, url: null, detail: 'glab call failed' };- let parsed;- try { parsed = JSON.parse(raw); } catch { parsed = null; }- // A zero-exit glab that emitted nothing parseable told us nothing.- if (!Array.isArray(parsed)) return { status: 'unavailable', number: null, url: null, detail: 'glab returned unparseable output' };- const mr = parsed[0];+ const { rows, reason } = await execGlabJson(['mr', 'list', '--source-branch', branch, '--all', '-P', '1'], cwd);+ // Both failure modes are "we could not ask" here — a zero-exit glab that+ // emitted nothing parseable told us nothing either.+ if (!rows) {+ const detail = reason === 'not-json' ? 'glab returned unparseable output' : 'glab call failed';+ return { status: 'unavailable', number: null, url: null, detail };+ }+ const mr = rows[0];if (!mr) return { status: 'none', number: null, url: null, detail: null };return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, detail: mr.state || null };}diff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.jsindex d9802dd1ac..9957f906b4 100644--- a/server/services/gitlab.test.js+++ b/server/services/gitlab.test.js@@ -8,9 +8,15 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { EventEmitter } from 'events';const spawnMock = vi.fn();-vi.mock('../lib/childProcess.js', () => ({ spawn: (...args) => spawnMock(...args) }));+// `execFile` is unused here, but gitlab.js reaches safeJSONParse through+// lib/fileUtils.js, which promisifies it at module load — a spawn-only mock+// makes the import itself throw.+vi.mock('../lib/childProcess.js', () => ({+ spawn: (...args) => spawnMock(...args),+ execFile: () => { throw new Error('execFile is not used by gitlab.js'); },+}));-const { findMergeRequestForBranch } = await import('./gitlab.js');+const { findMergeRequestForBranch, execGlabJson } = await import('./gitlab.js');/** A fake `glab` child that writes `stdout` then exits with `code`. */const glabChild = ({ code = 0, stdout = '' } = {}) => {@@ -38,10 +44,10 @@ describe('findMergeRequestForBranch (#3358)', () => {.resolves.toMatchObject({ status: 'found', number: 12 });});- it('queries by source branch across every state', async () => {+ it('queries by source branch across every state, asking for JSON with the long --output form', async () => {await findMergeRequestForBranch('claim/issue-1', '/repo');const [, args, opts] = spawnMock.mock.calls[0];- expect(args).toEqual(['mr', 'list', '--source-branch', 'claim/issue-1', '--all', '-P', '1', '-F', 'json']);+ expect(args).toEqual(['mr', 'list', '--source-branch', 'claim/issue-1', '--all', '-P', '1', '--output', 'json']);expect(opts.cwd).toBe('/repo');});@@ -91,3 +97,46 @@ describe('execGlab timeout (#3358)', () => {vi.useRealTimers();});});++describe('execGlabJson', () => {+ it('appends the JSON flag itself so no caller can re-copy the wrong one', async () => {+ await execGlabJson(['issue', 'list', '--per-page', '100'], '/repo');+ const [, args] = spawnMock.mock.calls[0];+ expect(args).toEqual(['issue', 'list', '--per-page', '100', '--output', 'json']);+ });++ it('returns the parsed rows on an answered list', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: '[{"iid":7}]' }));+ await expect(execGlabJson(['issue', 'list'], '/repo'))+ .resolves.toEqual({ rows: [{ iid: 7 }], reason: 'ok' });+ });++ it('an ANSWERED empty list is rows:[] / ok — never conflated with a failed read', async () => {+ await expect(execGlabJson(['issue', 'list'], '/repo'))+ .resolves.toEqual({ rows: [], reason: 'ok' });+ });++ it('reports `cli-failed` when glab exits non-zero (unauthenticated / offline / missing)', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ code: 1 }));+ await expect(execGlabJson(['issue', 'list'], '/repo'))+ .resolves.toEqual({ rows: null, reason: 'cli-failed' });+ });++ it('reports `not-json` — NOT `cli-failed` — when glab exits 0 with its human table', async () => {+ // The exact regression: a working, authenticated glab whose output flag+ // moved answers with a table at exit 0. Collapsing that into the+ // reachability failure is what produced the false "retry once the CLI is+ // authenticated" advice.+ spawnMock.mockImplementationOnce(() => glabChild({+ stdout: 'Showing 12 open issues in group/proj (Page 1)\n\n#356\tSomething\t(plan)\t1 hour ago'+ }));+ await expect(execGlabJson(['issue', 'list'], '/repo'))+ .resolves.toEqual({ rows: null, reason: 'not-json' });+ });++ it('a JSON OBJECT is not a row list either', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: '{"message":"404 Not Found"}' }));+ await expect(execGlabJson(['issue', 'list'], '/repo'))+ .resolves.toEqual({ rows: null, reason: 'not-json' });+ });+});diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.jsindex 1655f144a7..36795d4d85 100644--- a/server/services/issueReconcile.js+++ b/server/services/issueReconcile.js@@ -52,7 +52,7 @@import { execGit } from '../lib/execGit.js';import { execGh, ensureForgeReachable } from './github.js';-import { execGlab } from './gitlab.js';+import { execGlabJson } from './gitlab.js';import { fetchMyCurrentSprintTickets } from './jira.js';import { resolveAppForgeTarget, resolveRepoForgeTarget } from '../lib/workTracker.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';@@ -311,7 +311,7 @@ async function getGithubState(repoSpec, fullName, apiHost = null) {}/**- * Normalize a raw GitLab issue (from `glab issue list -F json`) into the common+ * Normalize a raw GitLab issue (from `glab issue list --output json`) into the common* shape. GitLab keys the number on `iid`, exposes labels as plain strings, and* assignees as `{ username }` objects.*/@@ -354,32 +354,34 @@ function normalizeGitlabMr(mr) {* @returns {Promise<{forge:'gitlab', fullName:string, inProgress:object[], mergedPrs:object[], openPrs:object[]}|null>}*/async function getGitlabState(repoPath, fullName) {- const [issuesRaw, mergedRaw, openRaw] = await Promise.all([+ // `glab mr list` has NO `--state` flag — the state is selected by presence+ // flags (`--merged`, `--closed`, `--all`) and defaults to OPEN. Passing+ // `--state merged` exited non-zero on every call, so the GitLab arm of this+ // scan skipped every cycle without ever reporting why.+ const [issues, merged, open] = await Promise.all([// `glab issue list` defaults to OPEN issues; --label filters to in-progress.- execGlab(['issue', 'list', '--label', IN_PROGRESS_LABEL,- '--per-page', String(GL_PER_PAGE), '-F', 'json'], repoPath),- execGlab(['mr', 'list', '--state', 'merged',- '--per-page', String(GL_PER_PAGE), '-F', 'json'], repoPath),- execGlab(['mr', 'list', '--state', 'opened',- '--per-page', String(GL_PER_PAGE), '-F', 'json'], repoPath),+ execGlabJson(['issue', 'list', '--label', IN_PROGRESS_LABEL,+ '--per-page', String(GL_PER_PAGE)], repoPath),+ execGlabJson(['mr', 'list', '--merged',+ '--per-page', String(GL_PER_PAGE)], repoPath),+ // Opened is glab's default; `--opened` is deprecated, so pass no state flag.+ execGlabJson(['mr', 'list',+ '--per-page', String(GL_PER_PAGE)], repoPath),]);- const inProgressRaw = safeJSONParse(issuesRaw, null);- if (!Array.isArray(inProgressRaw)) return null;+ if (!issues.rows) return null;// Same load-bearing treatment as the GitHub path (#3358): a `glab` blip on the// MR lists must fail the scan, not degrade to "no MRs exist".- const mergedRows = safeJSONParse(mergedRaw, null);- const openRows = safeJSONParse(openRaw, null);- if (!Array.isArray(mergedRows) || !Array.isArray(openRows)) {- console.error(`❌ issue-reconcile: glab mr list unavailable for ${fullName} — skipping this cycle`);+ if (!merged.rows || !open.rows) {+ console.error(`❌ issue-reconcile: glab mr list unavailable for ${fullName} (${merged.reason}/${open.reason}) — skipping this cycle`);return null;}return {forge: 'gitlab',fullName,- inProgress: inProgressRaw.map(normalizeGitlabIssue),- mergedPrs: mergedRows.map(normalizeGitlabMr),- openPrs: openRows.map(normalizeGitlabMr),+ inProgress: issues.rows.map(normalizeGitlabIssue),+ mergedPrs: merged.rows.map(normalizeGitlabMr),+ openPrs: open.rows.map(normalizeGitlabMr),};}diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.jsindex 3fb5468638..2c4ee55cb8 100644--- a/server/services/issueReconcile.test.js+++ b/server/services/issueReconcile.test.js@@ -22,7 +22,7 @@ vi.mock('./github.js', () => ({execGh: vi.fn(async () => '[]'),ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),}));-vi.mock('./gitlab.js', () => ({ execGlab: vi.fn(async () => '[]') }));+vi.mock('./gitlab.js', () => ({ execGlabJson: vi.fn(async () => ({ rows: [], reason: 'ok' })) }));vi.mock('./jira.js', () => ({ fetchMyCurrentSprintTickets: vi.fn(async () => []) }));vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: vi.fn(async () => ({ isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS' })),@@ -46,7 +46,7 @@ import {} from './issueReconcile.js';import { execGit } from '../lib/execGit.js';import { execGh } from './github.js';-import { execGlab } from './gitlab.js';+import { execGlabJson } from './gitlab.js';import { fetchMyCurrentSprintTickets } from './jira.js';import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';@@ -269,7 +269,7 @@ describe('reconcile', () => {const result = await reconcile('/repo');expect(result).toBeNull();expect(execGh).not.toHaveBeenCalled();- expect(execGlab).not.toHaveBeenCalled();+ expect(execGlabJson).not.toHaveBeenCalled();});it('scans a GitHub Enterprise host (isGithub=false) via a host-qualified --repo selector', async () => {@@ -329,7 +329,7 @@ describe('reconcile', () => {expect(result.forge).toBe('gitlab');expect(result.zombies.map((z) => z.number)).toEqual([42]);// glab is cwd-routed — it must run in the scanned checkout.- expect(execGlab.mock.calls[0][1]).toBe('/repo');+ expect(execGlabJson.mock.calls[0][1]).toBe('/repo');});it('still scans a plan-tracked app on a forge origin (a zombie is a fact about the repo, not about where claims are filed)', async () => {@@ -371,16 +371,18 @@ function useGitlabOrigin() {}/**- * Wire execGlab's three list calls by argv shape. Inputs use the RAW GitLab JSON- * shape (iid / web_url / source_branch / description) so the test also exercises- * the GitLab→common normalizers.+ * Wire execGlabJson's three list calls by argv shape. Inputs use the RAW GitLab+ * JSON shape (iid / web_url / source_branch / description) so the test also+ * exercises the GitLab→common normalizers.+ *+ * The merged/open split keys off the `--merged` presence flag; open is glab's+ * default. See gitlab.glabFlags.test.js for why there is no `--state` pair.*/function mockGlab({ issues = [], merged = [], open = [] }) {- execGlab.mockImplementation(async (argv) => {- if (argv[0] === 'issue' && argv[1] === 'list') return JSON.stringify(issues);- if (argv[0] === 'mr' && argv.includes('merged')) return JSON.stringify(merged);- if (argv[0] === 'mr' && argv.includes('opened')) return JSON.stringify(open);- return '[]';+ execGlabJson.mockImplementation(async (argv) => {+ if (argv[0] === 'issue' && argv[1] === 'list') return { rows: issues, reason: 'ok' };+ if (argv[0] === 'mr') return { rows: argv.includes('--merged') ? merged : open, reason: 'ok' };+ return { rows: [], reason: 'ok' };});}@@ -448,14 +450,35 @@ describe('reconcile (GitLab forge)', () => {});it('returns null (transient) when the glab issue list query fails', async () => {- execGlab.mockImplementation(async (argv) => {- if (argv[0] === 'issue') return null; // load-bearing query failed / glab down- return '[]';+ execGlabJson.mockImplementation(async (argv) => {+ // load-bearing query failed / glab down+ if (argv[0] === 'issue') return { rows: null, reason: 'cli-failed' };+ return { rows: [], reason: 'ok' };});const result = await reconcile('/repo');expect(result).toBeNull();});+ it('splits merged-vs-open MRs with presence flags, not a nonexistent `--state`', async () => {+ mockGlab({ issues: [], merged: [], open: [] });+ await reconcile('/repo');+ const mrCalls = execGlabJson.mock.calls.map(([argv]) => argv).filter((argv) => argv[0] === 'mr');+ expect(mrCalls).toHaveLength(2);+ for (const argv of mrCalls) expect(argv).not.toContain('--state');+ // Merged is explicit; opened is glab's default, so it carries no state flag.+ expect(mrCalls.some((argv) => argv.includes('--merged'))).toBe(true);+ expect(mrCalls.some((argv) => !argv.includes('--merged'))).toBe(true);+ });++ it('leaves the JSON output flag to execGlabJson', async () => {+ mockGlab({ issues: [], merged: [], open: [] });+ await reconcile('/repo');+ for (const [argv] of execGlabJson.mock.calls) {+ expect(argv).not.toContain('-F');+ expect(argv).not.toContain('--output');+ }+ });+it('empty in-progress list is a valid answer (no zombies), not a skip', async () => {mockGlab({ issues: [], merged: [], open: [] });const result = await reconcile('/repo');@@ -512,7 +535,7 @@ describe('reconcile (JIRA tracker)', () => {expect(result.zombies[0].status).toBe('In Review');// JIRA never routes to gh/glab.expect(execGh).not.toHaveBeenCalled();- expect(execGlab).not.toHaveBeenCalled();+ expect(execGlabJson).not.toHaveBeenCalled();});it('a live claim/<KEY> branch keeps the In-Review ticket LIVE (not a zombie)', async () => {diff --git a/server/services/layeredIntelligence/forgeFiler.js b/server/services/layeredIntelligence/forgeFiler.jsindex 145efd4219..d55462158e 100644--- a/server/services/layeredIntelligence/forgeFiler.js+++ b/server/services/layeredIntelligence/forgeFiler.js@@ -10,6 +10,7 @@ import { safeJSONParse } from '../../lib/fileUtils.js';import { LI_LABEL, LI_BLOCKING_LABEL } from './constants.js';import { slugMarker, extractSlugFromBody } from './dedup.js';import { runCli } from './runCli.js';+import { withGlabJson } from '../../lib/glabArgs.js';/*** Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`@@ -72,7 +73,7 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =// glab lists open issues by default and needs `--all` to widen to every state;// gh takes the state explicitly.const args = cli === 'glab'- ? ['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100', '-F', 'json']+ ? withGlabJson(['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100']): ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments,closedByPullRequestsReferences'];const { code, stdout } = await exec(cli, args, { cwd, env });if (code !== 0) return { ok: false, issues: [] };@@ -98,12 +99,12 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =// The rejection classifier's last-resort signal (#2748): the prose a human// left when declining, for a close with no matching label/close-reason. gh// returns `comments` in the same batched list call (no extra fetch); glab's- // `-F json` omits them, so its rows carry null and fall through to label/+ // JSON omits them, so its rows carry null and fall through to label/// stateReason only (tracked in the issue's Remaining).closingComment: extractClosingComment(i.comments),// The implementing-PR handle (#2748, deliverable 2): gh reports every PR that// closes/references this issue in `closedByPullRequestsReferences`. Additive- // and null-defaulted — glab's `-F json` omits it, so its rows carry null and+ // and null-defaulted — glab's JSON omits it, so its rows carry null and// fall through to the label/comment signals, and the reconciler only reads a// PR's state when it holds a number here. Scoped to the issue's own repo (parsed// from its url) so a cross-repo closing PR can't resolve to the wrong number.@@ -207,7 +208,7 @@ export function extractClosingComment(comments) {*/export async function listBlockingIssues({ cli, cwd, env, exec = runCli } = {}) {const args = cli === 'glab'- ? ['issue', 'list', '--label', LI_BLOCKING_LABEL, '-P', '100', '-F', 'json']+ ? withGlabJson(['issue', 'list', '--label', LI_BLOCKING_LABEL, '-P', '100']): ['issue', 'list', '--label', LI_BLOCKING_LABEL, '--state', 'open', '--limit', '100', '--json', 'number,title,state'];const { code, stdout } = await exec(cli, args, { cwd, env });if (code !== 0) return { ok: false, issues: [] };diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.jsindex 4c2e2b6a58..e15219b996 100644--- a/server/services/perpetualWork.js+++ b/server/services/perpetualWork.js@@ -28,6 +28,7 @@ import { join } from 'path';import { emitLog } from './cosEvents.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, extractSlugFromRef } from '../lib/planIds.js';import { readOriginRemoteUrl } from '../lib/gitRemote.js';+import { withGlabJson } from '../lib/glabArgs.js';// Labels that make a GitHub issue non-actionable for autonomous claiming. MUST// stay in sync with the claim-issue prompt's Phase 1 skip-list@@ -136,7 +137,7 @@ async function inFlightIssueNumbers(repoPath, forge = 'github') {const nums = new Set();// The branch list and the PR/MR list are independent CLI calls — run concurrently.const prListCall = forge === 'gitlab'- ? runCli('glab', ['mr', 'list', '--per-page', '100', '-F', 'json'], repoPath)+ ? runCli('glab', withGlabJson(['mr', 'list', '--per-page', '100']), repoPath): runCli('gh', ['pr', 'list', '--state', 'open', '--json', 'headRefName', '-q', '.[].headRefName'], repoPath);const [branchRes, prRes] = await Promise.all([runCli('git', ['branch', '-a', '--no-color', '--format=%(refname:short)'], repoPath),@@ -335,7 +336,7 @@ const FORGE_ISSUE_CONFIG = {// can still park on a false "no actionable issues" despite real work// further down the queue. `--issues-label`-style curation is the// practical mitigation there; this detector has no equivalent knob yet.- listArgs: ['issue', 'list', '--per-page', '100', '-F', 'json'],+ listArgs: withGlabJson(['issue', 'list', '--per-page', '100']),listFail: 'glab-list-failed',parseFail: 'glab-parse-failed',// Park reason when the owner filter resolves to a non-authoring owner. On