Skip to content

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

fix: harden claim review and merge gates

[._.]/ Adam Eivy55059078a71f
diff --git a/server/scripts/run-local-code-review.mjs b/server/scripts/run-local-code-review.mjs
new file mode 100644
index 0000000000..58e5b79c36
--- /dev/null
+++ b/server/scripts/run-local-code-review.mjs
@@ -0,0 +1,23 @@
+#!/usr/bin/env node
+
+/**
+ * Auth-independent local-review bridge for unattended claim agents.
+ * Reads one JSON request from stdin and writes the service result to stdout.
+ */
+import { getCodeReviewDefaults, runLocalCodeReview } from '../services/codeReview.js';
+
+const chunks = [];
+for await (const chunk of process.stdin) chunks.push(chunk);
+
+try {
+ const request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ const defaults = await getCodeReviewDefaults().catch(() => null);
+ const model = request.model || defaults?.[`${request.backend}Model`] || null;
+ const effort = request.effort || defaults?.[`${request.backend}Effort`] || null;
+ const result = await runLocalCodeReview({ ...request, model, effort });
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+ if (!result.ok) process.exitCode = 1;
+} catch (err) {
+ process.stdout.write(`${JSON.stringify({ ok: false, error: err.message })}\n`);
+ process.exitCode = 1;
+}
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index c41d4f1176..5ca87c7077 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -44,6 +44,8 @@ import { ensureInstanceId } from './instances.js';
import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { resolveTrackerFilingBlock } from '../lib/workTracker.js';
import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { shellQuote } from '../lib/shellQuote.js';
/**
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
@@ -697,23 +699,24 @@ export function buildLocalReviewerInstructions(promptTaskType, reviewers, review
const localReviewers = (reviewers || []).filter((reviewer) => LOCAL_LLM_REVIEWERS.includes(reviewer));
if (!localReviewers.length) return '';
+ const gitlabDiff = `MR_IID="$(glab mr list --source-branch "$(git branch --show-current)" -F json | jq -er '.[0].iid)'"\nglab mr diff "$MR_IID"`;
const diffCommand = promptTaskType === 'claim-issue-gitlab'
- ? 'glab mr diff "$MR_NUMBER"'
+ ? gitlabDiff
: promptTaskType === 'claim-issue'
- ? 'gh pr diff "$PR_NUMBER"'
- : '<gh pr diff "$PR_NUMBER" OR glab mr diff "$MR_NUMBER">';
+ ? 'gh pr diff'
+ : `if command -v gh >/dev/null 2>&1 && gh pr view --json url -q .url >/dev/null 2>&1; then\n gh pr diff\nelif command -v glab >/dev/null 2>&1; then\n ${gitlabDiff.replace(/\n/g, '\n ')}\nelse\n echo "No supported forge CLI can resolve the current branch's review diff" >&2\n exit 1\nfi`;
+ const reviewScript = shellQuote(join(PATHS.root, 'server/scripts/run-local-code-review.mjs'));
const commands = localReviewers.map((reviewer) => {
const pinned = {
backend: reviewer,
...(reviewerModels[reviewer] ? { model: reviewerModels[reviewer] } : {}),
...(reviewerEfforts[reviewer] ? { effort: reviewerEfforts[reviewer] } : {}),
};
- const shellQuote = (value) => `'${String(value).replaceAll("'", "'\"'\"'")}'`;
const jqArgs = Object.entries(pinned)
.map(([key, value]) => `--arg ${key} ${shellQuote(value)}`)
.join(' ');
const jqObject = Object.keys(pinned).map((key) => `${key}: $${key}`).join(', ');
- return `### ${reviewer}\n\n\`\`\`bash\nREVIEW_RESPONSE=$(mktemp)\n${diffCommand} | jq -Rs ${jqArgs} '{ ${jqObject}, diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @- > "$REVIEW_RESPONSE"\nif ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then\n echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2\n exit 1\nfi\ncat "\${REVIEW_RESPONSE}.findings"\n\`\`\``;
+ return `### ${reviewer}\n\n\`\`\`bash\nREVIEW_DIFF=$(mktemp)\nREVIEW_RESPONSE=$(mktemp)\ntrap 'rm -f "$REVIEW_DIFF" "$REVIEW_RESPONSE" "\${REVIEW_RESPONSE}.findings"' EXIT\nif ! { ${diffCommand}; } > "$REVIEW_DIFF"; then\n echo "Unable to resolve the current branch's review diff" >&2\n exit 1\nfi\njq -Rs ${jqArgs} '{ ${jqObject}, diff: . }' < "$REVIEW_DIFF" | node ${reviewScript} > "$REVIEW_RESPONSE"\nif ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then\n echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2\n exit 1\nfi\ncat "\${REVIEW_RESPONSE}.findings"\n\`\`\``;
}).join('\n\n');
return `\n\n## Local Reviewer Procedure\n\nRun each configured local reviewer in its listed order using the command below. Only a successfully extracted non-empty \`.findings\` string is a review result. Timeout, transport failure, malformed JSON, an error response, or missing/empty findings is INCONCLUSIVE: do not merge or substitute a self-review.\n\n${commands}`;
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index da0f7cc776..3678689004 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -72,17 +72,27 @@ describe('claim reviewer resolution', () => {
expect(normalizeClaimReviewers({ reviewers: ['copilot'] }, ['copilot'])).toEqual(['codex']);
});
- it('keeps local reviewers and emits forge-specific, fail-closed endpoint commands', () => {
+ it('keeps local reviewers and emits forge-specific, fail-closed service commands', () => {
const github = buildLocalReviewerInstructions('claim-issue', ['ollama'], { ollama: 'example-model' }, { ollama: 'high' });
- expect(github).toContain('gh pr diff "$PR_NUMBER"');
- expect(github).toContain("--arg backend 'ollama'");
- expect(github).toContain("--arg model 'example-model'");
- expect(github).toContain("--arg effort 'high'");
+ expect(github).toContain('gh pr diff');
+ expect(github).not.toContain('$PR_NUMBER');
+ expect(github).toContain('--arg backend ollama');
+ expect(github).toContain('--arg model example-model');
+ expect(github).toContain('--arg effort high');
+ expect(github).toContain('run-local-code-review.mjs');
+ expect(github).not.toContain('localhost:5555');
expect(github).toContain('missing/empty findings is INCONCLUSIVE');
const gitlab = buildLocalReviewerInstructions('claim-issue-gitlab', ['lmstudio']);
- expect(gitlab).toContain('glab mr diff "$MR_NUMBER"');
+ expect(gitlab).toContain('glab mr list --source-branch');
+ expect(gitlab).toContain('glab mr diff "$MR_IID"');
+ expect(gitlab).not.toContain('$MR_NUMBER');
expect(gitlab).not.toContain('gh pr diff');
+
+ const generic = buildLocalReviewerInstructions('plan-task', ['ollama']);
+ expect(generic).toContain('command -v gh');
+ expect(generic).toContain('command -v glab');
+ expect(generic).not.toContain('<gh pr diff');
});
});
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 24b0f923c4..d7d2b4542f 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -37,7 +37,9 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(prompt.toLowerCase()).not.toContain('copilot');
expect(prompt).not.toMatch(/^\s*gh pr merge[^\n]*--auto/m);
expect(prompt).toContain('--json state -q .state');
- expect(prompt).toContain('MERGED');
+ expect(prompt).toContain('[ "$STATE" = "MERGED" ]');
+ expect(prompt).toContain('--squash --delete-branch');
+ expect(prompt).toContain('--rebase --delete-branch');
expect(prompt).toContain('Never force-delete with `-D`');
}
@@ -45,6 +47,7 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(gitlab.toLowerCase()).not.toContain('copilot');
expect(gitlab).toContain('glab mr view');
expect(gitlab).toContain('ascii_downcase');
+ expect(gitlab).toContain('--squash --remove-source-branch');
expect(gitlab).toContain('Never force-delete with `-D`');
});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 50b10440b6..13096b8d89 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -12,9 +12,9 @@
"mobile-responsive": "16d8e7f63a673a2de48994c0ac08ef3d",
"ux": "e03d03fc7c16faa5b5db93be2896b9ad",
"feature-ideas": "d3282f16da29efe2d53595b3b34778bc",
- "plan-task": "614ffdd262719bfa7c63887424556f53",
- "claim-issue": "c0f939a1fa3f729fce486f03efff4945",
- "claim-issue-gitlab": "701841e87e24f0ccecab53c4e7cd523a",
+ "plan-task": "aa5d121b3cb25aa134e3a20e5f0186c6",
+ "claim-issue": "dc47a602c96b0618e7bca87e6b21c397",
+ "claim-issue-gitlab": "d8fe2bf614b465ca46108ea3295d2ec5",
"claim-issue-jira": "52fd3506aad0b283be7234b608cf31ca",
"code-reviewer-review": "1cd13ee5142d130f95cc390098d0f278",
"code-reviewer-implement": "ab2c3e16d54e195bdf856574b7702042",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index fa9c9c99e0..b2aa2bf351 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -641,13 +641,18 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\
3. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.
4. **Wait for each configured reviewer's valid findings BEFORE merging.** Invoke CLI reviewers headless against the PR diff; invoke local LLM reviewers through the appended endpoint procedure. Apply fixes, run tests, and re-push, capped at 3 rounds per reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the PR naming the failure, remove only the worktree, and leave the branch and PR for reconciliation.
-5. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`:
+5. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:
\`\`\`bash
PR_URL=$(gh pr view <num> --json url -q .url)
- gh pr merge "$PR_URL" --merge --delete-branch
- gh pr view "$PR_URL" --json state -q .state
+ gh pr merge "$PR_URL" --merge --delete-branch || {
+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \
+ gh pr merge "$PR_URL" --squash --delete-branch || \
+ gh pr merge "$PR_URL" --rebase --delete-branch
+ }
+ STATE=$(gh pr view "$PR_URL" --json state -q .state)
+ [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }
\`\`\`
- The final command must return \`MERGED\`. Investigate and retry on \`OPEN\`; \`CLOSED\` is not success. Do not enter Phase 7 until remote state is exactly \`MERGED\`.
+ The exact comparison must succeed. Investigate and retry on \`OPEN\`; \`CLOSED\` is not success. Do not enter Phase 7 until remote state is exactly \`MERGED\`.
## Phase 7 — Clean up (post-merge ONLY)
@@ -767,13 +772,18 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\
2. **Wait for each configured reviewer's findings BEFORE merging.** Run the reviewers in the listed order (\`{reviewers}\`). Invoke CLI reviewers headless against the PR diff and local LLM reviewers through the appended endpoint procedure; apply fixes, run tests, and re-push — capped at 3 rounds — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review or merge; comment on the PR naming the failure and stop.
**Review-stuck cleanup** (after 3 unresolved rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.
-3. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN:
+3. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:
\`\`\`bash
PR_URL=$(gh pr view <pr-num> --json url -q .url)
- gh pr merge "$PR_URL" --merge --delete-branch
- gh pr view "$PR_URL" --json state -q .state
+ gh pr merge "$PR_URL" --merge --delete-branch || {
+ [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \
+ gh pr merge "$PR_URL" --squash --delete-branch || \
+ gh pr merge "$PR_URL" --rebase --delete-branch
+ }
+ STATE=$(gh pr view "$PR_URL" --json state -q .state)
+ [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }
\`\`\`
- The final command MUST return \`MERGED\`. \`OPEN\` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. \`CLOSED\` is also not success. Do not enter Phase 7 until remote GitHub state is exactly \`MERGED\`.
+ The exact comparison MUST succeed. \`OPEN\` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. \`CLOSED\` is also not success. Do not enter Phase 7 until remote GitHub state is exactly \`MERGED\`.
## Phase 7 — Clean up (post-merge ONLY)
@@ -903,7 +913,10 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. \`claude\
3. **Merge immediately via \`glab mr merge\`** — NEVER a local \`git merge\`. \`glab mr merge\` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:
\`\`\`bash
MR_IID="$(glab mr list --source-branch "claim/issue-\${NUM}" -F json | sed -n 's/.*"iid":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)"
- glab mr merge "\${MR_IID}" --yes --remove-source-branch
+ glab mr merge "\${MR_IID}" --yes --remove-source-branch || {
+ glab mr view "\${MR_IID}" -F json | jq -e 'select((.state | ascii_downcase) == "merged")' >/dev/null || \
+ glab mr merge "\${MR_IID}" --yes --squash --remove-source-branch
+ }
glab mr view "\${MR_IID}" -F json | jq -er 'select((.state | ascii_downcase) == "merged") | .state'
\`\`\`
The verification command must succeed and print a merged state. An opened/closed state or missing value is not success; investigate CI, review, and branch protection, then retry. Do not enter Phase 7 until the forge confirms the MR is merged.