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

address review (codex): forge-aware manual TUI PR + shell-quoted refs

[._.]/ Adam Eivy692183cba754
diff --git a/server/lib/README.md b/server/lib/README.md
index 7cc877e2c9..3dee569a0e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -234,6 +234,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
+| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
diff --git a/server/lib/index.js b/server/lib/index.js
index 3eb42aa6a6..36b2e88d33 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -204,6 +204,7 @@ export * from './lwwTimestamp.js';
export * from './mapWithConcurrency.js';
export * from './objects.js';
export * from './openapiSpec.js';
+export * from './shellQuote.js';
export * from './singleFlight.js';
export * from './streamBackpressure.js';
export * from './sseUtils.js';
diff --git a/server/lib/shellQuote.js b/server/lib/shellQuote.js
new file mode 100644
index 0000000000..2bfb08ed61
--- /dev/null
+++ b/server/lib/shellQuote.js
@@ -0,0 +1,16 @@
+/**
+ * POSIX single-quote shell escaping for values interpolated into shell command
+ * strings (display command lines, copy-paste command blocks in agent prompts).
+ *
+ * Bare-safe tokens (`[A-Za-z0-9_./:=+-]`) are returned untouched for readability;
+ * anything else is wrapped in single quotes with embedded `'` escaped as `'\''`.
+ * This is the canonical helper — do NOT hand-roll another escaper.
+ *
+ * @param {*} value
+ * @returns {string}
+ */
+export function shellQuote(value) {
+ const text = String(value ?? '');
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
+ return `'${text.replace(/'/g, `'\\''`)}'`;
+}
diff --git a/server/lib/shellQuote.test.js b/server/lib/shellQuote.test.js
new file mode 100644
index 0000000000..1785890a13
--- /dev/null
+++ b/server/lib/shellQuote.test.js
@@ -0,0 +1,27 @@
+import { describe, it, expect } from 'vitest';
+import { shellQuote } from './shellQuote.js';
+
+describe('shellQuote', () => {
+ it('passes bare-safe tokens through unquoted', () => {
+ expect(shellQuote('claim/issue-1814')).toBe('claim/issue-1814');
+ expect(shellQuote('main')).toBe('main');
+ expect(shellQuote('feature_v2.1')).toBe('feature_v2.1');
+ expect(shellQuote('a:b=c+d-e/f')).toBe('a:b=c+d-e/f');
+ });
+
+ it('single-quotes values containing shell metacharacters', () => {
+ expect(shellQuote('weird;rm -rf')).toBe("'weird;rm -rf'");
+ expect(shellQuote('a b')).toBe("'a b'");
+ expect(shellQuote('$(whoami)')).toBe("'$(whoami)'");
+ expect(shellQuote('back`tick`')).toBe("'back`tick`'");
+ });
+
+ it('escapes embedded single quotes with the POSIX \'\\\'\' sequence', () => {
+ expect(shellQuote("it's")).toBe("'it'\\''s'");
+ });
+
+ it('stringifies null/undefined to an empty quoted string', () => {
+ expect(shellQuote(null)).toBe("''");
+ expect(shellQuote(undefined)).toBe("''");
+ });
+});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 4aed612e26..505e0881bb 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -19,6 +19,7 @@ import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUt
import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, normalizeReviewers, buildReviewWithArgs } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { isOpencodeCommand } from '../lib/providerModels.js';
+import { shellQuote } from '../lib/shellQuote.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
@@ -888,7 +889,9 @@ function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, revie
*/
function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, reviewers = DEFAULT_REVIEWERS, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
if (slashdoFree) {
- return buildManualTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, branchName, baseBranch });
+ // The manual path never auto-merges (it opens the PR for review), so it
+ // doesn't need willReviewLoop — the review gate holds unconditionally.
+ return buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinelPath, branchName, baseBranch });
}
const cmd = willOpenPR ? '/do:pr' : '/do:push';
const reviewArgs = willOpenPR && willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies) : '';
@@ -936,25 +939,25 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
/**
* Manual (slashdo-free) TUI completion-workflow block — for an OpenCode TUI that
* does NOT load Claude Code slash commands and so can't run `/do:pr` / `/do:push`.
- * Drives the same commit → push → (PR) → sentinel handshake with plain `git` / `gh`
- * commands, so the `.agent-done` signal still fires and the task completes.
+ * Drives a plain `git` commit → push → (open PR/MR) → sentinel handshake, so the
+ * `.agent-done` signal still fires and the task completes.
*
* PortOS forces `openPR:false, skipMerge:true` on TUI worktree cleanup (see
* agentTuiSpawning.js), so nothing happens after the agent exits — the agent owns
- * the push, and the PR + merge when one is requested, itself.
- *
- * OpenCode can't invoke the CLI reviewers itself, and PortOS runs no post-exit
- * review follow-up for a TUI. So when a review loop is requested (`willReviewLoop`),
- * the agent opens the PR but must NOT auto-merge — it leaves the PR open for a
- * configured reviewer / human, preserving the same review gate the slashdo `/do:pr`
- * flow enforces. Only when no review loop is requested does it merge directly.
+ * the push and the PR itself. It opens the PR/MR for review but does NOT merge:
+ * this provider can't drive the reviewer CLIs (no slashdo `/do:pr` review loop)
+ * and PortOS runs no post-exit review for a TUI, so auto-merging would ship
+ * unreviewed work. A configured reviewer / human reviews and merges. Forge-aware
+ * (GitHub `gh` + GitLab `glab`) to match the slashdo path; refs are shell-quoted
+ * because a git ref can legally contain shell metacharacters.
*/
-function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = false, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null }) {
- const branchRef = branchName || 'HEAD';
- // Pin the PR base to the worktree's base branch when known, so `gh pr create`
- // doesn't guess (and a fork install targets the intended branch rather than the
- // default). `--fill` still supplies title/body from the commits.
- const prCreate = baseBranch ? `gh pr create --fill --base ${baseBranch}` : 'gh pr create --fill';
+function buildManualTuiCompletionSection({ willOpenPR, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null }) {
+ const branchRef = shellQuote(branchName || 'HEAD');
+ // Pin the PR base to the worktree's base branch when known, so the forge CLI
+ // doesn't guess (and a fork install targets the intended branch). `--fill`
+ // still supplies title/body from the commits.
+ const ghBaseArg = baseBranch ? ` --base ${shellQuote(baseBranch)}` : '';
+ const glabBaseArg = baseBranch ? ` --target-branch ${shellQuote(baseBranch)}` : '';
const simplifyStep = simplifyEnabled
? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`
: '1. (simplify disabled — skip)';
@@ -962,7 +965,7 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = false, s
const lines = [
'## Completion Workflow',
- 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git` / `gh`. Run these in order:',
+ 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git` (and your forge\'s CLI). Run these in order:',
'',
simplifyStep,
'2. Stage only the files you changed (never `git add -A` / `git add .`) and commit with a conventional message (`feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations):',
@@ -981,30 +984,13 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = false, s
let step = 4;
if (willOpenPR) {
lines.push(
- `${step++}. Open a pull request against the default branch and capture the PR URL it prints:`,
+ `${step++}. Open a pull/merge request against the base branch using the CLI for this repo's forge (check \`git remote -v\`), and capture the URL it prints. **Leave it open for review — do NOT merge it yourself.** This provider can't run the reviewer loop, and PortOS won't merge it for a TUI task, so a configured reviewer or a human reviews and merges it.`,
'',
' ```bash',
- ` ${prCreate}`,
+ ` # GitHub: gh pr create --fill${ghBaseArg}`,
+ ` # GitLab: glab mr create --fill${glabBaseArg}`,
' ```',
);
- if (willReviewLoop) {
- // A review loop was requested. This provider can't drive the reviewer
- // CLIs, and PortOS runs no post-exit review for a TUI — so DON'T merge.
- // Leave the PR open so the configured reviewer / a human reviews + merges,
- // matching the gate the slashdo `/do:pr` flow enforces before merging.
- lines.push(
- `${step++}. **Leave the PR open for review — do NOT merge it yourself.** A code review was requested for this task; this provider can't run the reviewer loop, so a configured reviewer or a human reviews and merges the PR. Record the PR URL in the sentinel below and finish.`,
- );
- } else {
- lines.push(
- `${step++}. Merge the PR and delete the branch:`,
- '',
- ' ```bash',
- ' gh pr merge "<PR_URL>" --merge --delete-branch',
- ' ```',
- `${step++}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If \`gh pr merge\` exited non-zero (it can fail to delete/checkout the branch locally from inside a worktree even though the **remote** merge succeeded) but this shows \`MERGED\`, you are done — do NOT retry. If it shows \`OPEN\` or \`CLOSED\`, investigate (failing check, branch protection), fix, and retry.`,
- );
- }
}
lines.push(
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index d72cf3098c..5cb26b20cf 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -209,10 +209,11 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/gh pr merge/);
});
- it('emits a slashdo-free git/gh Completion Workflow for an OpenCode TUI + openPR', () => {
+ it('emits a slashdo-free, forge-aware Completion Workflow for an OpenCode TUI + openPR (opens PR, no auto-merge)', () => {
// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push
- // would be uninvokable. The agent must commit, push, open + merge the PR, and
- // write the sentinel with plain git/gh — PortOS does NOT push or merge post-exit.
+ // would be uninvokable. The agent commits, pushes, opens the PR/MR for review,
+ // and writes the sentinel with plain git + the forge CLI. It must NOT auto-merge
+ // (it can't run the reviewer loop and PortOS runs no post-exit review for a TUI).
const prompt = buildLightContextPrompt(
makeTask({ metadata: { simplify: true, openPR: true } }),
'/r',
@@ -226,52 +227,49 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/`\/simplify`/);
// /simplify is a Claude built-in — OpenCode gets the inline equivalent.
expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);
- // Plain git/gh commit → push → PR → merge → verify. The PR base is pinned
- // to the worktree's base branch when known.
+ // Plain git commit → push → open PR. Base pinned to the worktree base branch.
expect(prompt).toMatch(/git commit -m/);
expect(prompt).toMatch(/git push -u origin claim\/issue-1/);
+ // Forge-aware: both GitHub (gh) and GitLab (glab) create commands, base-pinned.
expect(prompt).toMatch(/gh pr create --fill --base main/);
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
- expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
- expect(prompt).toMatch(/MERGED/);
+ expect(prompt).toMatch(/glab mr create --fill --target-branch main/);
+ // Opens for review — never auto-merges.
+ expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/glab mr merge/);
+ expect(prompt).toMatch(/do NOT merge it yourself/);
// Sentinel handshake still drives completion; never tell the agent to run /quit.
expect(prompt).toMatch(/\.agent-done/);
expect(prompt).toMatch(/NOT run `\/quit`/);
expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);
});
- it('OpenCode TUI + openPR + reviewLoop opens the PR but does NOT auto-merge (review gate)', () => {
- // OpenCode can't drive the reviewer loop and PortOS runs no post-exit review
- // for a TUI, so when a review loop is requested the agent must leave the PR
- // open for a reviewer/human rather than merging past the gate.
+ it('OpenCode TUI without openPR pushes the branch but opens no PR', () => {
const prompt = buildLightContextPrompt(
- makeTask({ metadata: { openPR: true, reviewLoop: true } }),
+ makeTask({ metadata: { openPR: false } }),
'/r',
- { branchName: 'claim/issue-3', worktreePath: '/tmp/wt' },
+ { branchName: 'claim/issue-2', worktreePath: '/tmp/wt' },
isTruthyMeta,
{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });
expect(prompt).toMatch(/## Completion Workflow/);
- expect(prompt).toMatch(/gh pr create --fill/);
- // No merge — the PR is left open for review.
+ expect(prompt).not.toMatch(/`\/do:push`/);
+ expect(prompt).toMatch(/git push -u origin claim\/issue-2/);
+ // No PR is opened, so no forge create/merge steps.
+ expect(prompt).not.toMatch(/gh pr create/);
+ expect(prompt).not.toMatch(/glab mr create/);
expect(prompt).not.toMatch(/gh pr merge/);
- expect(prompt).toMatch(/Leave the PR open for review/);
expect(prompt).toMatch(/\.agent-done/);
});
- it('OpenCode TUI without openPR pushes the branch but opens no PR', () => {
+ it('shell-quotes a branch ref containing shell metacharacters in the manual push command', () => {
+ // Git refs can legally contain `;` etc.; the emitted push command must quote it.
const prompt = buildLightContextPrompt(
makeTask({ metadata: { openPR: false } }),
'/r',
- { branchName: 'claim/issue-2', worktreePath: '/tmp/wt' },
+ { branchName: 'weird;rm -rf', worktreePath: '/tmp/wt' },
isTruthyMeta,
{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });
- expect(prompt).toMatch(/## Completion Workflow/);
- expect(prompt).not.toMatch(/`\/do:push`/);
- expect(prompt).toMatch(/git push -u origin claim\/issue-2/);
- // No PR is opened, so no gh pr create / merge steps.
- expect(prompt).not.toMatch(/gh pr create/);
- expect(prompt).not.toMatch(/gh pr merge/);
- expect(prompt).toMatch(/\.agent-done/);
+ expect(prompt).toMatch(/git push -u origin 'weird;rm -rf'/);
+ expect(prompt).not.toMatch(/git push -u origin weird;rm/);
});
it('a non-OpenCode TUI (claude-code-tui) keeps the slashdo /do:pr workflow', () => {
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 5d1130ba83..b6e0ef3bf6 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -17,6 +17,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
+import { shellQuote } from '../lib/shellQuote.js';
import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
@@ -109,12 +110,6 @@ const OUTPUT_FLUSH_INTERVAL_MS = 250;
const DONE_SENTINEL_NAME = '.agent-done';
const DONE_POLL_INTERVAL_MS = 2000;
-function shellQuote(value) {
- const text = String(value ?? '');
- if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
- return `'${text.replace(/'/g, `'\\''`)}'`;
-}
-
/**
* Thin wrapper around `shellService.createShellSession` for the agent TUI
* path. Centralizes the agent-side defaults (kind, label, initialCommand)