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: stop an OpenCode TUI completion run from refusing its own sentinel (#7405)
[._.]/ Adam Eivy3b0a3889b0b7
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.jsindex cef704ae33..067fdd0efe 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -65,6 +65,7 @@ import {isCursorProvider,isClaudeCommand,hasModelFlag,+ argvHasFlag,resolveInjectedTuiModel,resolveClaudeCliModel,buildCodexStartupArgs,@@ -355,6 +356,34 @@ function opencodeCliArgs(baseArgs, { model, provider }) {return appendOpencodeModel(args, provider, model);}+/**+ * Pin OpenCode's tool-enabled `build` agent on an ordinary interactive TUI+ * session, unless the argv already selects one.+ *+ * Unlike every other vendor here, OpenCode's ROLE — not just its permissions —+ * is argv/config state, and the seeded TUI provider records ship `args: []`.+ * A bare `opencode` therefore opens in whatever agent that install defaults to+ * (or last used), which is how a task-completion run came up as a read-only+ * specialist and refused to write its own completion sentinel, asking a human+ * that an unattended run has none of (#7405). The prompt cannot fix that: the+ * host role outranks prompt text for a small local model, so the flag is the+ * fix and the prompt's sentinel-write permission line is the belt.+ *+ * Idempotent, and scoped to the interactive path only: `applyCommandDefaults`+ * is never reached by a public-review posture (its argv comes from+ * `buildVendorSpawnConfig`), so pinning the tool-enabled agent here cannot+ * widen the `--agent plan` recipe that hardens a public-content review.+ *+ * @param {string[]} args+ * @returns {string[]}+ */+function ensureOpencodeTuiArgs(args = []) {+ const out = [...args];+ // `--agent` is spelled the same on the bare TUI binary and on `opencode run`.+ if (!argvHasFlag(out, ['--agent'])) out.push('--agent', OPENCODE_BUILD_AGENT);+ return out;+}+/*** An OpenCode wrapper this install can actually run the tool-free gate on.* Three conditions, each closing a different way the stage would otherwise be@@ -434,6 +463,7 @@ const OPENCODE = {// No dedicated matchCliProvider — matches by command, same as matchCommand// (buildVendorCliArgs/buildVendorSpawnConfig fall back to matchCommand when// matchCliProvider is absent).+ tuiArgs: ensureOpencodeTuiArgs,cliArgs: opencodeCliArgs,spawnArgs: defaultSpawnArgs(opencodeCliArgs, 'opencode'),publicReview: {diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 58846a6d4d..cebac4c17b 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -647,6 +647,24 @@ describe('tuiHandshake.applyCommandDefaults', () => {// A user-pinned short posture is respected.expect(applyCommandDefaults('kimi', ['-y'])).toEqual(['-y']);});++ // #7405: the seeded OpenCode TUI records ship `args: []`, so a bare+ // `opencode` opened in whatever agent that install defaults to. A+ // task-completion run came up as a read-only specialist and refused to write+ // its own completion sentinel, stalling an unattended run on a question.+ it('pins the tool-enabled OpenCode agent on an interactive session', () => {+ expect(applyCommandDefaults('opencode', [])).toEqual(['--agent', 'build']);+ });++ it('respects an OpenCode agent the operator already pinned, in either flag form', () => {+ expect(applyCommandDefaults('opencode', ['--agent', 'plan'])).toEqual(['--agent', 'plan']);+ expect(applyCommandDefaults('opencode', ['--agent=plan'])).toEqual(['--agent=plan']);+ });++ it('pins the OpenCode agent for a path-configured binary too', () => {+ expect(applyCommandDefaults('/opt/homebrew/bin/opencode', ['-m', 'mtplx/example-model']))+ .toEqual(['-m', 'mtplx/example-model', '--agent', 'build']);+ });});describe('tuiHandshake.buildTuiInvocation', () => {@@ -813,7 +831,8 @@ describe('tuiHandshake.buildTuiInvocation', () => {const provider = { id: 'opencode-ollama-tui', command: 'opencode', args: [], ollamaBacked: true };const out = buildTuiInvocation(provider, 'qwen2.5:7b');expect(out.command).toBe('opencode');- expect(out.args).toEqual(['--model', 'ollama/qwen2.5:7b']);+ // `--agent build` is the TUI arm's role pin (#7405) — see applyCommandDefaults.+ expect(out.args).toEqual(['--agent', 'build', '--model', 'ollama/qwen2.5:7b']);});it('handles a provider with no args (treats as empty array)', () => {@@ -887,7 +906,7 @@ describe('tuiHandshake.buildTuiInvocation', () => {{ id: 'opencode-tui', command: 'opencode', args: [], effort: 'high' },'qwen3',);- expect(out.args).toEqual(['--model', 'qwen3']);+ expect(out.args).toEqual(['--agent', 'build', '--model', 'qwen3']);});// agy serves its `claude-*` ids through Google's own gateway, so a Bedrock box@@ -1522,8 +1541,11 @@ describe('tuiHandshake — parity with the shipped provider catalog', () => {// claude's `--dangerously-skip-permissions` rides in the seed `args`.['claude', { channel: 'args', marker: '--dangerously-skip-permissions' }],// opencode has no argv approval/trust gate; its permission posture is- // configured through OPENCODE_CONFIG_CONTENT (see cliChildEnv.js).- ['opencode', { channel: 'envVars', marker: '"permission":"allow"' }],+ // configured through OPENCODE_CONFIG_CONTENT (see cliChildEnv.js). Its+ // builder arm injects a ROLE rather than a posture — `--agent build` pins+ // the tool-enabled agent so a bare session cannot open as OpenCode's+ // read-only one and refuse to write its own completion sentinel (#7405).+ ['opencode', { channel: 'envVars', marker: '"permission":"allow"', builderInjects: ['--agent', 'build'] }],]);it('parses the shipped catalog (guards against a silently empty walk)', () => {@@ -1558,8 +1580,12 @@ describe('tuiHandshake — parity with the shipped provider catalog', () => {const exemption = POSTURE_NOT_FROM_BUILDER.get(command);if (exemption) {- it('injects nothing (its posture comes from another channel)', () => {- expect(applyCommandDefaults(command, [])).toEqual([]);+ // An exempt vendor's POSTURE comes from another channel, but its arm may+ // still inject something else (opencode's agent-role pin). Whatever that+ // is must be declared here, so the assertion stays exact and a new,+ // undeclared injection still fails.+ it('injects only what its exemption declares (its posture comes from another channel)', () => {+ expect(applyCommandDefaults(command, [])).toEqual(exemption.builderInjects || []);});if (exemption.channel) {diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 58dc1b2773..fe60135c61 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1518,9 +1518,12 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/READ THAT FILE/);expect(prompt).toMatch(/\/data\/slashdo-resolved\/local-agent-review-loop\.md/);expect(prompt).not.toMatch(/RECIPE HEADER/);- // The fixed review-blocked publication/merge contract adds prose to the- // prompt, but the 40KB recipe itself must still stay in the staged file.- expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(25_000);+ // The fixed review-blocked publication/merge contract and the sentinel+ // write-permission note (#7405) both add prose to the prompt, but the+ // 40KB recipe itself must still stay in the staged file — which is the+ // only thing this ceiling is measuring, so it carries growth headroom+ // rather than pinning today's byte count.+ expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(27_000);});it('quotes a hostile branch ref inert in the PR-create command line', () => {@@ -1790,6 +1793,43 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/watches this sentinel/);});+ // #7405 — an OpenCode MTPLX TUI task-completion run read its host's+ // read-only role as covering the sentinel too ("the edits/sentinel can't+ // happen here"), then went looking for the path in `runner-state.json` /+ // `state.json` because a SIBLING run's agent id was visible in the shared+ // checkout's branch state. It asked a human how to proceed and stalled: an+ // unattended run has nobody to answer. Both halves are prompt contract.+ describe('sentinel-write permission (#7405)', () => {+ const SENTINEL_PATH = '/shared-checkout/.agent-done-agent-07ddbb85';++ const completionPrompt = (metadata = {}) => buildLightContextPrompt(+ makeTask({ metadata }),+ '/shared-checkout', null, isTruthyMeta,+ { isTui: true, agentId: 'agent-07ddbb85', providerId: 'opencode-mtplx-tui', providerCommand: 'opencode' });++ it('gives a worktree-less TUI completion run one canonical sentinel path, no read-only banner, and permission to write it', () => {+ const prompt = completionPrompt();+ // The path is agent-scoped and derived from THIS run's cwd + id, so a+ // sibling agent id elsewhere in the shared checkout cannot change it.+ expect(prompt).toContain(SENTINEL_PATH);+ // EXACTLY one — a second candidate is what sent the stalled run hunting+ // through state files instead of writing the file it was handed.+ expect([...new Set(prompt.match(/[\w/.-]*\.agent-done[\w.-]*/g))]).toEqual([SENTINEL_PATH]);+ expect(prompt).not.toMatch(/## Read-Only Task/);+ expect(prompt).toMatch(/Writing that one file is ALWAYS permitted/);+ // No second place to look the path up.+ expect(prompt).toMatch(/Do NOT look one up in `runner-state\.json`, `state\.json`, a branch name, or a worktree name/);+ });++ it('carves the sentinel out of the read-only do-not-modify rule', () => {+ const prompt = completionPrompt({ readOnly: true });+ expect(prompt).toMatch(/## Read-Only Task/);+ // The banner and the sentinel instruction sit in the same section; a+ // small local model read them as a contradiction and wrote nothing.+ expect(prompt).toMatch(/no read-only, do-not-modify, or restricted-session rule applies to it/);+ });+ });+it('read-only on a non-TUI (CLI) provider gets the bare notice, no sentinel', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { readOnly: true } }),diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex bc4c0f8093..e358c7d010 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1174,6 +1174,18 @@ export async function spawnTuiAgent({const { finalSuccess, finalError, terminatedByUser } = finalizeOutcome;+ // Name the path the run was supposed to write when it ends without one.+ // The sentinel is the PRIMARY finalize path, so reaching here without it+ // means the run either died or talked itself out of the write — and the+ // second shape is silent today: a model that decided its session was not+ // allowed to write the file (#7405) leaves an ordinary "TUI agent ended"+ // line and nothing an operator can grep for. Placed after the shared+ // finalize, so the paused / host-abandoned / user-terminated paths (which+ // legitimately produce no sentinel) have already returned or are excluded.+ if (doneSentinelPath && !terminatedByUser && !sentinelPresent()) {+ emitLog('warn', `⚠️ ${agentId} finalized (${reason}) with no completion sentinel — expected ${doneSentinelPath}`, { agentId });+ }+// output.txt has already been incrementally appended via the spooler;// do NOT writeFile() it from the output buffer at finalize — the buffer is// capped at OUTPUT_BUFFER_CAP and would silently truncate the on-diskdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex a8ce677240..bd8c647e98 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -465,7 +465,8 @@ describe('agent TUI spawning', () => {id: 'opencode-ollama-tui', type: 'tui', command: 'opencode', args: [], ollamaBacked: true,}, 'qwen2.5:7b');expect(config.command).toBe('opencode');- expect(config.args).toEqual(['--model', 'ollama/qwen2.5:7b']);+ // `--agent build` is the TUI arm's role pin (#7405) — see applyCommandDefaults.+ expect(config.args).toEqual(['--agent', 'build', '--model', 'ollama/qwen2.5:7b']);});it('respects a user-baked --model pin on an OpenCode TUI and does not duplicate it', () => {@@ -473,7 +474,7 @@ describe('agent TUI spawning', () => {id: 'opencode-ollama-tui', type: 'tui', command: 'opencode',args: ['--model', 'ollama/custom'], ollamaBacked: true,}, 'qwen2.5:7b');- expect(config.args).toEqual(['--model', 'ollama/custom']);+ expect(config.args).toEqual(['--model', 'ollama/custom', '--agent', 'build']);});it('falls back to the default command via id heuristic when command is omitted', () => {diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 7193e360a2..717bc19f8c 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -25,6 +25,28 @@ const AUDIT_FLOW_GUIDANCE = 'Follow the bundled Better audit workflow through reconst RELEASE_FLOW_GUIDANCE = 'Follow the bundled release workflow through its final verification and report. It owns release delivery; do not stop at a prepared commit or hand publication back to PortOS. If it cannot complete, report INCOMPLETE and the first unverified checkpoint instead of claiming a successful release.';+/**+ * Why a run that was told not to touch the repository may still write ONE file.+ *+ * A completion sentinel is PortOS's done-signal, not a repository edit — but+ * every section that emits one also carries a "do not modify anything" rule+ * (read-only, reasoning-only, no-code-output), and the agent's HOST may hand it+ * a restricted role on top of that. A small local model resolves the apparent+ * conflict the safe way and writes nothing, then asks a human an unattended run+ * does not have: an OpenCode MTPLX TUI run stalled exactly there, refusing the+ * sentinel because "the current session is a read-only file-search specialist"+ * (#7405). Stating the carve-out is what makes the write reachable.+ *+ * The second sentence is the other half of that stall: the same run went+ * looking for its sentinel path in `runner-state.json` / `state.json` after+ * noticing a SIBLING run's agent id in the shared checkout's branch state, and+ * never wrote one. There is no such lookup — `doneSentinelPath(cwd, agentId)`+ * resolves the single path for both the prompt and every watcher — and a+ * worktree-less run legitimately shares its workspace with other live agents,+ * so a foreign agent id in git or state is expected and means nothing here.+ */+export const SENTINEL_WRITE_PERMISSION_NOTE = 'Writing that one file is ALWAYS permitted, whatever the task shape or your host role says — it is PortOS\'s completion signal, not a repository edit, so no read-only, do-not-modify, or restricted-session rule applies to it. Use the sentinel path exactly as printed in this section: it is this run\'s only one. Do NOT look one up in `runner-state.json`, `state.json`, a branch name, or a worktree name, and do NOT treat another agent id in this workspace as a conflict — the filename already scopes the sentinel to you.';+const REASONING_ONLY_BULLET = '**This is a reasoning-only task.** The worktree is discarded on exit — do NOT commit, push, merge, or open a PR. Write your result to the completion sentinel (see the Completion section) and stop.';const DISCARD_WORKTREE_HYGIENE = '- **Do NOT commit, push, or open a PR.** This worktree is discarded on exit — your only output is the completion sentinel (see the Completion section above).';@@ -344,7 +366,9 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {`## ${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}`,'This is a reasoning task, not a code change. The worktree you are in is **discarded on exit** — any commits, pushes, or PRs are thrown away and have no effect. Do NOT run `/do:push`, `/do:pr`, `git commit`, `git push`, or open a pull request.','',- `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`,+ '',+ SENTINEL_WRITE_PERMISSION_NOTE].join('\n');}@@ -361,12 +385,14 @@ export function buildProgrammaticOutputCompletionSection(sentinelPath) {* sentinel, so they get the bare notice only.*/export function buildReadOnlyCompletionSection({ isTui = false, sentinelPath = null } = {}) {- const notice = '## Read-Only Task\nDo NOT commit, push, or modify any files. Read data and report findings only.';+ const notice = '## Read-Only Task\nDo NOT commit, push, or modify any files in the repository. Read data and report findings only.';if (!isTui || !sentinelPath) return notice;return [notice,'',- `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `When you have finished, write a short markdown summary of what you found (and where you recorded it) to \`${sentinelPath}\`, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`,+ '',+ SENTINEL_WRITE_PERMISSION_NOTE].join('\n');}@@ -387,7 +413,9 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPathreturn [notice,'',- `Your task is complete once that request succeeds. Then write a short summary, including any structured report required by your task, to \`${sentinelPath}\` and stop — PortOS watches this sentinel and finalizes the run shortly after it appears. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`+ `Your task is complete once that request succeeds. Then write a short summary, including any structured report required by your task, to \`${sentinelPath}\` and stop — PortOS watches this sentinel and finalizes the run shortly after it appears. Do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`,+ '',+ SENTINEL_WRITE_PERMISSION_NOTE].join('\n');}@@ -631,6 +659,8 @@ export function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail)return [`${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS watches it and finalizes the run shortly after it appears. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,'',+ ` ${SENTINEL_WRITE_PERMISSION_NOTE}`,+ '',' ```bash',` cat > "${sentinelPath}" <<'EOF'`,' ## Summary',