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: honor task-specific PR ownership for spawned agents (#6551)
[._.]/ Adam Eivy5f62ec1e47ce
diff --git a/server/lib/README.md b/server/lib/README.mdindex bbac24a39f..c33a662225 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -552,7 +552,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. || `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. `client/src/lib/slashdoCatalog.js` decorates this list with button styling rather than restating it. |-| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); `resolvePrOwnership({task, isTruthyMeta, providerType, providerId, providerCommand, leanMode})` → `{taskOpenPR, agentOwnsPR, prClaimExpected}` — the one reading of the task plus LIVE provider descriptor that both in-process spawners (TUI `finish()`, direct-CLI `close`) hand to `runSpawnerCompletionCleanup`, so the ownership question and the cleanup acting on it cannot disagree; and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |+| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); `resolvePrOwnership({task, isTruthyMeta, persisted, providerId, providerCommand, leanMode})` → `{taskOpenPR, agentOwnsPR, prClaimExpected}` — the persisted-first, task-shape-aware ownership verdict plus provider descriptor that both in-process spawners (TUI `finish()`, direct-CLI `close`) hand to `runSpawnerCompletionCleanup`, so the ownership question and the cleanup acting on it cannot disagree; and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. || `slashdoLoader.js` | Shared slashdo renderer adapter: `loadSlashdoBundle(cmd, {stripFrontmatter, skipIncludes, defer})` returns an entrypoint and supporting files using the bundled transformer; `loadSlashdoFile` returns a self-contained command; `loadSlashdoLib` expands explicit reads for legacy recipes without traversing see-also links. `writeResolvedSlashdoBody(cmd, body, {files})` stages immutable content-addressed bundles under `PATHS.slashdoResolved`, with relative library paths and the entrypoint written last. Missing required references fail dispatch rather than silently removing workflow gates. || `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 `services/promptRunner.js`'s fallback mark-and-pick. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex e0c9db627e..4578bc9d4e 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -542,8 +542,8 @@ export function resolveOwnsPrWorkflow({ persisted, providerId = null, providerCo/*** The three PR answers a spawned run needs, from ONE reading of the task and- * the LIVE provider descriptor. Both in-process spawners call this once — the- * TUI `finish()` path up front, because its merge-gate contract check (#5876)+ * the persisted prompt verdict and provider descriptor. Both in-process spawners+ * call this once — the TUI `finish()` path up front, because its merge-gate contract check (#5876)* reads `agentOwnsPR` before the run completes; the direct-CLI `close` handler* at exit — and hand the result to `runSpawnerCompletionCleanup`, so the* ownership question and the cleanup that acts on it can never read different@@ -556,27 +556,24 @@ export function resolveOwnsPrWorkflow({ persisted, providerId = null, providerCo* when the agent skipped it — failing it at finalize for a PR that is about to* exist would turn a recovered hand-off into a false needs-attention (#3358).*- * The runner-event path answers the same question from the PERSISTED record- * via `resolveOwnsPrWorkflow` — see `runCompletionCleanupSteps`. That record- * is stamped at spawn time from the prompt's own gate (`metadata.ownsPrWorkflow`,- * task-shape aware), which the spawners do not read yet: `agentOwnsPR` here is- * still provider-only, as both spawners derived it before this helper existed.- * Converging the two is #6551.+ * Like the runner-event path, ownership reads the prompt's persisted,+ * task-shape-aware verdict first, falling back to the slash-command gate only+ * for legacy runs without a stamp.** @param {Object} opts* @param {Object} opts.task* @param {(value: unknown) => boolean} opts.isTruthyMeta- * @param {string|null} [opts.providerType] - `'tui' | 'cli'`+ * @param {boolean|undefined} opts.persisted - `metadata.ownsPrWorkflow`* @param {string|null} [opts.providerId]* @param {string|null} [opts.providerCommand]* @param {boolean} [opts.leanMode]* @returns {{ taskOpenPR: boolean, agentOwnsPR: boolean, prClaimExpected: boolean }}*/-export function resolvePrOwnership({ task, isTruthyMeta, providerType = null, providerId = null, providerCommand = null, leanMode = false }) {+export function resolvePrOwnership({ task, isTruthyMeta, persisted, providerId = null, providerCommand = null, leanMode = false }) {const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);return {taskOpenPR,- agentOwnsPR: taskOpenPR && agentOwnsPrWorkflow({ providerType, leanMode }),+ agentOwnsPR: taskOpenPR && resolveOwnsPrWorkflow({ persisted, providerId, providerCommand, leanMode }),prClaimExpected: taskOpenPR && canTypeSlashCommands({ providerId, providerCommand, leanMode }),};}diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 71951fa169..457e6cc97d 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -8,6 +8,7 @@ import {buildSlashdoSection,canTypeSlashCommands,resolveOwnsPrWorkflow,+ resolvePrOwnership,isValidSlashdoCommand,parseExplicitReviewWith,resolveSlashdoInvocation,@@ -454,3 +455,23 @@ describe('parseExplicitReviewWith', () => {});});});++describe('resolvePrOwnership', () => {+ const resolve = (overrides = {}) => resolvePrOwnership({+ task: { metadata: { openPR: true } }, isTruthyMeta: Boolean,+ providerId: 'codex', providerCommand: 'codex', ...overrides,+ });++ it('uses the prompt stamp while keeping claim verification tied to slash commands', () => {+ expect(resolve({ persisted: true })).toEqual({ taskOpenPR: true, agentOwnsPR: true, prClaimExpected: false });+ expect(resolve({ persisted: false, providerId: 'claude-code', providerCommand: 'claude' }))+ .toEqual({ taskOpenPR: true, agentOwnsPR: false, prClaimExpected: true });+ expect(resolve({ persisted: true, task: { metadata: { openPR: false } } }))+ .toEqual({ taskOpenPR: false, agentOwnsPR: false, prClaimExpected: false });+ });++ it('falls back to the legacy slash-command gate without a stamp', () => {+ expect(resolve().agentOwnsPR).toBe(false);+ expect(resolve({ providerId: 'claude-code', providerCommand: 'claude' }).agentOwnsPR).toBe(true);+ });+});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 4fe8baaa0e..ab429dcd87 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -347,6 +347,7 @@ export async function spawnDirectly({executionId,laneName,isTruthyMetaFn,+ ownsPrWorkflow,safetyProfile = null,}) {const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;@@ -906,7 +907,7 @@ export async function spawnDirectly({const prOwnership = resolvePrOwnership({task,isTruthyMeta: isTruthyMetaFn,- providerType: PROVIDER_TYPES.CLI,+ persisted: ownsPrWorkflow,providerId: provider?.id,providerCommand: provider?.command,leanMode: isOllamaClaudeProvider(provider),diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex a89f46d843..fb4a87e058 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -1283,6 +1283,18 @@ describe('stream error containment', () => {expect(finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ prExpected: true }));});+ it('hands a read-only CLI run to PortOS using the prompt ownership stamp', async () => {+ const task = { id: 'task-read-only', description: 'analyze the code', metadata: { openPR: true, readOnly: true } };+ const spawnPromise = spawnDirectly({ ...minimalArgs, task, ownsPrWorkflow: false, isTruthyMetaFn: (v) => v === true });+ await vi.waitFor(() => expect(fakeProcess.listenerCount('close')).toBeGreaterThan(0));+ fakeProcess.emit('close', 0);+ await spawnPromise;+ await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledTimes(1));+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({+ prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: true },+ }));+ });+// The dispatch releases the retry hold with this verdict (#3368 — its ordering// after worktree cleanup is pinned in agentCompletionCleanup.test.js). What// this pins is that the close handler hands it the REAL verdict: a hardcodeddiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 12f040c2a4..d0ad09f790 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -744,6 +744,14 @@ async function runAgentSpawn(task) {? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR): null;+ const ownsPrWorkflow = inlinePrLifecycleSection(task, {+ providerType: provider.type,+ providerId: provider.id,+ providerCommand: provider.command,+ leanMode,+ worktreeInfo,+ isTruthyMetaFn: isTruthyMeta,+ }) !== null;await registerAgent(agentId, task.id, {instanceId,workspacePath,@@ -802,14 +810,7 @@ async function runAgentSpawn(task) {// every one of them — routing a Creative Director reasoning run into the// did-you-open-it net, which then opened a PR for it and filed a HIGH// notification blaming the agent for skipping a step it was never given.- ownsPrWorkflow: inlinePrLifecycleSection(task, {- providerType: provider.type,- providerId: provider.id,- providerCommand: provider.command,- leanMode,- worktreeInfo,- isTruthyMetaFn: isTruthyMeta,- }) !== null,+ ownsPrWorkflow,model: selectedModel,// The reasoning-effort override this run was dispatched with (null when the// task pinned none). Persisted next to the model because the Resume Agent@@ -1037,6 +1038,7 @@ async function runAgentSpawn(task) {laneName,isTruthyMetaFn: isTruthyMeta,leanMode,+ ownsPrWorkflow,useDurableRunner: dispatchUseRunner,safetyProfile,});@@ -1058,6 +1060,7 @@ async function runAgentSpawn(task) {executionId: toolExecution.id,laneName,isTruthyMetaFn: isTruthyMeta,+ ownsPrWorkflow,safetyProfile,});} catch (err) {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 6a537ba906..0845bbe5e4 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -26,7 +26,6 @@ import { prClaimWasVerified, leavesPrForHuman } from '../lib/prDisposition.js';import { resolvePrOwnership } from '../lib/slashdoInvocation.js';import { mergeGateOwed, resolveMergeGateVerdict, buildMergeGateReprompt } from '../lib/mergeGateContract.js';import { probePrForBranch } from './prProbe.js';-import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import * as git from './git.js';import { spawnTuiSessionViaRunner, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';@@ -666,6 +665,7 @@ export async function spawnTuiAgent({executionId,laneName,isTruthyMetaFn,+ ownsPrWorkflow,leanMode = false,useDurableRunner = false,// The public-content execution profile this run enforces (null for an@@ -711,7 +711,7 @@ export async function spawnTuiAgent({const prOwnership = resolvePrOwnership({task,isTruthyMeta: isTruthyMetaFn,- providerType: PROVIDER_TYPES.TUI,+ persisted: ownsPrWorkflow,providerId: provider?.id,providerCommand: provider?.command,leanMode,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex cf905626b2..629d152cea 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -657,6 +657,7 @@ describe('spawnTuiAgent runtime', () => {agentDir,executionId,laneName,+ ownsPrWorkflow: overrides.ownsPrWorkflow ?? !overrides.leanMode,leanMode: overrides.leanMode ?? false,useDurableRunner: overrides.useDurableRunner ?? false,safetyProfile: overrides.safetyProfile ?? null,@@ -2737,6 +2738,27 @@ describe('spawnTuiAgent runtime', () => {beforeEach(() => { sentinelExists = false; });+ it('leaves a read-only run with an open PR to PortOS without a merge re-prompt', async () => {+ vi.mocked(probePrForBranch).mockResolvedValue({+ prState: 'OPEN', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,+ });+ withSentinel('## Summary\nFinished the analysis.');+ const spawnPromise = runSpawn({+ task: { ...openPrTask, metadata: { openPR: true, readOnly: true } },+ ownsPrWorkflow: false,+ });+ await flushMicrotasks();+ sentinelExists = true;+ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;+ expect(probePrForBranch).not.toHaveBeenCalled();+ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({+ prOwnership: expect.objectContaining({ taskOpenPR: true, agentOwnsPR: false }),+ }));+ });+it('re-prompts exactly once when the PR is open and the summary names no blocker, then finalizes on the RE-ARMED watcher even if still open', async () => {vi.mocked(shellService.pasteToSession).mockReturnValue(999);vi.mocked(probePrForBranch).mockResolvedValue({