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

refactor: resolve the agent completion mode once instead of in five flag ladders (#6616)

[._.]/ Adam Eivye241cb63c6f4
diff --git a/server/lib/README.md b/server/lib/README.md
index 9b33ae6c4b..36aed4ba51 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -235,6 +235,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `callerModePolicy.js` | The one caller EXECUTION-MODE policy: `CALLER_MODE_POLICIES` (`agent-harness`, `cli-harness`, `direct-api`, `any-text`) plus `resolveCallerModePolicy` / `allowedModesFor` / `callerModeRejection` / `isCallerModeEligible` / `filterCallerModeEligible`. Answers "may THIS caller run on THAT route mode?" for an explicit pin, `activeProvider` inheritance and every fallback candidate alike — `allowedModesFor()` is what rides on `requestCapabilities.allowedModes` into the toolkit's `getFallbackProvider`. Pure and dependency-light so the out-of-process autofixer can import it; `enabled`/benched state, prerequisites and text-transport consent stay with their existing owners. Unknown never becomes true: a record with no executable mode, and a required model capability with no positive evidence, are both refused. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: filters the inherited base to runtime essentials/provider auth, then layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. |
+| `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. |
diff --git a/server/lib/agentCompletionMode.js b/server/lib/agentCompletionMode.js
new file mode 100644
index 0000000000..50c5f10e80
--- /dev/null
+++ b/server/lib/agentCompletionMode.js
@@ -0,0 +1,148 @@
+/**
+ * The ONE completion-contract decision for an agent prompt.
+ *
+ * A task's completion contract — what its deliverable is, and therefore
+ * whether it may commit, push, open a PR, write a sentinel, or simply reply —
+ * used to be re-derived by five separate flag ladders in
+ * `agentPromptBuilder.js`, each over the same flags in a different order with
+ * a different subset of arms. The ordering contract between them was held by
+ * prose comments, and two of them had drifted: an `api`-provider task with a
+ * tool-free or read-only posture rendered a prompt whose `## Instructions`
+ * step 4 told it to commit while `## Git Hygiene` told it there was no git at
+ * all (#6616).
+ *
+ * `resolveCompletionMode` is that decision, made once. Call sites branch on
+ * the returned key and never re-test the flags themselves, so a new completion
+ * mode is added HERE and rendered per site — it can no longer be added to four
+ * ladders out of five.
+ *
+ * A mode is the *contract*, not the *host*: several sites legitimately render
+ * two modes the same way (the light path emits one TUI completion section for
+ * both TUI modes, and the full path emits nothing for the modes whose contract
+ * it carries in another section). That is a rendering choice each site owns.
+ */
+
+/**
+ * Does PortOS land this run's branch ITSELF? True under the worktree-without-PR
+ * posture (`useWorktree: true`, `openPR: false`): once the agent exits,
+ * `agentWorktreeCleanup.js` merges the worktree branch into the source checkout
+ * and deletes it (`removeWorktree` with `merge: true`). Nothing on that path
+ * reads a remote copy of the branch, so a push has no consumer — and because
+ * the local branch is deleted the moment the merge lands, a pushed copy becomes
+ * an orphan that the post-completion audit (`agentRepoStateVerification.js`)
+ * reports as "remote branch was never deleted" and hands to a recovery agent.
+ * The `/do:push` completion step this posture used to get produced exactly
+ * that, run after run (every module-hygiene audit on 2026-09-06/07, and user
+ * tasks with the same posture before them — each followed by a recovery agent
+ * that then pushed the merged commit straight to the default branch). So under
+ * this posture the contract is commit-only, on every path that can type slashdo.
+ *
+ * The other worktree contracts (discard, claim flow, PR follow-up, no-code) are
+ * decided BEFORE this question is asked — callers apply their precedence first,
+ * the way `buildCompletionGuidelineBullet` does.
+ *
+ * @param {object} params
+ * @param {object|null} params.worktreeInfo
+ * @param {boolean} params.willOpenPR
+ * @returns {boolean}
+ */
+export function portosMergesBranchOnExit({ worktreeInfo, willOpenPR }) {
+ return Boolean(worktreeInfo) && !willOpenPR;
+}
+
+export const COMPLETION_MODES = Object.freeze({
+ /** No tools at all — the reply itself is the deliverable. */
+ TOOL_FREE: 'tool-free',
+ /** Sandboxed stage whose output is the JSON payload in the sentinel. */
+ SENTINEL_PAYLOAD: 'sentinel-payload',
+ /** Deliverable is an API call or command performed during the run. */
+ ACTION_OUTPUT: 'action-output',
+ /** Reasoning-only worktree, thrown away on exit; sentinel is the output. */
+ DISCARD_WORKTREE: 'discard-worktree',
+ /** Self-managed claim flow — it owns its own PR/review/merge/cleanup. */
+ CLAIM_FLOW: 'claim-flow',
+ /** Reads and reports; must not modify the repository at all. */
+ READ_ONLY: 'read-only',
+ /** Pushes fixes straight to an existing PR branch; opens no new PR. */
+ REVIEW_LOOP_FOLLOW_UP: 'review-loop-follow-up',
+ /** TUI host that cannot type a `/do:*` command — commit, then hand off. */
+ TUI_SLASHDO_FREE: 'tui-slashdo-free',
+ /** TUI host that drives its own `/do:pr` | `/do:push` completion workflow. */
+ TUI: 'tui',
+ /** Worktree with no PR: commit only, PortOS merges the branch back. */
+ PORTOS_MERGES: 'portos-merges',
+ /** Worktree with a PR: commit only, the system pushes and opens it. */
+ WORKTREE_NO_PUSH: 'worktree-no-push',
+ /** Plain checkout: commit and push. */
+ COMMIT_AND_PUSH: 'commit-and-push',
+});
+
+/**
+ * Ordered rules — first match wins. The ORDER is the contract this module
+ * exists to hold, so it is data rather than control flow.
+ *
+ * Derived from the light path's ladder, which is the one production `tui`/`cli`
+ * runs actually reach, with the two arms it lacked slotted in where the full
+ * path's ladders put them: `SENTINEL_PAYLOAD` ahead of `ACTION_OUTPUT` (a
+ * sandboxed review stage sets both `noCodeOutput` and a restricted profile, and
+ * its output is the sentinel payload, not an API action), and `PORTOS_MERGES`
+ * after `TUI_SLASHDO_FREE`.
+ *
+ * One deliberate deviation from the Git Hygiene ladder it replaces: `TUI` sits
+ * ahead of `PORTOS_MERGES` rather than behind it, so `PORTOS_MERGES` implies a
+ * non-TUI host. Ordering them the other way would have resolved a TUI run in a
+ * merge-back worktree to `PORTOS_MERGES` and dropped the TUI wording that tells
+ * it to run the Completion Workflow and write the sentinel — wording the
+ * completion-guideline bullet pins directly. The two orders are otherwise
+ * indistinguishable: `isTui` is always false on the full path (every `tui`/`cli`
+ * provider returns from the light path first), which is why the ladders could
+ * disagree here unnoticed. Sites that must still say "commit only" for a TUI
+ * host in a merge-back worktree key off `tuiCompletionCommand === null`, which
+ * is exactly that combination.
+ */
+const COMPLETION_MODE_RULES = Object.freeze([
+ [COMPLETION_MODES.TOOL_FREE, (f) => f.toolFreeReasoning],
+ [COMPLETION_MODES.SENTINEL_PAYLOAD, (f) => f.sentinelPayloadOutput],
+ [COMPLETION_MODES.ACTION_OUTPUT, (f) => f.noCodeOutput],
+ [COMPLETION_MODES.DISCARD_WORKTREE, (f) => f.discardWorktree],
+ [COMPLETION_MODES.CLAIM_FLOW, (f) => f.claimFlow],
+ [COMPLETION_MODES.READ_ONLY, (f) => f.isReadOnly],
+ [COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP, (f) => f.isReviewLoopFollowUp],
+ [COMPLETION_MODES.TUI_SLASHDO_FREE, (f) => f.isTui && !f.canRunSlashCommands],
+ [COMPLETION_MODES.TUI, (f) => f.isTui],
+ [COMPLETION_MODES.PORTOS_MERGES, (f) => f.portosMergesBranch],
+ [COMPLETION_MODES.WORKTREE_NO_PUSH, (f) => f.worktreeInfo && f.willOpenPR],
+]);
+
+/**
+ * Resolve a task's completion contract to a single {@link COMPLETION_MODES} key.
+ *
+ * @param {Object} flags
+ * @param {boolean} [flags.toolFreeReasoning]
+ * @param {boolean} [flags.sentinelPayloadOutput]
+ * @param {boolean} [flags.noCodeOutput]
+ * @param {boolean} [flags.discardWorktree]
+ * @param {boolean} [flags.claimFlow]
+ * @param {boolean} [flags.isReadOnly]
+ * @param {boolean} [flags.isReviewLoopFollowUp]
+ * @param {boolean} [flags.isTui]
+ * @param {boolean} [flags.canRunSlashCommands] - Defaults to `true`; only a TUI
+ * host that demonstrably cannot type `/do:*` takes the slashdo-free contract.
+ * @param {boolean} [flags.portosMergesBranch] - Defaults to
+ * `portosMergesBranchOnExit({ worktreeInfo, willOpenPR })`.
+ * @param {Object|null} [flags.worktreeInfo]
+ * @param {boolean} [flags.willOpenPR]
+ * @returns {string} one of {@link COMPLETION_MODES}
+ */
+export function resolveCompletionMode(flags = {}) {
+ const resolved = {
+ canRunSlashCommands: true,
+ portosMergesBranch: portosMergesBranchOnExit({
+ worktreeInfo: flags.worktreeInfo,
+ willOpenPR: flags.willOpenPR,
+ }),
+ ...flags,
+ };
+ const match = COMPLETION_MODE_RULES.find(([, test]) => test(resolved));
+ return match ? match[0] : COMPLETION_MODES.COMMIT_AND_PUSH;
+}
diff --git a/server/lib/agentCompletionMode.test.js b/server/lib/agentCompletionMode.test.js
new file mode 100644
index 0000000000..e2172119ce
--- /dev/null
+++ b/server/lib/agentCompletionMode.test.js
@@ -0,0 +1,99 @@
+import { describe, it, expect } from 'vitest';
+import { COMPLETION_MODES, portosMergesBranchOnExit, resolveCompletionMode } from './agentCompletionMode.js';
+
+// The rule ORDER is the whole contract this module holds — it used to live in
+// prose comments across five ladders, two of which had silently drifted out of
+// agreement (#6616). Each case below names the specific precedence a
+// reordering would break, not just "the resolver returns a string".
+describe('resolveCompletionMode', () => {
+ const wt = { worktreePath: '/wt', branchName: 'b' };
+
+ it('gives a tool-free stage its own contract even when it also looks like a no-code discard task', () => {
+ // The production shape: a public-review gate sets noCodeOutput AND
+ // discardWorktree alongside its profile. Any other arm would send a model
+ // with no tools chasing a sentinel, an API call, or a commit.
+ expect(resolveCompletionMode({
+ toolFreeReasoning: true, sentinelPayloadOutput: false, noCodeOutput: true,
+ discardWorktree: true, isTui: true, worktreeInfo: wt,
+ })).toBe(COMPLETION_MODES.TOOL_FREE);
+ });
+
+ it('sends a sandboxed review stage to the sentinel payload, not the API-action contract', () => {
+ // Stage 3 sets noCodeOutput too, but its deliverable is the JSON payload in
+ // the sentinel. Ordering ACTION_OUTPUT first told it to "deliver your result
+ // the way the task describes", which is how a run reports nothing.
+ expect(resolveCompletionMode({
+ sentinelPayloadOutput: true, noCodeOutput: true, discardWorktree: true,
+ })).toBe(COMPLETION_MODES.SENTINEL_PAYLOAD);
+ });
+
+ it('lets the deliverable\'s destination outrank the worktree\'s disposal', () => {
+ // noCodeOutput says WHERE the result goes; discardWorktree says what happens
+ // to the checkout. A task doing external work during the run must not be
+ // told the sentinel is its output channel — the cleanup throws it away.
+ expect(resolveCompletionMode({ noCodeOutput: true, discardWorktree: true }))
+ .toBe(COMPLETION_MODES.ACTION_OUTPUT);
+ });
+
+ it('keeps a TUI run in a merge-back worktree on the TUI contract', () => {
+ // The deliberate deviation from the Git Hygiene ladder's order. Resolving
+ // this to PORTOS_MERGES drops the wording that tells a TUI host to run the
+ // Completion Workflow and write the sentinel — it would just be told to
+ // commit, and PortOS would wait forever for a sentinel nobody writes.
+ expect(resolveCompletionMode({ isTui: true, worktreeInfo: wt, willOpenPR: false }))
+ .toBe(COMPLETION_MODES.TUI);
+ // …and a non-TUI host in the same worktree still gets the commit-only one.
+ expect(resolveCompletionMode({ isTui: false, worktreeInfo: wt, willOpenPR: false }))
+ .toBe(COMPLETION_MODES.PORTOS_MERGES);
+ });
+
+ it('separates a TUI host that cannot type a slash command from one that can', () => {
+ expect(resolveCompletionMode({ isTui: true, canRunSlashCommands: false, worktreeInfo: wt, willOpenPR: true }))
+ .toBe(COMPLETION_MODES.TUI_SLASHDO_FREE);
+ // Absent evidence, a host is assumed able — only a demonstrably slashdo-free
+ // one takes the manual commit + handoff contract.
+ expect(resolveCompletionMode({ isTui: true, worktreeInfo: wt, willOpenPR: true }))
+ .toBe(COMPLETION_MODES.TUI);
+ });
+
+ it('falls through the worktree postures to a plain commit and push', () => {
+ expect(resolveCompletionMode({ worktreeInfo: wt, willOpenPR: true })).toBe(COMPLETION_MODES.WORKTREE_NO_PUSH);
+ expect(resolveCompletionMode({ worktreeInfo: null, willOpenPR: false })).toBe(COMPLETION_MODES.COMMIT_AND_PUSH);
+ expect(resolveCompletionMode()).toBe(COMPLETION_MODES.COMMIT_AND_PUSH);
+ });
+
+ it('takes an explicit portosMergesBranch over the worktree/PR derivation', () => {
+ // The prompt builders pass the value they already computed; a caller that
+ // passes neither still gets the derived answer.
+ expect(resolveCompletionMode({ portosMergesBranch: true, worktreeInfo: null, willOpenPR: true }))
+ .toBe(COMPLETION_MODES.PORTOS_MERGES);
+ });
+
+ // A mode nothing can return is a rule that was never written — exactly the
+ // failure that left step 4 with no tool-free and no read-only arm.
+ it('can return every declared mode', () => {
+ const reachable = new Set([
+ resolveCompletionMode({ toolFreeReasoning: true }),
+ resolveCompletionMode({ sentinelPayloadOutput: true }),
+ resolveCompletionMode({ noCodeOutput: true }),
+ resolveCompletionMode({ discardWorktree: true }),
+ resolveCompletionMode({ claimFlow: true }),
+ resolveCompletionMode({ isReadOnly: true }),
+ resolveCompletionMode({ isReviewLoopFollowUp: true }),
+ resolveCompletionMode({ isTui: true, canRunSlashCommands: false }),
+ resolveCompletionMode({ isTui: true }),
+ resolveCompletionMode({ worktreeInfo: wt, willOpenPR: false }),
+ resolveCompletionMode({ worktreeInfo: wt, willOpenPR: true }),
+ resolveCompletionMode({}),
+ ]);
+ expect([...reachable].sort()).toEqual(Object.values(COMPLETION_MODES).sort());
+ });
+});
+
+describe('portosMergesBranchOnExit', () => {
+ it('is true only for a worktree that opens no PR', () => {
+ expect(portosMergesBranchOnExit({ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: false })).toBe(true);
+ expect(portosMergesBranchOnExit({ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true })).toBe(false);
+ expect(portosMergesBranchOnExit({ worktreeInfo: null, willOpenPR: false })).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index b3cbfb755f..afba8d7464 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -150,6 +150,7 @@ export * as childProcess from './childProcess.js';
export * from './callerModePolicy.js';
export * from './cliChildEnv.js';
export * from './agentExecutionProfiles.js';
+export * from './agentCompletionMode.js';
export * from './localEndpoint.js';
export * from './cliProviderArgs.js';
export * from './cliProviderRun.js';
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 6a18b9e0ca..222c3e2331 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -32,12 +32,14 @@ import { manualForgeCli, resolveManualForgeCli } from './promptSections/forge.js
import { buildOrchestrationDoctrineSection } from './promptSections/orchestrationDoctrine.js';
import { buildPlannerAttributionSection } from './promptSections/plannerAttribution.js';
import { isPublicReviewNoToolProfile, isPublicReviewRestrictedProfile } from '../lib/agentExecutionProfiles.js';
+import { COMPLETION_MODES, resolveCompletionMode } from '../lib/agentCompletionMode.js';
import {
DISCARD_WORKTREE_NOTE,
buildActionOutputCompletionSection,
buildClaimFlowCompletionSection,
buildCliCompletionSection,
buildCompletionGuidelineBullet,
+ buildFallbackCompletionInstructions,
buildInlineReviewLoopSection,
NO_CHANGE_AUDIT_GUIDANCE,
buildProgrammaticOutputCompletionSection,
@@ -81,6 +83,14 @@ const AGENTS_DIR = PATHS.cosAgents;
// These scheduled audits inspect a running web UI. Keep their runtime contract
// in the builder rather than only in the default prompt bodies so customized
// prompts and tasks queued before a prompt revision get the same guidance.
+// The configurable briefing template the full (`api`) path renders. Named here,
+// above this file's first template literal, because the prompt-stage call-site
+// generator indexes stage keys by scanning string tokens — and its scanner can
+// lose phase on a file with this many nested backticks, which silently dropped
+// agentPromptBuilder.js from this stage's "Referenced in" list. A key declared
+// before the first multi-line template is found regardless of that phase.
+const BRIEFING_STAGE_KEY = 'cos-agent-briefing';
+
export const UI_AUDIT_TASK_TYPES = Object.freeze([
'accessibility', 'console-errors', 'ui-bugs', 'mobile-responsive', 'ux'
]);
@@ -435,6 +445,10 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
const sentinelPayloadOutput = isPublicReviewRestrictedProfile(task.metadata?.executionProfile) && !toolFreeReasoning;
const noChangeSuccess = isTruthyMetaFn(task.metadata?.noChangeSuccess);
const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);
+ // The review-loop follow-up that addresses PR feedback and merges (spawned by
+ // the previous agent's cleanup hook). Its own procedure section renders far
+ // below; the flag is read up here because it is an input to the mode decision.
+ const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
const isWorktreeOnExistingBranch = isPrBranchWorktree(task, worktreeInfo);
const worktreeCommitNote = worktreeInfo
? worktreeCommitGuidance({
@@ -482,14 +496,10 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
const canRunSlashCommands = canTypeSlashCommands({
providerId, providerCommand, leanMode, assumeClaudeWhenUnknown: false,
});
- const simplifyInstruction = canRunSlashCommands
- ? 'run `/simplify` to review the changed code for reuse, quality, and efficiency'
- : SIMPLIFY_INLINE_REVIEW;
- // Discard tasks don't commit, so the simplify-before-commit step is moot.
- const simplifySection = simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
-## Simplify Step
-After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : portosMergesBranch ? 'commit your changes (do NOT push — PortOS merges this branch back into the source checkout after you exit; a pushed copy would only be left behind on origin)' : 'commit and push using `/do:push`'}.
-` : '';
+ const simplifySection = buildSimplifySection({
+ canRunSlashCommands, simplifyEnabled, isTui, discardWorktree, claimFlow,
+ worktreeInfo, willOpenPR, portosMergesBranch,
+ });
// Resolve the user's ordered reviewer list + flags (task metadata wins; else the
// install's configured Code Review Defaults; else `[]`). Declared up here
@@ -530,50 +540,175 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
// is a plain commit (buildCompletionGuidelineBullet renders that case).
const tuiCompletionCommand = willOpenPR ? '/do:pr' : portosMergesBranch ? null : '/do:push';
const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
- // A discard task's completion is the sentinel-only contract (no push/PR/merge),
- // and this applies to every provider type — so it wins over the isTui fork and
- // over the fallback template's commit/push instructions below.
- // Same precedence as buildCompletionGuidelineBullet: where the deliverable
- // goes (`noCodeOutput`) decides the completion contract, and only then does
- // worktree disposal (`discardWorktree`) pick the reasoning-payload contract.
- // A task doing external work during the run must not be told the sentinel is
- // its output channel.
- const tuiCompletionSection = toolFreeReasoning
- ? buildToolFreeReasoningCompletionSection()
- : sentinelPayloadOutput
- ? buildProgrammaticOutputCompletionSection(sentinelPath)
- : noCodeOutput
- ? buildActionOutputCompletionSection({ isTui, sentinelPath })
- : discardWorktree
- ? buildProgrammaticOutputCompletionSection(sentinelPath)
- : claimFlow
- ? buildClaimFlowCompletionSection({ isTui, sentinelPath, reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) })
- : isTui
- ? buildTuiCompletionSection({
- willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, portosMergesBranch,
- // Unreachable today — every `tui`/`cli` provider returns early at the
- // LIGHT_CONTEXT gate above, so `isTui` is always false on this path
- // (same situation as buildCompletionGuidelineBullet's `isTui` arm).
- // Kept provider-aware anyway so it can't be the ONE call site that
- // silently promises `/do:pr` to a host that can't type it if the
- // routing ever changes — this arm previously passed no slashdoFree at
- // all, which is how gates like this drift (#3114).
- slashdoFree: !canRunSlashCommands,
- branchName: worktreeInfo?.branchName || null,
- baseBranch: worktreeInfo?.baseBranch || null,
- sentinelPath,
- leavePrOpen: leavesPrForHuman(task),
- reviewers: taskReviewers,
- usernames: taskReviewerUsernames,
- optionalReviewers: taskOptionalReviewers,
- reviewerMaxRounds: taskReviewerMaxRounds,
- reviewerModels: taskReviewerModels,
- reviewerEfforts: taskReviewerEfforts,
- reviewStopMode: taskReviewStopMode,
- reviewerApplies: taskReviewerApplies
- })
- : '';
+ // THE completion decision, made once. Every section below renders this key;
+ // none re-derives it. See lib/agentCompletionMode.js for the rule order.
+ const completionMode = resolveCompletionMode({
+ toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,
+ isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands, portosMergesBranch,
+ worktreeInfo, willOpenPR,
+ });
+ // Step 4, the Git Hygiene bullet and the commit-target bullet as ONE record,
+ // so the three cannot contradict each other the way they did (#6616).
+ const completionInstructions = buildFallbackCompletionInstructions({
+ mode: completionMode, worktreeInfo, willOpenPR, tuiCompletionCommand,
+ });
+ // The `## Guidelines` completion bullet: same mode, rendered here so the
+ // fallback template stays pure interpolation.
+ const guidelineBullet = buildCompletionGuidelineBullet({
+ mode: completionMode, whenDone,
+ tuiCompletionCommand, slashdoFree: isTui && !canRunSlashCommands,
+ worktreeInfo, willOpenPR, prCompletion, noChangeSuccess,
+ leavePrOpen: leavesPrForHuman(task),
+ });
+ const completionBullet = guidelineBullet ? `- ${guidelineBullet}` : '';
+ // Unreachable today — every `tui`/`cli` provider returns early at the
+ // LIGHT_CONTEXT gate above, so `isTui` is always false on this path (the
+ // light path's `buildTuiCompletionSection` call is the live one). Kept
+ // provider-aware anyway so this can't become the ONE call site that silently
+ // promises `/do:pr` to a host that can't type it if the routing ever changes
+ // — this arm previously passed no slashdoFree at all, which is how gates like
+ // it drift (#3114).
+ const buildFullPathTuiCompletion = () => buildTuiCompletionSection({
+ willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, portosMergesBranch,
+ slashdoFree: !canRunSlashCommands,
+ branchName: worktreeInfo?.branchName || null,
+ baseBranch: worktreeInfo?.baseBranch || null,
+ sentinelPath,
+ leavePrOpen: leavesPrForHuman(task),
+ reviewers: taskReviewers,
+ usernames: taskReviewerUsernames,
+ optionalReviewers: taskOptionalReviewers,
+ reviewerMaxRounds: taskReviewerMaxRounds,
+ reviewerModels: taskReviewerModels,
+ reviewerEfforts: taskReviewerEfforts,
+ reviewStopMode: taskReviewStopMode,
+ reviewerApplies: taskReviewerApplies
+ });
+ // Which completion section this mode gets. A mode with no entry renders
+ // nothing HERE because the full path carries its contract elsewhere: the
+ // review-loop follow-up has its own procedure section below, read-only and
+ // the commit/push modes are covered by the Guidelines bullet and Git Hygiene.
+ const tuiCompletionSection = ({
+ [COMPLETION_MODES.TOOL_FREE]: () => buildToolFreeReasoningCompletionSection(),
+ [COMPLETION_MODES.SENTINEL_PAYLOAD]: () => buildProgrammaticOutputCompletionSection(sentinelPath),
+ [COMPLETION_MODES.ACTION_OUTPUT]: () => buildActionOutputCompletionSection({ isTui, sentinelPath }),
+ [COMPLETION_MODES.DISCARD_WORKTREE]: () => buildProgrammaticOutputCompletionSection(sentinelPath),
+ [COMPLETION_MODES.CLAIM_FLOW]: () => buildClaimFlowCompletionSection({
+ isTui, sentinelPath, reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
+ }),
+ [COMPLETION_MODES.TUI_SLASHDO_FREE]: buildFullPathTuiCompletion,
+ [COMPLETION_MODES.TUI]: buildFullPathTuiCompletion,
+ }[completionMode] || (() => ''))();
+
+ const {
+ reviewLoopSection, reviewLoopFollowUpSection, jiraSection, skillSection,
+ toolsSection, planningContextSection,
+ } = await buildFullPathOptionalSections({
+ task, workspaceDir, agentId, worktreeInfo, isTui, prCompletion, willOpenPR,
+ taskReviewers, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,
+ skipDevContext,
+ });
+
+ // Try to use the prompt template system. Skip the template path for
+ // review-loop follow-up agents because the user-side template usually
+ // predates the {{reviewLoopFollowUpSection}} placeholder; the built-in
+ // fallback is the source of truth for that section, and silently dropping
+ // it would leave the agent with no instructions and the loop would not run.
+ // Precomputed display label for the stock "Target Application" heading in the
+ // cos-agent-briefing template. Mirrors buildTaskBlock's predicate: suppress
+ // the redundant heading for the PortOS default app (empty string → the
+ // template section is falsy and renders nothing), surface the app id for
+ // managed apps. `task.metadata.app` stays in the context for any custom
+ // template references — only the stock heading gates on this.
+ const briefingApp = task.metadata?.app;
+ const targetAppLabel = briefingApp && briefingApp !== PORTOS_APP_ID ? briefingApp : '';
+ // The task's prompt payload + human note as ONE string (#4153). Templates —
+ // the shipped `cos-agent-briefing.md` AND every copy an install has since
+ // customized — reference `{{task.metadata.context}}`, so the split is folded
+ // back into that key for rendering instead of being pushed out to every
+ // template on every install. `metadata.prompt` still travels untouched for a
+ // custom template that wants to address it directly.
+ const briefingSourceTask = taskVisibleToPipelineReviewer(task);
+ const contextBlock = taskContextBlock(briefingSourceTask);
+ const uiAuditRuntimeSection = isUiAuditTask(task) ? UI_AUDIT_RUNTIME_RULE : '';
+ const briefingTask = contextBlock === (briefingSourceTask.metadata?.[TASK_CONTEXT_KEY] ?? null)
+ ? briefingSourceTask
+ : { ...briefingSourceTask, metadata: { ...briefingSourceTask.metadata, [TASK_CONTEXT_KEY]: contextBlock } };
+ const promptData = isReviewLoopFollowUp ? null : await buildPrompt(BRIEFING_STAGE_KEY, {
+ task: briefingTask,
+ targetAppLabel,
+ config,
+ memorySection,
+ agentInstructionsSection,
+ digitalTwinSection,
+ worktreeSection,
+ pipelineSection,
+ jiraSection,
+ simplifySection,
+ tuiCompletionSection,
+ reviewLoopSection,
+ reviewLoopFollowUpSection,
+ compactionSection,
+ skillSection,
+ planningContextSection,
+ toolsSection,
+ claudeMdSection: agentInstructionsSection, // Backwards compatibility for prompt templates (pre-#4852 name)
+ soulSection: digitalTwinSection, // Backwards compatibility for prompt templates
+ timestamp: new Date().toISOString()
+ }).catch(() => null);
+
+ if (promptData?.prompt) {
+ return `${promptData.prompt}${orchestrationSection ? `\n\n${orchestrationSection}` : ''}${plannerAttributionSection ? `\n\n${plannerAttributionSection}` : ''}\n\n${UNATTENDED_RUN_RULE}${uiAuditRuntimeSection ? `\n\n${uiAuditRuntimeSection}` : ''}\n\n${PM2_SAFETY_RULE}`;
+ }
+
+ return buildFallbackAgentPrompt({
+ task, workspaceDir, agentInstructionsSection, memorySection, contextBlock,
+ worktreeSection, pipelineSection, jiraSection, orchestrationSection,
+ plannerAttributionSection, simplifySection, tuiCompletionSection,
+ reviewLoopSection, reviewLoopFollowUpSection, compactionSection, skillSection,
+ toolsSection, planningContextSection, uiAuditRuntimeSection,
+ completionBullet, completionInstructions, noChangeSuccess,
+ });
+}
+
+/**
+ * The "## Simplify Step" section for the full (`api`) path — the
+ * reuse/quality/efficiency self-review the agent runs before it commits.
+ *
+ * `/simplify` is a Claude Code built-in slash command, so only a session that
+ * loaded its commands can run it; everyone else gets the inline equivalent
+ * describing the same pass. Empty for the contracts that never commit.
+ */
+function buildSimplifySection({
+ canRunSlashCommands, simplifyEnabled, isTui, discardWorktree, claimFlow,
+ worktreeInfo, willOpenPR, portosMergesBranch,
+}) {
+ const simplifyInstruction = canRunSlashCommands
+ ? 'run `/simplify` to review the changed code for reuse, quality, and efficiency'
+ : SIMPLIFY_INLINE_REVIEW;
+ // Discard tasks don't commit, so the simplify-before-commit step is moot.
+ const simplifySection = simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
+## Simplify Step
+After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : portosMergesBranch ? 'commit your changes (do NOT push — PortOS merges this branch back into the source checkout after you exit; a pushed copy would only be left behind on origin)' : 'commit and push using `/do:push`'}.
+` : '';
+ return simplifySection;
+}
+
+/**
+ * The full (`api`) path's per-task optional sections: the review-loop notice,
+ * the review-loop follow-up procedure, JIRA context, the auto-matched skill
+ * templates, the tools summary and any `.planning/` context.
+ *
+ * Each is independent of the others and of the completion contract — lifting
+ * them out of `buildAgentPrompt` keeps that function about ORDER (resolve,
+ * then render) rather than about every section's presence test.
+ */
+async function buildFullPathOptionalSections({
+ task, workspaceDir, agentId, worktreeInfo, isTui, prCompletion, willOpenPR,
+ taskReviewers, isReviewLoopFollowUp, isFollowUpNeedingRecipes, localAgentLoopBody,
+ skipDevContext,
+}) {
// Build review loop section if enabled. The agent itself does NOT open the PR
// or run /do:rpr — by the time the PR exists, the agent has already exited.
// The system requests Copilot review automatically after PR creation on GitHub
@@ -597,7 +732,6 @@ After your task completes, the system will spawn a follow-up agent that runs the
// hook (see spawnReviewLoopFollowUp in agentLifecycle.js). It needs the full /do:rpr
// procedure inlined because the agent runs in a one-shot session and won't trigger
// a slash command itself.
- const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
let reviewLoopFollowUpSection = '';
if (isReviewLoopFollowUp) {
// `/do:rpr` is the Copilot/@github comment-resolution procedure — a merge-only
@@ -663,63 +797,34 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
}
}
}
+ return {
+ reviewLoopSection, reviewLoopFollowUpSection, jiraSection, skillSection,
+ toolsSection, planningContextSection,
+ };
+}
- // Try to use the prompt template system. Skip the template path for
- // review-loop follow-up agents because the user-side template usually
- // predates the {{reviewLoopFollowUpSection}} placeholder; the built-in
- // fallback is the source of truth for that section, and silently dropping
- // it would leave the agent with no instructions and the loop would not run.
- // Precomputed display label for the stock "Target Application" heading in the
- // cos-agent-briefing template. Mirrors buildTaskBlock's predicate: suppress
- // the redundant heading for the PortOS default app (empty string → the
- // template section is falsy and renders nothing), surface the app id for
- // managed apps. `task.metadata.app` stays in the context for any custom
- // template references — only the stock heading gates on this.
- const briefingApp = task.metadata?.app;
- const targetAppLabel = briefingApp && briefingApp !== PORTOS_APP_ID ? briefingApp : '';
- // The task's prompt payload + human note as ONE string (#4153). Templates —
- // the shipped `cos-agent-briefing.md` AND every copy an install has since
- // customized — reference `{{task.metadata.context}}`, so the split is folded
- // back into that key for rendering instead of being pushed out to every
- // template on every install. `metadata.prompt` still travels untouched for a
- // custom template that wants to address it directly.
- const briefingSourceTask = taskVisibleToPipelineReviewer(task);
- const contextBlock = taskContextBlock(briefingSourceTask);
- const uiAuditRuntimeSection = isUiAuditTask(task) ? UI_AUDIT_RUNTIME_RULE : '';
- const briefingTask = contextBlock === (briefingSourceTask.metadata?.[TASK_CONTEXT_KEY] ?? null)
- ? briefingSourceTask
- : { ...briefingSourceTask, metadata: { ...briefingSourceTask.metadata, [TASK_CONTEXT_KEY]: contextBlock } };
- const promptData = isReviewLoopFollowUp ? null : await buildPrompt('cos-agent-briefing', {
- task: briefingTask,
- targetAppLabel,
- config,
- memorySection,
- agentInstructionsSection,
- digitalTwinSection,
- worktreeSection,
- pipelineSection,
- jiraSection,
- simplifySection,
- tuiCompletionSection,
- reviewLoopSection,
- reviewLoopFollowUpSection,
- compactionSection,
- skillSection,
- planningContextSection,
- toolsSection,
- claudeMdSection: agentInstructionsSection, // Backwards compatibility for prompt templates (pre-#4852 name)
- soulSection: digitalTwinSection, // Backwards compatibility for prompt templates
- timestamp: new Date().toISOString()
- }).catch(() => null);
-
- if (promptData?.prompt) {
- return `${promptData.prompt}${orchestrationSection ? `\n\n${orchestrationSection}` : ''}${plannerAttributionSection ? `\n\n${plannerAttributionSection}` : ''}\n\n${UNATTENDED_RUN_RULE}${uiAuditRuntimeSection ? `\n\n${uiAuditRuntimeSection}` : ''}\n\n${PM2_SAFETY_RULE}`;
- }
-
- const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });
-
- // Fallback to built-in template
- return `${agentInstructionsSection || ''}
+/**
+ * The built-in fallback prompt for the full (`api`) path — rendered when the
+ * configurable `cos-agent-briefing` template is unavailable or a review-loop
+ * follow-up bypasses it.
+ *
+ * Pure string assembly, deliberately separate from `buildAgentPrompt`: every
+ * optional section it interpolates is decided by the caller, so the
+ * orchestrator reads as "resolve the sections, then render" instead of
+ * carrying each section's presence ternary in its own body.
+ */
+function buildFallbackAgentPrompt({
+ task, workspaceDir, agentInstructionsSection, memorySection, contextBlock,
+ worktreeSection, pipelineSection, jiraSection, orchestrationSection,
+ plannerAttributionSection, simplifySection, tuiCompletionSection,
+ reviewLoopSection, reviewLoopFollowUpSection, compactionSection, skillSection,
+ toolsSection, planningContextSection, uiAuditRuntimeSection,
+ completionBullet, completionInstructions, noChangeSuccess,
+}) {
+const taskBlock = buildTaskBlock(task, { screenshotsAsList: false });
+
+// Fallback to built-in template
+return `${agentInstructionsSection || ''}
${memorySection || ''}
@@ -741,27 +846,7 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too
1. Analyze the task requirements carefully
2. Make necessary changes to complete the task
3. Test your changes when possible
-4. ${toolFreeReasoning
- ? 'Answer in this reply — you have no tools to commit, push, or call an API with; the Completion section above is the whole contract'
- : sentinelPayloadOutput
- ? 'Write your result to the completion sentinel in the payload format your task describes (see the Completion section above) — do NOT commit, push, or open a PR'
- : noCodeOutput
- ? 'Deliver your result the way the task describes (the API call or command it names) — do NOT commit, push, or open a PR; this task changes no code'
- : discardWorktree
- ? 'Write your result to the completion sentinel (see the Completion section above) — do NOT commit, push, or open a PR; this worktree is discarded on exit'
- : claimFlow
- ? 'Follow the claim workflow prompt above; it owns its worktree, PR/MR, review, merge or human-handoff, and cleanup. Do not stop after committing.'
- : isReadOnly
- ? 'Do NOT commit, push, or modify any files — this is a read-only task; read what you need and report your findings'
- : isReviewLoopFollowUp
- ? 'Follow the follow-up section above — push any fixes you make to the PR branch; a run that needed no fix makes no commit and that is a success, not a miss'
- : portosMergesBranch
- ? `Commit your changes (see ${isTui ? 'Completion Workflow above' : 'Git Hygiene below'}) — do NOT push, PortOS merges this branch back on exit`
- : isTui
- ? `Commit, push, and ${willOpenPR ? 'open the PR (see Completion Workflow above)' : 'push the branch (see Completion Workflow above)'}`
- : worktreeInfo && willOpenPR
- ? 'Commit your changes (see Git Hygiene below) — do NOT push, the system handles that on exit'
- : 'Commit and push your changes (see Git Hygiene below)'}
+4. ${completionInstructions.step4}
5. Provide a summary of what was done
## Guidelines
@@ -771,44 +856,15 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too
- Do not make unrelated changes
- If blocked, explain clearly why
- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only
-${(() => {
- const bullet = buildCompletionGuidelineBullet({
- isReadOnly, whenDone,
- isTui, tuiCompletionCommand, slashdoFree: isTui && !canRunSlashCommands,
- worktreeInfo, willOpenPR, prCompletion, discardWorktree, noCodeOutput: noCodeOutput && !sentinelPayloadOutput, noChangeSuccess,
- leavePrOpen: leavesPrForHuman(task),
- isPrFollowUp: isReviewLoopFollowUp, claimFlow, toolFreeReasoning,
- });
- return bullet ? `- ${bullet}` : '';
-})()}
+${completionBullet}
## Git Hygiene (CRITICAL)
- **Before starting work**, run \`git status\` to verify a clean working tree. Do NOT stash or discard uncommitted changes — other agents may be working concurrently and expecting those changes to be present. If the tree is dirty, only commit files YOU changed for this task.
- **NEVER use \`git stash\`** in any form (\`git stash push\`, \`git stash pop\`, etc.). This is a multi-agent system — stashing can silently destroy or corrupt another agent's or the user's in-progress work. Work around uncommitted changes instead. (Note: the backend may use \`--autostash\` in user-triggered pull operations — that is safe because those are single-user UI actions, not concurrent agent operations.)
- **Only commit files YOU changed** for this task. Never use \`git add -A\` or \`git add .\` — always stage specific files by name.
${noChangeSuccess ? `- **No-change audits may exit cleanly.** ${NO_CHANGE_AUDIT_GUIDANCE}` : ''}
-${toolFreeReasoning
- ? `- **No git at all.** You have no tools; the Completion section above is the whole contract.`
- : noCodeOutput && !sentinelPayloadOutput
- ? `- **Do NOT commit, push, or open a PR.** This task changes no code — its result is delivered by the API call or command described above. Without this, a no-worktree task of this shape was told to \`/do:push\` **directly to the branch it is standing on**, which for a task running in the app's live checkout is its default branch.`
- : discardWorktree
- ? `- **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).`
- : claimFlow
- ? `- **Follow the claim workflow prompt above.** It owns the claim worktree and the full PR/MR lifecycle; do not stop after committing or hand push/PR/merge/cleanup back to PortOS.`
- : isReadOnly
- ? `- **Do NOT commit, push, or modify any files.** This is a read-only task — read what you need and report your findings.`
- : isReviewLoopFollowUp
- ? `- **Push fixes straight to the PR branch you are on** (the follow-up section above is the procedure). Stage specific files, use a \`fix:\` prefix, no Co-Authored-By annotations. Do NOT open a new PR.`
- : isTui && !canRunSlashCommands
- ? `- **Commit only — do NOT push.** Stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations, then write the completion sentinel. PortOS will handle the branch after it closes the session.`
- : portosMergesBranch
- ? `- **Commit only — do NOT push.** Stage specific files (no \`git add -A\`), use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations. PortOS merges this branch back into the source checkout after you exit and deletes it, so do NOT run \`git push\` or \`/do:push\` yourself — a pushed copy would only be left behind on origin.`
- : isTui
- ? `- **Use \`${tuiCompletionCommand}\` to ${willOpenPR ? 'commit, push, and open the PR' : 'commit and push the branch'}** — see the Completion Workflow section above. Stage specific files (no \`git add -A\`), use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations.`
- : worktreeInfo && willOpenPR
- ? `- **Commit only — do NOT push.** Stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations. The system will push your branch and open the PR after you exit, so do NOT run \`git push\` or \`/do:push\` yourself.`
- : `- **Commit and push using \`/do:push\`** — this handles changelog updates, staging specific files, writing a conventional commit message, and pushing safely. If \`/do:push\` is unavailable, follow its conventions manually: stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations, and push with \`git pull --rebase && git push\`.`}
-${toolFreeReasoning || isReadOnly || discardWorktree || noCodeOutput || claimFlow ? '' : worktreeInfo ? `- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.` : `- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.`}
+${completionInstructions.gitHygiene}
+${completionInstructions.commitTarget}
## Working Directory
${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.
@@ -1022,96 +1078,65 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
const lightOrchestrationSection = buildOrchestrationDoctrineSection(task);
if (lightOrchestrationSection) contractSections.push(lightOrchestrationSection);
- // --- Worktree ----------------------------------------------------------
- if (worktreeInfo) {
- contractSections.push([
- '## Git Worktree',
- `- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}`,
- `- **Path**: \`${worktreeInfo.worktreePath}\``,
- worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,
- '',
- worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),
- 'Do NOT manually switch branches or modify the worktree configuration.',
- // Resuming a previous failed agent's branch: establish what's already done
- // before writing code (see buildResumeSection). '' when not a resume.
- buildResumeSection(task, worktreeInfo) || null
- ].filter(Boolean).join('\n'));
- }
-
- // --- Pipeline ----------------------------------------------------------
- const pipelineCtx = task.metadata?.pipeline;
- const pipelineLines = pipelineContextLines(pipelineCtx);
- if (pipelineLines.length) contractSections.push(['## Pipeline Context', ...pipelineLines].join('\n'));
-
- // --- JIRA --------------------------------------------------------------
- if (task.metadata?.jiraTicketId) {
- contractSections.push([
- '## JIRA',
- `- **Ticket**: ${task.metadata.jiraTicketId} (${task.metadata.jiraTicketUrl})`,
- task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\` — commit here; do NOT switch branches.` : null,
- `Include the ticket ID in commit messages, e.g. \`${task.metadata.jiraTicketId}: description\`.`
- ].filter(Boolean).join('\n'));
- }
+ // --- Worktree / pipeline / JIRA context --------------------------------
+ contractSections.push(...buildLightTaskContextSections({
+ task, worktreeInfo, isWorktreeOnExistingBranch, isTui, hasSlashdo, ownsPrWorkflow,
+ willOpenPR, discardWorktree, claimFlow, noChangeSuccess,
+ }));
// --- Completion / review-loop ------------------------------------------
- // Ordering matches the full path's (buildCompletionGuidelineBullet and the
- // tuiCompletionSection ternary): the deliverable's destination
- // (`noCodeOutput`) decides the contract, and only then does worktree disposal
- // (`discardWorktree`) pick the reasoning-payload one. THIS is the branch that
- // matters in production — every `tui`/`cli` provider returns from the light
- // path above and never reaches the other two, so a fix applied only there is
- // no fix at all for anything a subscription-quota job can run.
- if (toolFreeReasoning) {
- // No tools at all: the reply is the deliverable (see the full path's
- // tuiCompletionSection ternary for the same precedence).
- contractSections.push(buildToolFreeReasoningCompletionSection());
- } else if (noCodeOutput && !sentinelPayloadOutput) {
- contractSections.push(buildActionOutputCompletionSection({
- isTui,
- sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
- }));
- } else if (discardWorktree) {
+ // THIS is the branch that matters in production — every `tui`/`cli` provider
+ // returns from the light path and never reaches the full one, so a fix
+ // applied only there is no fix at all for anything a subscription-quota job
+ // can run. The precedence itself lives in `resolveCompletionMode`.
+ const completionMode = resolveCompletionMode({
+ toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,
+ isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands: canTypeSlash,
+ portosMergesBranch, worktreeInfo, willOpenPR,
+ });
+ const lightSentinelPath = () => resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
+ // Both TUI modes render the same section — `buildTuiCompletionSection` takes
+ // `slashdoFree` and adapts the workflow itself. Likewise the three commit/push
+ // modes: `buildCliCompletionSection` already reads `worktreeInfo`/`willOpenPR`.
+ const pushTuiCompletion = () => contractSections.push(buildTuiCompletionSection({
+ willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, slashdoFree: tuiSlashdoFree, ownsPrWorkflow, portosMergesBranch,
+ sentinelPath: lightSentinelPath(),
+ branchName: worktreeInfo?.branchName || null,
+ baseBranch: worktreeInfo?.baseBranch || null,
+ leavePrOpen: leavesPrForHuman(task),
+ reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies,
+ forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null
+ }));
+ const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));
+
+ ({
+ [COMPLETION_MODES.TOOL_FREE]: () => contractSections.push(buildToolFreeReasoningCompletionSection()),
+ // A sandboxed review stage sets `noCodeOutput` too, but its deliverable is
+ // the sentinel payload, not an API action.
+ [COMPLETION_MODES.SENTINEL_PAYLOAD]: () => contractSections.push(buildProgrammaticOutputCompletionSection(lightSentinelPath())),
+ [COMPLETION_MODES.ACTION_OUTPUT]: () => contractSections.push(buildActionOutputCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
// Reasoning-only task: the sentinel payload (shape set by the task-type
- // output hook) is the sole output; the worktree is discarded on exit. Wins
- // over the isTui / CLI push-and-PR completion workflows below.
- contractSections.push(buildProgrammaticOutputCompletionSection(resolveSentinelPath(worktreeInfo, workspaceDir, agentId)));
- } else if (claimFlow) {
- contractSections.push(buildClaimFlowCompletionSection({
- isTui,
- sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
- reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
- }));
- } else if (isReadOnly) {
- contractSections.push(buildReadOnlyCompletionSection({
- isTui,
- sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
- }));
- } else if (isReviewLoopFollowUp) {
- contractSections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));
- if (isTui) {
- const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);
+ // output hook) is the sole output; the worktree is discarded on exit.
+ [COMPLETION_MODES.DISCARD_WORKTREE]: () => contractSections.push(buildProgrammaticOutputCompletionSection(lightSentinelPath())),
+ [COMPLETION_MODES.CLAIM_FLOW]: () => contractSections.push(buildClaimFlowCompletionSection({
+ isTui, sentinelPath: lightSentinelPath(), reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
+ })),
+ [COMPLETION_MODES.READ_ONLY]: () => contractSections.push(buildReadOnlyCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
+ [COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => {
+ contractSections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));
+ if (!isTui) return;
const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;
const sentinelTail = branchName ? ` ## Branch\n ${branchName}` : ' ## Branch\n <branch name>';
contractSections.push([
'## Completion Handoff',
'When finished with the follow-up steps above, write the completion sentinel to signal PortOS that you are done:',
'',
- ...buildSentinelWriteSteps(1, sentinelPath, sentinelTail)
+ ...buildSentinelWriteSteps(1, lightSentinelPath(), sentinelTail)
].join('\n'));
- }
- } else if (isTui) {
- contractSections.push(buildTuiCompletionSection({
- willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, slashdoFree: tuiSlashdoFree, ownsPrWorkflow, portosMergesBranch,
- sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
- branchName: worktreeInfo?.branchName || null,
- baseBranch: worktreeInfo?.baseBranch || null,
- leavePrOpen: leavesPrForHuman(task),
- reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies,
- forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null
- }));
- } else {
- contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));
- }
+ },
+ [COMPLETION_MODES.TUI_SLASHDO_FREE]: pushTuiCompletion,
+ [COMPLETION_MODES.TUI]: pushTuiCompletion,
+ }[completionMode] || pushCliCompletion)();
// The manual workflow's step 4 points here — it must follow the completion
// section it is a step of. Gated on the SAME value that made that step emit,
@@ -1147,3 +1172,47 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
return { taskSections, contractSections };
}
+
+/**
+ * The light path's worktree / pipeline / JIRA context sections, in the order
+ * they render. Each is present only when the task carries that context, which
+ * is why they are collected here rather than tested inline in
+ * `buildLightContextSections`.
+ */
+function buildLightTaskContextSections({
+ task, worktreeInfo, isWorktreeOnExistingBranch, isTui, hasSlashdo, ownsPrWorkflow,
+ willOpenPR, discardWorktree, claimFlow, noChangeSuccess,
+}) {
+ const sections = [];
+ // --- Worktree ----------------------------------------------------------
+ if (worktreeInfo) {
+ sections.push([
+ '## Git Worktree',
+ `- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}`,
+ `- **Path**: \`${worktreeInfo.worktreePath}\``,
+ worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,
+ '',
+ worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),
+ 'Do NOT manually switch branches or modify the worktree configuration.',
+ // Resuming a previous failed agent's branch: establish what's already done
+ // before writing code (see buildResumeSection). '' when not a resume.
+ buildResumeSection(task, worktreeInfo) || null
+ ].filter(Boolean).join('\n'));
+ }
+
+ // --- Pipeline ----------------------------------------------------------
+ const pipelineCtx = task.metadata?.pipeline;
+ const pipelineLines = pipelineContextLines(pipelineCtx);
+ if (pipelineLines.length) sections.push(['## Pipeline Context', ...pipelineLines].join('\n'));
+
+ // --- JIRA --------------------------------------------------------------
+ if (task.metadata?.jiraTicketId) {
+ sections.push([
+ '## JIRA',
+ `- **Ticket**: ${task.metadata.jiraTicketId} (${task.metadata.jiraTicketUrl})`,
+ task.metadata.jiraBranch ? `- **Branch**: \`${task.metadata.jiraBranch}\` — commit here; do NOT switch branches.` : null,
+ `Include the ticket ID in commit messages, e.g. \`${task.metadata.jiraTicketId}: description\`.`
+ ].filter(Boolean).join('\n'));
+ }
+ return sections;
+}
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 45ae2fab90..0a403ae93f 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -111,6 +111,7 @@ vi.mock('./codeReview.js', () => ({
getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: ['copilot'] }),
}));
+import { resolveCompletionMode } from '../lib/agentCompletionMode.js';
import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getAgentInstructionsContext, detectSkillTemplates, loadSkillTemplates, UI_AUDIT_RUNTIME_RULE, UI_AUDIT_TASK_TYPES, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default
@@ -2707,16 +2708,16 @@ describe('unattended-run rule reaches every prompt path', () => {
describe('buildCompletionGuidelineBullet', () => {
it('read-only short-circuits regardless of other flags', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: true, isTui: true, slashdoFree: true,
- tuiCompletionCommand: '/do:pr', worktreeInfo: null, willOpenPR: true, willReviewLoop: false,
+ mode: resolveCompletionMode({ isReadOnly: true, isTui: true, worktreeInfo: null, willOpenPR: true }),
+ slashdoFree: true, tuiCompletionCommand: '/do:pr', worktreeInfo: null, willOpenPR: true,
});
expect(bullet).toMatch(/read-only task/i);
});
it('slashdo TUI bullet references the slashdo command', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, slashdoFree: false,
- tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: false,
+ mode: resolveCompletionMode({ isTui: true, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true }),
+ slashdoFree: false, tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
});
expect(bullet).toMatch(/`\/do:pr`/);
expect(bullet).not.toMatch(/plain `git`\/`gh`/);
@@ -2725,8 +2726,8 @@ describe('buildCompletionGuidelineBullet', () => {
it('slashdo-free TUI bullet points at the commit + PortOS handoff, not a /do:* command', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, slashdoFree: true,
- tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: false,
+ mode: resolveCompletionMode({ isTui: true, canRunSlashCommands: false, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true }),
+ slashdoFree: true, tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
});
expect(bullet).toMatch(/plain `git` commit \+ PortOS handoff/);
expect(bullet).toMatch(/no slashdo commands/);
@@ -2736,31 +2737,31 @@ describe('buildCompletionGuidelineBullet', () => {
it('non-TUI worktree+openPR bullet defers push/PR to the system, and read-only/null cases return null', () => {
const prBullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: false, tuiCompletionCommand: '/do:pr',
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: false,
+ mode: resolveCompletionMode({ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true }),
+ tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
});
expect(prBullet).toMatch(/the system will push your branch and open a pull request/);
// Without a review loop, a follow-up merges on green CI...
expect(prBullet).toMatch(/merges the PR once CI is green/);
// ...unless the PR is a human's to land, where the bullet must not promise a merge.
const jiraBullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: false, tuiCompletionCommand: '/do:pr',
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: false, leavePrOpen: true,
+ mode: resolveCompletionMode({ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true }),
+ tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, leavePrOpen: true,
});
expect(jiraBullet).toMatch(/left OPEN for a human/);
expect(jiraBullet).not.toMatch(/merges the PR once CI is green/);
// No worktree, not TUI, not read-only → no bullet.
const none = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: false, tuiCompletionCommand: '/do:push',
- worktreeInfo: null, willOpenPR: false, willReviewLoop: false,
+ mode: resolveCompletionMode({ worktreeInfo: null, willOpenPR: false }),
+ tuiCompletionCommand: '/do:push', worktreeInfo: null, willOpenPR: false,
});
expect(none).toBeNull();
});
it('marks a catalog audit no-op as a valid completion without weakening the change path', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: false, tuiCompletionCommand: '/do:pr',
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, noChangeSuccess: true,
+ mode: resolveCompletionMode({ worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true }),
+ tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, noChangeSuccess: true,
});
expect(bullet).toMatch(/no change is needed/i);
expect(bullet).toMatch(/leave the worktree clean/i);
@@ -2770,9 +2771,8 @@ describe('buildCompletionGuidelineBullet', () => {
it('discardWorktree short-circuits to the reasoning-only bullet (wins over TUI/openPR)', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, tuiCompletionCommand: '/do:pr',
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, willReviewLoop: true,
- discardWorktree: true,
+ mode: resolveCompletionMode({ isTui: true, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, discardWorktree: true }),
+ tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
});
expect(bullet).toMatch(/reasoning-only task/i);
expect(bullet).toMatch(/discarded on exit/);
@@ -2781,8 +2781,8 @@ describe('buildCompletionGuidelineBullet', () => {
it('claimFlow short-circuits to the claim-owned lifecycle bullet', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, tuiCompletionCommand: '/do:push',
- worktreeInfo: null, willOpenPR: false, claimFlow: true,
+ mode: resolveCompletionMode({ isTui: true, worktreeInfo: null, willOpenPR: false, claimFlow: true }),
+ tuiCompletionCommand: '/do:push', worktreeInfo: null, willOpenPR: false,
});
expect(bullet).toMatch(/self-managed claim flow/i);
expect(bullet).toMatch(/Do NOT stop after committing/);
@@ -2797,9 +2797,8 @@ describe('buildCompletionGuidelineBullet', () => {
// told "write your result to the sentinel" — that is how a run performs no
// action and reports its findings into a file that is then discarded.
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, tuiCompletionCommand: '/do:pr',
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
- discardWorktree: true, noCodeOutput: true,
+ mode: resolveCompletionMode({ isTui: true, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true, discardWorktree: true, noCodeOutput: true }),
+ tuiCompletionCommand: '/do:pr', worktreeInfo: { worktreePath: '/wt' }, willOpenPR: true,
});
expect(bullet).toMatch(/produces no code output/i);
expect(bullet).not.toMatch(/reasoning-only task/i);
@@ -4188,8 +4187,8 @@ describe('auto-merge posture (worktree, no PR) is commit-only on every path', ()
it('buildCompletionGuidelineBullet renders the commit-only TUI wording when there is no completion command', () => {
const bullet = buildCompletionGuidelineBullet({
- isReadOnly: false, isTui: true, tuiCompletionCommand: null,
- worktreeInfo: { worktreePath: '/wt' }, willOpenPR: false,
+ mode: resolveCompletionMode({ isTui: true, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: false }),
+ tuiCompletionCommand: null, worktreeInfo: { worktreePath: '/wt' }, willOpenPR: false,
});
expect(bullet).toMatch(/commit only — no push; PortOS merges your branch back after you exit/);
expect(bullet).not.toMatch(/`\/do:push`/);
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 5f47e8733b..5bad1235c6 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -6,6 +6,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normaliz
import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';
import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../../lib/slashdoInvocation.js';
import { shellQuote } from '../../lib/shellQuote.js';
+import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';
import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib/prDisposition.js';
import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';
import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';
@@ -18,19 +19,24 @@ function withNoChangeAuditGuidance(guidance, noChangeSuccess) {
: guidance;
}
+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).';
+
/**
* Build the single "## Guidelines" completion-handoff bullet for the full
- * (api) prompt path. Mirrors the helper pattern the light path already uses
- * (`worktreeCommitGuidance`, `buildTuiCompletionSection`) — same 4-branch
- * decision tree (read-only / TUI / worktree+PR / worktree-only / default) but
- * flattened into a function so reading is linear instead of a nested ternary.
+ * (api) prompt path, and the `## Instructions` step 4 / `## Git Hygiene` /
+ * commit-target trio that has to agree with it.
+ *
+ * Both take the completion mode `resolveCompletionMode` already decided — they
+ * do not re-derive it. Everything else they take is RENDERING detail (which
+ * `/do:*` command this host can type, whether a PR is a human's to land), never
+ * a second opinion about the contract.
*
* Returns the bullet body WITHOUT the leading `- ` marker (caller prepends),
- * or `null` when the branch produces no text (the legacy empty-string tail).
+ * or `null` when the mode produces no text (the legacy empty-string tail).
*
* @param {Object} opts
- * @param {boolean} opts.isReadOnly
- * @param {boolean} opts.isTui
+ * @param {string} opts.mode - a `COMPLETION_MODES` key
* @param {string|null} opts.tuiCompletionCommand - `/do:pr` or `/do:push`; `null`
* when PortOS merges the branch back itself and the workflow is commit-only
* (see `portosMergesBranchOnExit`)
@@ -44,76 +50,167 @@ function withNoChangeAuditGuidance(guidance, noChangeSuccess) {
* @returns {string|null}
*/
export function buildCompletionGuidelineBullet({
- isReadOnly, isTui, tuiCompletionCommand, slashdoFree = false,
- worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, discardWorktree = false, noCodeOutput = false,
- leavePrOpen = false, isPrFollowUp = false, claimFlow = false, noChangeSuccess = false, whenDone = null,
- toolFreeReasoning = false,
+ mode, tuiCompletionCommand, slashdoFree = false,
+ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN,
+ leavePrOpen = false, noChangeSuccess = false, whenDone = null,
}) {
- // Checked before every other contract: a tool-free stage cannot write a
- // sentinel, call an API, or run a command, so any of the bullets below would
- // send it chasing an output channel it does not have.
- if (toolFreeReasoning) return TOOL_FREE_REASONING_BULLET;
- // A PR follow-up (review-loop or merge-only) already carries its own PRIMARY
- // OBJECTIVE section with the full procedure, and its cleanup runs with
- // `skipMerge`. The generic "your branch is merged back automatically" bullet
- // would contradict both — and a merge-only run legitimately makes no commit.
- if (isPrFollowUp && !discardWorktree && !noCodeOutput && !isReadOnly) {
- return 'Follow the follow-up section above — it is the whole task. Commit and push only fixes you actually make; the deliverable is the PR\'s final state, not a commit. Do NOT open a new PR, and do NOT expect this branch to be merged back for you.';
- }
- // `noCodeOutput` is checked FIRST because the two flags answer different
- // questions: `discardWorktree` decides what happens to the checkout, while
- // `noCodeOutput` decides where the deliverable goes. A task that sets both —
- // "do your work through an API/CLI action during the run, and never land
- // code" — must be told its output channel is that action, NOT the sentinel.
- // Telling it "write your result to the sentinel" is how a run files nothing
- // and reports its findings into a file that gets thrown away (PLAN.md records
- // this exact hazard from the 2026-07-16 codex review). No pre-existing task
- // sets both, so this ordering changes nothing that shipped before it.
- if (noCodeOutput) {
- return '**This task produces no code output.** Its result is the API request or command your instructions describe (a PortOS endpoint call, a filed tracker issue, …) — do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a PR. Write the completion sentinel (see the Completion section) and stop.';
- }
- if (discardWorktree) {
- return '**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.';
- }
- if (claimFlow) {
- return '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.';
- }
- if (isReadOnly) {
- return '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.';
- }
- if (isTui) {
- // NOTE: in production this branch is only reachable from the full/api prompt
- // path, where `isTui` is currently always false (TUI providers route through
- // buildLightContextPrompt, which emits the live TUI completion via
- // buildTuiCompletionSection — not this bullet). It's kept provider-aware and
- // directly unit-tested so the guideline stays correct if that routing changes.
+ // NOTE: the TUI arms are only reachable from the full/api prompt path, where
+ // `isTui` is currently always false (TUI providers route through
+ // buildLightContextPrompt, which emits the live TUI completion via
+ // buildTuiCompletionSection — not this bullet). They're kept host-aware and
+ // directly unit-tested so the guideline stays correct if that routing changes.
+ const tuiBullet = () => {
const howTo = slashdoFree
? 'the Completion Workflow above (plain `git` commit + PortOS handoff — this provider has no slashdo commands)'
: tuiCompletionCommand
? `the Completion Workflow above (\`${tuiCompletionCommand}\`)`
: 'the Completion Workflow above (commit only — no push; PortOS merges your branch back after you exit)';
return withNoChangeAuditGuidance(`On successful completion, YOU run ${howTo}, then write the sentinel and stop — PortOS closes the session once it sees the sentinel; do NOT run \`/quit\`.`, noChangeSuccess);
- }
- if (worktreeInfo && willOpenPR) {
- const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
- const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
- const reviewSuffix = policyLeavesOpen
- ? ' This task is configured to leave the PR OPEN for you to inspect — no follow-up agent will review or merge it automatically.'
- : leavePrOpen
- ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (runsReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')
- : runsReviewLoop
- ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'
- : ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';
- return withNoChangeAuditGuidance(`On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`, noChangeSuccess);
- }
- if (portosMergesBranchOnExit({ worktreeInfo, willOpenPR })) {
- return withNoChangeAuditGuidance('Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.', noChangeSuccess);
- }
+ };
+
+ const bullets = {
+ [COMPLETION_MODES.TOOL_FREE]: () => TOOL_FREE_REASONING_BULLET,
+ [COMPLETION_MODES.SENTINEL_PAYLOAD]: () => REASONING_ONLY_BULLET,
+ [COMPLETION_MODES.ACTION_OUTPUT]: () => '**This task produces no code output.** Its result is the API request or command your instructions describe (a PortOS endpoint call, a filed tracker issue, …) — do NOT run `/do:push`, `/do:pr`, `/simplify`, `git commit`, `git push`, or open a PR. Write the completion sentinel (see the Completion section) and stop.',
+ [COMPLETION_MODES.DISCARD_WORKTREE]: () => REASONING_ONLY_BULLET,
+ [COMPLETION_MODES.CLAIM_FLOW]: () => '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.',
+ [COMPLETION_MODES.READ_ONLY]: () => '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.',
+ // A PR follow-up already carries its own PRIMARY OBJECTIVE section with the
+ // full procedure, and its cleanup runs with `skipMerge`. The generic "your
+ // branch is merged back automatically" bullet would contradict both — and a
+ // merge-only run legitimately makes no commit.
+ [COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => 'Follow the follow-up section above — it is the whole task. Commit and push only fixes you actually make; the deliverable is the PR\'s final state, not a commit. Do NOT open a new PR, and do NOT expect this branch to be merged back for you.',
+ [COMPLETION_MODES.TUI_SLASHDO_FREE]: tuiBullet,
+ [COMPLETION_MODES.TUI]: tuiBullet,
+ [COMPLETION_MODES.PORTOS_MERGES]: () => withNoChangeAuditGuidance('Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.', noChangeSuccess),
+ [COMPLETION_MODES.WORKTREE_NO_PUSH]: () => {
+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
+ const reviewSuffix = policyLeavesOpen
+ ? ' This task is configured to leave the PR OPEN for you to inspect — no follow-up agent will review or merge it automatically.'
+ : leavePrOpen
+ ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (runsReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')
+ : runsReviewLoop
+ ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'
+ : ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';
+ return withNoChangeAuditGuidance(`On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`, noChangeSuccess);
+ },
+ };
+
+ const render = bullets[mode];
+ if (render) return render();
return whenDone === null ? null : whenDone === 'commit-push'
? 'Commit and push your changes to the default branch (see Git Hygiene below).'
: 'Leave your code changes uncommitted in the default branch; do not commit or push.';
}
+
+// The modes whose contract forbids a commit outright, so the trailing
+// commit-target bullet ("your PR should contain only…" / "commit directly to
+// the current branch") has nothing to say. Without the tool-free and read-only
+// entries a no-worktree run of either shape was pointed at the checkout's own
+// default branch (#6616).
+const NO_COMMIT_TARGET_MODES = new Set([
+ COMPLETION_MODES.TOOL_FREE,
+ COMPLETION_MODES.SENTINEL_PAYLOAD,
+ COMPLETION_MODES.ACTION_OUTPUT,
+ COMPLETION_MODES.DISCARD_WORKTREE,
+ COMPLETION_MODES.CLAIM_FLOW,
+ COMPLETION_MODES.READ_ONLY,
+]);
+
+/**
+ * The full (api) fallback template's three completion instructions, as ONE
+ * per-mode record.
+ *
+ * `## Instructions` step 4, the `## Git Hygiene` bullet and the commit-target
+ * bullet used to be three independent ternary ladders over the same flags. They
+ * drifted: step 4 tested neither `toolFreeReasoning` nor `readOnly`, so both
+ * shapes rendered a prompt that told the agent to commit and, four lines later,
+ * that it had no git at all (#6616). Returning them together is what makes that
+ * unrepresentable — a new mode either fills all three fields or fills none.
+ *
+ * @param {Object} opts
+ * @param {string} opts.mode - a `COMPLETION_MODES` key
+ * @param {Object|null} [opts.worktreeInfo]
+ * @param {boolean} [opts.willOpenPR]
+ * @param {string|null} [opts.tuiCompletionCommand]
+ * @returns {{ step4: string, gitHygiene: string, commitTarget: string }}
+ */
+export function buildFallbackCompletionInstructions({
+ mode, worktreeInfo = null, willOpenPR = false, tuiCompletionCommand = null,
+}) {
+ const portosMergesStep4 = (where) => `Commit your changes (see ${where}) — do NOT push, PortOS merges this branch back on exit`;
+ const portosMergesHygiene = '- **Commit only — do NOT push.** Stage specific files (no `git add -A`), use `feat:`/`fix:`/`breaking:` prefix in the commit message, no Co-Authored-By annotations. PortOS merges this branch back into the source checkout after you exit and deletes it, so do NOT run `git push` or `/do:push` yourself — a pushed copy would only be left behind on origin.';
+ // A TUI host with no `/do:*` command to name is exactly the merge-back
+ // posture (`tuiCompletionCommand` is null only when PortOS lands the branch),
+ // so it gets the commit-only contract rather than "Use `null` to …".
+ const tuiEntry = () => (tuiCompletionCommand
+ ? {
+ step4: `Commit, push, and ${willOpenPR ? 'open the PR (see Completion Workflow above)' : 'push the branch (see Completion Workflow above)'}`,
+ gitHygiene: `- **Use \`${tuiCompletionCommand}\` to ${willOpenPR ? 'commit, push, and open the PR' : 'commit and push the branch'}** — see the Completion Workflow section above. Stage specific files (no \`git add -A\`), use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations.`,
+ }
+ : { step4: portosMergesStep4('Completion Workflow above'), gitHygiene: portosMergesHygiene });
+
+ const entries = {
+ [COMPLETION_MODES.TOOL_FREE]: () => ({
+ step4: 'Answer in this reply — you have no tools to commit, push, or call an API with; the Completion section above is the whole contract',
+ gitHygiene: '- **No git at all.** You have no tools; the Completion section above is the whole contract.',
+ }),
+ [COMPLETION_MODES.SENTINEL_PAYLOAD]: () => ({
+ step4: 'Write your result to the completion sentinel in the payload format your task describes (see the Completion section above) — do NOT commit, push, or open a PR',
+ gitHygiene: DISCARD_WORKTREE_HYGIENE,
+ }),
+ [COMPLETION_MODES.ACTION_OUTPUT]: () => ({
+ step4: 'Deliver your result the way the task describes (the API call or command it names) — do NOT commit, push, or open a PR; this task changes no code',
+ gitHygiene: '- **Do NOT commit, push, or open a PR.** This task changes no code — its result is delivered by the API call or command described above. Without this, a no-worktree task of this shape was told to `/do:push` **directly to the branch it is standing on**, which for a task running in the app\'s live checkout is its default branch.',
+ }),
+ [COMPLETION_MODES.DISCARD_WORKTREE]: () => ({
+ step4: 'Write your result to the completion sentinel (see the Completion section above) — do NOT commit, push, or open a PR; this worktree is discarded on exit',
+ gitHygiene: DISCARD_WORKTREE_HYGIENE,
+ }),
+ [COMPLETION_MODES.CLAIM_FLOW]: () => ({
+ step4: 'Follow the claim workflow prompt above; it owns its worktree, PR/MR, review, merge or human-handoff, and cleanup. Do not stop after committing.',
+ gitHygiene: '- **Follow the claim workflow prompt above.** It owns the claim worktree and the full PR/MR lifecycle; do not stop after committing or hand push/PR/merge/cleanup back to PortOS.',
+ }),
+ [COMPLETION_MODES.READ_ONLY]: () => ({
+ step4: 'Do NOT commit, push, or modify any files — this is a read-only task; read what you need and report your findings',
+ gitHygiene: '- **Do NOT commit, push, or modify any files.** This is a read-only task — read what you need and report your findings.',
+ }),
+ [COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => ({
+ step4: 'Follow the follow-up section above — push any fixes you make to the PR branch; a run that needed no fix makes no commit and that is a success, not a miss',
+ gitHygiene: '- **Push fixes straight to the PR branch you are on** (the follow-up section above is the procedure). Stage specific files, use a `fix:` prefix, no Co-Authored-By annotations. Do NOT open a new PR.',
+ }),
+ [COMPLETION_MODES.TUI_SLASHDO_FREE]: () => ({
+ step4: 'Commit your changes (see Completion Workflow above) — do NOT push; PortOS handles the branch after it closes the session',
+ gitHygiene: '- **Commit only — do NOT push.** Stage specific files, use `feat:`/`fix:`/`breaking:` prefix in the commit message, no Co-Authored-By annotations, then write the completion sentinel. PortOS will handle the branch after it closes the session.',
+ }),
+ [COMPLETION_MODES.TUI]: tuiEntry,
+ [COMPLETION_MODES.PORTOS_MERGES]: () => ({
+ step4: portosMergesStep4('Git Hygiene below'),
+ gitHygiene: portosMergesHygiene,
+ }),
+ [COMPLETION_MODES.WORKTREE_NO_PUSH]: () => ({
+ step4: 'Commit your changes (see Git Hygiene below) — do NOT push, the system handles that on exit',
+ gitHygiene: '- **Commit only — do NOT push.** Stage specific files, use `feat:`/`fix:`/`breaking:` prefix in the commit message, no Co-Authored-By annotations. The system will push your branch and open the PR after you exit, so do NOT run `git push` or `/do:push` yourself.',
+ }),
+ };
+
+ const entry = (entries[mode] || (() => ({
+ step4: 'Commit and push your changes (see Git Hygiene below)',
+ gitHygiene: '- **Commit and push using `/do:push`** — this handles changelog updates, staging specific files, writing a conventional commit message, and pushing safely. If `/do:push` is unavailable, follow its conventions manually: stage specific files, use `feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations, and push with `git pull --rebase && git push`.',
+ })))();
+
+ const commitTarget = NO_COMMIT_TARGET_MODES.has(mode)
+ ? ''
+ : worktreeInfo
+ ? '- **Your PR should contain only your task\'s commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents\' work.'
+ : '- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.';
+
+ return { ...entry, commitTarget };
+}
+
+
// One-line worktree note for a discard (reasoning-only) task, replacing the
// "commit / push / auto-merge" guidance the normal worktree section emits. The
// worktree exists only so the reasoner can make scratch edits without touching
@@ -325,33 +422,10 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
return lines.join('\n');
}
-/**
- * Does PortOS land this run's branch ITSELF? True under the worktree-without-PR
- * posture (`useWorktree: true`, `openPR: false`): once the agent exits,
- * `agentWorktreeCleanup.js` merges the worktree branch into the source checkout
- * and deletes it (`removeWorktree` with `merge: true`). Nothing on that path
- * reads a remote copy of the branch, so a push has no consumer — and because
- * the local branch is deleted the moment the merge lands, a pushed copy becomes
- * an orphan that the post-completion audit (`agentRepoStateVerification.js`)
- * reports as "remote branch was never deleted" and hands to a recovery agent.
- * The `/do:push` completion step this posture used to get produced exactly
- * that, run after run (every module-hygiene audit on 2026-09-06/07, and user
- * tasks with the same posture before them — each followed by a recovery agent
- * that then pushed the merged commit straight to the default branch). So under
- * this posture the contract is commit-only, on every path that can type slashdo.
- *
- * The other worktree contracts (discard, claim flow, PR follow-up, no-code) are
- * decided BEFORE this question is asked — callers apply their precedence first,
- * the way `buildCompletionGuidelineBullet` does.
- *
- * @param {object} params
- * @param {object|null} params.worktreeInfo
- * @param {boolean} params.willOpenPR
- * @returns {boolean}
- */
-export function portosMergesBranchOnExit({ worktreeInfo, willOpenPR }) {
- return Boolean(worktreeInfo) && !willOpenPR;
-}
+// `portosMergesBranchOnExit` moved to `lib/agentCompletionMode.js` (it is an
+// input to the one completion-mode decision); re-exported here so the prompt
+// sections that already import it from this module keep working.
+export { portosMergesBranchOnExit } from '../../lib/agentCompletionMode.js';
// The one commit-hygiene sentence every manual commit step composes — the
// slashdo-free TUI workflow, the PR-owning CLI workflow and the auto-merge