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
stop an unattended OpenCode run from being handed a question tool it can stall on
[._.]/ Adam Eivy14056858ed76
diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.jsindex cd26159e0c..19bf5a2cbc 100644--- a/server/lib/cliChildEnv.test.js+++ b/server/lib/cliChildEnv.test.js@@ -65,8 +65,9 @@ describe('buildCliChildEnv — layering', () => {expect(declaredModels(env).sort()).toEqual(['llama3.1:8b', 'qwen2.5:7b']);// Non-conflicting provider vars survive.expect(env.API_KEY).toBe('from-provider');- // The stored base is merged, not clobbered.- expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT).permission).toBe('deny');+ // The stored base is merged, not clobbered — the string shorthand expands+ // so the unattended interactive-gate denials can ride alongside it.+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT).permission['*']).toBe('deny');});it('declares the MTPLX models map for a marked OpenCode provider', () => {@@ -205,7 +206,7 @@ describe('buildCliChildEnv — public-review profile, OpenCode harness', () => {it('leaves the ordinary (non-public-review) OpenCode config tool-enabled', () => {const env = buildCliChildEnv({ provider: OLLAMA_OPENCODE, model: 'qwen2.5:7b', cwd: '/tmp/work' });const config = JSON.parse(env.OPENCODE_CONFIG_CONTENT);- expect(config.permission).toBe('deny'); // the provider's stored value, untouched+ expect(config.permission['*']).toBe('deny'); // the provider's stored value, untouchedexpect(config.provider.ollama.models['qwen2.5:7b'].tool_call).toBe(true);expect(config).not.toHaveProperty('tools');});diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsindex b7375f07e7..2c068c9333 100644--- a/server/lib/opencodeConfig.js+++ b/server/lib/opencodeConfig.js@@ -183,6 +183,69 @@ const THINKING_STYLE = {...Object.fromEntries(PROVIDER_GATEWAY_IDS.map((id) => [id, null])),};+const asObject = (value) => (isPlainObject(value) ? value : {});++/**+ * The three OpenCode permissions that open an interactive gate: `question` (the+ * "Should I …? 1. Yes 2. No" selector), and `plan_enter` / `plan_exit` (the plan+ * agent's hand-back to a human). OpenCode denies all three in its OWN built-in+ * agent defaults, and `opencode run` re-denies them explicitly, precisely+ * because nothing can answer them without a person at the terminal.+ *+ * PortOS's config re-ENABLED them. A root `permission` is merged LAST into the+ * agent ruleset and resolved with `findLast`, so the blanket `permission:+ * "allow"` PortOS writes (and that every seeded provider record stores) wins+ * over the vendor denial for every key including these. A denied permission+ * also hides its tool from the model entirely (OpenCode's `visibleTools`), so+ * allowing it is what put the `question` tool back into the schema handed to a+ * local model — an unattended issues-watcher run on `qwen3-coder:30b` then+ * called it and parked on "Should I review these issue comments and PRs?" with+ * nobody there to press a key, burning its whole session. The+ * UNATTENDED_RUN_RULE in `services/agentPromptBuilder.js` tells the agent not+ * to ask; this makes asking unreachable.+ *+ * Every PortOS OpenCode spawn is unattended, so these stay denied+ * unconditionally — this is an enforcement boundary, not a default. The rest of+ * the blanket allow is kept: PortOS agents must not stall on an edit/bash+ * approval either.+ */+const INTERACTIVE_GATE_DENIALS = Object.freeze({+ question: 'deny',+ plan_enter: 'deny',+ plan_exit: 'deny',+});++/**+ * Re-apply {@link INTERACTIVE_GATE_DENIALS} on top of whatever root permission a+ * config carries. OpenCode accepts a string shorthand there (`"allow"`), which+ * it decodes to `{'*': <action>}`; that expansion happens here so the denials+ * have an object to be appended to.+ *+ * **Key order is the enforcement, not cosmetics.** OpenCode flattens the block+ * to a rule list in key order and resolves a permission with `findLast`, where a+ * `'*'` KEY matches every permission name — so the last rule wins outright,+ * specificity notwithstanding, and the denials only bind while they sit after+ * the wildcard. Overwriting a gate key in place would keep that key's ORIGINAL+ * position, so a stored `{ question: 'allow', '*': 'allow' }` would emit+ * `{ question: 'deny', '*': 'allow' }` and the trailing wildcard would allow+ * `question` right back. The gate keys are therefore DROPPED from the base and+ * re-appended, which puts them last whatever order the base used.+ *+ * Mutates and returns `config`; callers pass a config they already own.+ *+ * @param {object} config+ * @returns {object} the same config+ */+function denyInteractiveGates(config) {+ const current = config.permission;+ const base = typeof current === 'string' ? { '*': current } : asObject(current);+ const kept = Object.fromEntries(+ Object.entries(base).filter(([key]) => !Object.hasOwn(INTERACTIVE_GATE_DENIALS, key)),+ );+ config.permission = { ...kept, ...INTERACTIVE_GATE_DENIALS };+ return config;+}+const numberInRange = (value, min, max) => {if (value === null || value === undefined || value === '') return undefined;const n = Number(value);@@ -249,6 +312,11 @@ export function buildAgentGeneration(generation, providerKey) {* is invented), identical to the shipped base. When `base` is absent/unusable,* the canonical endpoint for the selected local runtime is used.*+ * The one field that is NOT purely preserved is the root `permission`: the+ * interactive-gate denials are re-applied over it (see `denyInteractiveGates`),+ * because a PortOS spawn has no human to answer a gate. Everything else the+ * base sets there survives.+ ** NOT the whole config: `small_model` is applied downstream by* `buildOpencodeEnvVars`, which is the only caller that knows THIS run's single* model (this one takes a list). A config built here alone is unpinned.@@ -292,7 +360,7 @@ export function buildOpencodeConfig(models, base = null, providerKey = 'ollama',...build,};}- return config;+ return denyInteractiveGates(config);}// `'*'` is OpenCode's documented wildcard for a tool map; `deny` is its hard@@ -309,8 +377,6 @@ const DENY_ALL_TOOLS = Object.freeze({ '*': false });const DENY_ALL_PERMISSIONS = 'deny';const DENY_ALL_AGENT_PERMISSIONS = Object.freeze({ edit: 'deny', bash: 'deny', webfetch: 'deny' });-const asObject = (value) => (isPlainObject(value) ? value : {});-/*** Harden an OpenCode config for the `no-tool` public-review posture.*diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.jsindex 3ebf351bc6..645710e5d0 100644--- a/server/lib/opencodeConfig.test.js+++ b/server/lib/opencodeConfig.test.js@@ -10,6 +10,15 @@ import {import { LOCAL_RUNTIMES } from './localProviderRuntime.js';import { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE } from './agentExecutionProfiles.js';+// Spelled out rather than imported from the module under test: these three+// permissions ARE the contract (OpenCode's own defaults deny them because no+// unattended run can answer the gate they open), so an assertion that reads+// them back out of the source would prove nothing. Named once so a fourth gate+// is one edit — every assertion below compares the WHOLE permission object, so+// adding one to the source without adding it here fails loudly.+const GATES = { question: 'deny', plan_enter: 'deny', plan_exit: 'deny' };+const gated = (wildcard) => ({ '*': wildcard, ...GATES });+describe('toBareModelIds', () => {it('strips the ollama/ namespace, drops empties, and dedupes', () => {expect(toBareModelIds(['ollama/qwen2.5:7b', 'qwen2.5:7b', '', null, 'llama3.1:8b']))@@ -42,7 +51,7 @@ describe('toBareModelIds', () => {describe('buildOpencodeConfig', () => {it('returns base config without a models map when no model provided', () => {const cfg = buildOpencodeConfig(null);- expect(cfg.permission).toBe('allow');+ expect(cfg.permission).toEqual(gated('allow'));expect(cfg.provider.ollama).toMatchObject({npm: '@ai-sdk/openai-compatible',name: 'Ollama (local)',@@ -85,7 +94,7 @@ describe('buildOpencodeConfig', () => {},};const cfg = buildOpencodeConfig('qwen2.5:7b', base);- expect(cfg.permission).toBe('ask');+ expect(cfg.permission).toEqual(gated('ask'));expect(cfg.provider.ollama.options.baseURL).toBe('http://gpu-box:11434/v1');// hand-maintained model kept, runtime model addedexpect(cfg.provider.ollama.models['kept:70b']).toBeDefined();@@ -147,7 +156,7 @@ describe('buildOpencodeConfigContent', () => {it('serializes the base config (no models) for null model', () => {const parsed = JSON.parse(buildOpencodeConfigContent(null));- expect(parsed.permission).toBe('allow');+ expect(parsed.permission).toEqual(gated('allow'));expect(parsed.provider.ollama.models).toBeUndefined();});});@@ -180,7 +189,7 @@ describe('buildOpencodeEnvVars', () => {'opencode/big-pickle',);const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);- expect(cfg).toEqual({ permission: 'allow', small_model: 'opencode/big-pickle' });+ expect(cfg).toEqual({ permission: gated('allow'), small_model: 'opencode/big-pickle' });expect(cfg.provider).toBeUndefined();// No gateway key env var rides along — OpenCode authenticates Zen itself.expect(Object.keys(result)).toEqual(['OPENCODE_CONFIG_CONTENT']);@@ -193,7 +202,7 @@ describe('buildOpencodeEnvVars', () => {'opencode/big-pickle',);expect(JSON.parse(result.OPENCODE_CONFIG_CONTENT)).toEqual({- permission: 'ask',+ permission: gated('ask'),small_model: 'opencode/mimo-v2.5-free',});});@@ -467,6 +476,57 @@ describe('small-model pin', () => {});});+describe('interactive-gate denials', () => {+ // OpenCode resolves a permission with findLast over the config's entries, and+ // the root block is merged after the vendor's own agent defaults — so the+ // blanket allow PortOS writes used to override OpenCode's built-in+ // question/plan_enter/plan_exit denials and hand an unattended local model a+ // `question` tool it then stalled the whole run on.+ it('denies every interactive gate under the blanket allow, wildcard first', () => {+ const permission = buildOpencodeConfig('qwen3', null, 'ollama').permission;+ // Order is load-bearing: OpenCode resolves a permission by findLast over+ // the config's entries, so a denial after the wildcard is what wins.+ expect(Object.keys(permission)[0]).toBe('*');+ expect(permission).toEqual(gated('allow'));+ });++ it('overrides a stored config that allows a gate outright', () => {+ const stored = JSON.stringify({ permission: { '*': 'allow', question: 'allow' } });+ const config = JSON.parse(buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: true, models: ['qwen3'], envVars: { OPENCODE_CONFIG_CONTENT: stored } },+ 'qwen3',+ ).OPENCODE_CONFIG_CONTENT);+ expect(config.permission.question).toBe('deny');+ expect(config.permission['*']).toBe('allow');+ });++ // OpenCode resolves with findLast and a '*' KEY matches every permission, so+ // the last rule wins outright. Overwriting a gate key in place would keep its+ // original position — a stored config listing 'question' BEFORE the wildcard+ // would emit { question: 'deny', '*': 'allow' } and the trailing wildcard+ // would allow it right back. The denials have to be re-appended, not merged.+ it('re-appends a gate the stored block listed before its wildcard', () => {+ const stored = JSON.stringify({ permission: { question: 'allow', '*': 'allow' } });+ const config = JSON.parse(buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: true, models: ['qwen3'], envVars: { OPENCODE_CONFIG_CONTENT: stored } },+ 'qwen3',+ ).OPENCODE_CONFIG_CONTENT);+ const keys = Object.keys(config.permission);+ expect(keys.indexOf('question')).toBeGreaterThan(keys.indexOf('*'));+ expect(config.permission).toEqual(gated('allow'));+ });++ it('keeps the rest of a stored permission block', () => {+ const stored = JSON.stringify({ permission: { '*': 'allow', bash: 'ask' } });+ const config = JSON.parse(buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: true, models: ['qwen3'], envVars: { OPENCODE_CONFIG_CONTENT: stored } },+ 'qwen3',+ ).OPENCODE_CONFIG_CONTENT);+ expect(config.permission.bash).toBe('ask');+ expect(config.permission.question).toBe('deny');+ });+});+describe('hardenOpencodeConfigForNoTool', () => {// OpenCode has no read-only argv flag — this IS the vendor's enforced recipe// for the pr-reviewer eligibility gate, so it has to override a user's storeddiff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 10235a5d9f..4bdb79f196 100644--- a/server/services/issueWatcher.js+++ b/server/services/issueWatcher.js@@ -49,6 +49,9 @@ const MAX_TOTAL_DIFF_CHARS = MAX_DIFF_CHARS * MAX_PULL_REQUESTS_PER_RUN;const MAX_ISSUE_COMMENTS_PER_RUN = 25;const MAX_ISSUE_CONTEXT_CHARS = 40_000;const MAX_PENDING_ISSUE_COMMENTS = 250;+// How many carried-over issues `pruneClosedIssueComments` re-reads at once. Each+// read forks a gh child, and the queue it walks is capped at 250 entries.+const ISSUE_STATE_PROBE_BATCH = 10;// One entry per PR, so this only grows with the count of external PRs that were// reviewed and did not merge. Bounded anyway: the ledger lives in app state,// which is read on every gather pass.@@ -67,6 +70,9 @@ let stateWriteTail = Promise.resolve();const text = (value, max = 8_000) => typeof value === 'string' ? value.trim().slice(0, max) : '';const fullText = (value) => typeof value === 'string' ? value : '';const sameLogin = (a, b) => Boolean(a && b) && String(a).toLowerCase() === String(b).toLowerCase();+// GitHub reports issue state as `open`/`closed`; normalize once so every caller+// that gates on "still actionable" agrees, including on a missing state field.+const isOpenIssue = (issue) => String(issue?.state || '').toLowerCase() === 'open';const MODEL_ABUSE_REPORT_LIMIT = 100;function flattenPages(value) {@@ -518,6 +524,45 @@ async function gatherIssueComments(ctx, { since, ownerLogin }) {return { ok: true, comments, assignments };}+/**+ * Drop pending comments whose issue has closed since it was gathered.+ *+ * The gather query is `state=open`, so a fresh comment always belongs to an open+ * issue — but `state.pendingIssueComments` carries a comment forward across runs+ * until the reasoning agent returns a decision for it, and nothing re-checked+ * the issue in between. The output pass DOES re-check (`readCurrentIssueComment`+ * returns null for a non-open issue), so a comment on an issue closed in the+ * meantime could never be handled: it burned a slot in every prompt — the agent+ * dutifully reasoning about an issue already resolved — for+ * MAX_PENDING_ISSUE_COMMENT_TICKS runs, then raised a HIGH-priority "needs+ * attention" notification for work that no longer existed.+ *+ * Only entries this run did NOT gather are re-read; the freshly gathered ones+ * came from the `state=open` list moments ago. A read failure keeps the entry —+ * an unreachable forge is not evidence that an issue closed.+ *+ * The reads run concurrently in bounded batches: every `runJson` spawns a `gh`+ * subprocess, and the pending queue holds up to MAX_PENDING_ISSUE_COMMENTS+ * entries, so an unbounded `Promise.all` over it would fork hundreds of children+ * at once.+ */+async function pruneClosedIssueComments(ctx, items, freshIssueNumbers) {+ const carried = [...new Set(items.map((item) => item.issueNumber))]+ .filter((number) => !freshIssueNumbers.has(number));+ if (carried.length === 0) return items;+ const closed = new Set();+ for (let start = 0; start < carried.length; start += ISSUE_STATE_PROBE_BATCH) {+ const batch = carried.slice(start, start + ISSUE_STATE_PROBE_BATCH);+ const issues = await Promise.all(batch.map((number) => (+ runJson(apiArgs(ctx, `repos/${ctx.repoFullName}/issues/${number}`), ctx)+ )));+ batch.forEach((number, index) => {+ if (issues[index] && !isOpenIssue(issues[index])) closed.add(number);+ });+ }+ return closed.size === 0 ? items : items.filter((item) => !closed.has(item.issueNumber));+}+async function readPullRequest(ctx, number) {return runJson(['pr', 'view', String(number), '--repo', ctx.repoSpec,@@ -588,7 +633,7 @@ async function eligibilityFactsStillCurrent(ctx, pr, target) {if (issues.some((issue, index) => issue?.number !== expected.linkedIssueNumbers[index])) return false;const openIssues = issues.filter((issue) => (- !issue.pull_request && String(issue.state || '').toLowerCase() === 'open'+ !issue.pull_request && isOpenIssue(issue)));const openLinkedIssueNumbers = openIssues.map((issue) => issue.number);const openerAssignedIssueNumbers = openIssues@@ -1076,7 +1121,11 @@ export async function buildTaskInput({ app } = {}) {pendingById.set(key, { ...item, ticks: existing?.ticks || item.ticks || 0 });}}- const allPendingIssueComments = [...pendingById.values()];+ const allPendingIssueComments = await pruneClosedIssueComments(+ ctx,+ [...pendingById.values()],+ new Set(issueResult.comments.map((item) => item.issueNumber)),+ );const pendingIssueComments = allPendingIssueComments.slice(-MAX_PENDING_ISSUE_COMMENTS);if (allPendingIssueComments.length > pendingIssueComments.length) {console.warn(`⚠️ issue-watcher: dropped ${allPendingIssueComments.length - pendingIssueComments.length} oldest pending issue comment(s) for ${app.name} to preserve queue progress.`);@@ -1185,7 +1234,7 @@ async function readCurrentIssueComment(ctx, item) {runJson(apiArgs(ctx, `repos/${ctx.repoFullName}/issues/${item.issueNumber}`), ctx),runJson(apiArgs(ctx, `repos/${ctx.repoFullName}/issues/${item.issueNumber}/comments/${item.commentId}`), ctx),]);- if (!issue || String(issue.state || '').toLowerCase() !== 'open' || !comment || comment.id !== item.commentId) return null;+ if (!isOpenIssue(issue) || !comment || comment.id !== item.commentId) return null;return {...item,issueTitle: fullText(issue.title),diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.jsindex d4837df0ad..cffbd15cff 100644--- a/server/services/issueWatcher.test.js+++ b/server/services/issueWatcher.test.js@@ -356,6 +356,64 @@ describe('buildTaskInput', () => {expect(apps.get(APP.id).issueWatcherState.pendingIssueComments).toEqual([]);});+ // A carried-over pending comment is the only way an issue that is no longer+ // open reaches the reasoning agent: the gather query is state=open, but the+ // pending queue is only drained by a decision. The output pass refuses to act+ // on a closed issue, so such an entry could only be re-prompted every run+ // until it timed out and raised a false "needs attention" alarm.+ it('drops a carried-over comment whose issue has closed since it was gathered', async () => {+ apps.set(APP.id, {+ ...APP,+ issueWatcherState: {+ cursor: '2026-08-29T00:00:00.000Z',+ pendingIssueComments: [{+ issueNumber: 6072,+ issueTitle: 'Already resolved',+ issueBody: 'done',+ commentId: 4242,+ commentAuthor: 'alice',+ commentBody: 'What do you think?',+ commentUrl: 'https://github.com/o/r/issues/6072#issuecomment-4242',+ claimRequest: false,+ claimAssignable: false,+ }],+ },+ });+ installDefaultGhMock({ pr: null, issueDetails: { 6072: { number: 6072, state: 'closed', title: 'Already resolved' } } });++ const result = await buildTaskInput({ app: apps.get(APP.id) });++ expect(result).toEqual({ skip: { reason: 'no-cognitive-activity' } });+ expect(apps.get(APP.id).issueWatcherState.pendingIssueComments).toEqual([]);+ });++ // An unreachable forge is not evidence that an issue closed — losing the+ // comment would silently drop a real question from a contributor.+ it('keeps a carried-over comment when the issue re-read fails', async () => {+ const pending = {+ issueNumber: 6072,+ issueTitle: 'Still open',+ issueBody: 'body',+ commentId: 4242,+ commentAuthor: 'alice',+ commentBody: 'What do you think?',+ commentUrl: 'https://github.com/o/r/issues/6072#issuecomment-4242',+ claimRequest: false,+ claimAssignable: false,+ };+ apps.set(APP.id, { ...APP, issueWatcherState: { cursor: '2026-08-29T00:00:00.000Z', pendingIssueComments: [pending] } });+ installDefaultGhMock({ pr: null });+ interceptGh((args) => {+ if (args[0] === 'api' && args.includes('repos/o/r/issues/6072')) throw new Error('HTTP 503');+ return undefined;+ });++ const result = await buildTaskInput({ app: apps.get(APP.id) });++ expect(result.prompt).toContain('Issue #6072: Still open');+ expect(apps.get(APP.id).issueWatcherState.pendingIssueComments).toEqual([{ ...pending, ticks: 0 }]);+ });+it('continues to cognition when an explicit volunteer cannot be assigned', async () => {installVolunteerGhMock();interceptGh((args) => {