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

fix([issue-13264]): allow scoped external repository delivery

[._.]/ Adam Eivy48a566e6d05f
diff --git a/server/lib/agentCompletionMode.js b/server/lib/agentCompletionMode.js
index 72d0780e9d..5bf235c6fe 100644
--- a/server/lib/agentCompletionMode.js
+++ b/server/lib/agentCompletionMode.js
@@ -57,6 +57,8 @@ export const COMPLETION_MODES = Object.freeze({
SENTINEL_PAYLOAD: 'sentinel-payload',
/** Deliverable is an API call or command performed during the run. */
ACTION_OUTPUT: 'action-output',
+ /** Task owns scoped code delivery in an external scratch repository. */
+ EXTERNAL_REPOSITORY: 'external-repository',
/** 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. */
@@ -111,6 +113,7 @@ export const COMPLETION_MODES = Object.freeze({
const COMPLETION_MODE_RULES = Object.freeze([
[COMPLETION_MODES.TOOL_FREE, (f) => f.toolFreeReasoning],
[COMPLETION_MODES.SENTINEL_PAYLOAD, (f) => f.sentinelPayloadOutput],
+ [COMPLETION_MODES.EXTERNAL_REPOSITORY, (f) => f.externalRepositoryOutput && !f.isReadOnly && !f.discardWorktree],
[COMPLETION_MODES.ACTION_OUTPUT, (f) => f.noCodeOutput],
[COMPLETION_MODES.DISCARD_WORKTREE, (f) => f.discardWorktree],
[COMPLETION_MODES.CLAIM_FLOW, (f) => f.claimFlow],
@@ -132,6 +135,7 @@ const COMPLETION_MODE_RULES = Object.freeze([
* @param {Object} flags
* @param {boolean} [flags.toolFreeReasoning]
* @param {boolean} [flags.sentinelPayloadOutput]
+ * @param {boolean} [flags.externalRepositoryOutput]
* @param {boolean} [flags.noCodeOutput]
* @param {boolean} [flags.discardWorktree]
* @param {boolean} [flags.claimFlow]
diff --git a/server/lib/agentCompletionMode.test.js b/server/lib/agentCompletionMode.test.js
index 3366dd3b1e..49be66198c 100644
--- a/server/lib/agentCompletionMode.test.js
+++ b/server/lib/agentCompletionMode.test.js
@@ -76,6 +76,7 @@ describe('resolveCompletionMode', () => {
resolveCompletionMode({ toolFreeReasoning: true }),
resolveCompletionMode({ sentinelPayloadOutput: true }),
resolveCompletionMode({ noCodeOutput: true }),
+ resolveCompletionMode({ externalRepositoryOutput: true }),
resolveCompletionMode({ discardWorktree: true }),
resolveCompletionMode({ claimFlow: true }),
resolveCompletionMode({ isReadOnly: true }),
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index f12e6b4ae7..629a6fc9d1 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -11,9 +11,9 @@ import { join } from 'path';
import { stat } from 'fs/promises';
import { getMemorySection } from './memoryRetriever.js';
import { getToolsSummaryForPrompt } from './tools.js';
-import { isTruthyMeta } from '../lib/metadataFlags.js';
+import { isTruthyMeta, isFalsyMeta } from '../lib/metadataFlags.js';
import { permitsNoChangeCompletion } from '../lib/noChangeCompletion.js';
-import { PATHS, tryReadFile } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';
import { DEFAULT_REVIEWER, isToolFreeReviewer, isCliReviewer, hasRequiredReviewer, resolveReviewerConfig, resolveReviewPolicy } from '../lib/validation.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
@@ -42,6 +42,7 @@ import { COMPLETION_MODES, resolveCompletionMode } from '../lib/agentCompletionM
import {
DISCARD_WORKTREE_NOTE,
buildActionOutputCompletionSection,
+ buildExternalRepositoryCompletionSection,
buildAuditOutputCompletionSection,
buildClaimFlowCompletionSection,
buildMergeAdmissionSection,
@@ -498,7 +499,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// CD tasks are recognized without a metadata migration.
const {
willOpenPR, claimFlow, portosMergesBranch, prCompletion, simplifyEnabled, isReadOnly,
- discardWorktree, noCodeOutput, toolFreeReasoning, sentinelPayloadOutput, noChangeSuccess,
+ discardWorktree, noCodeOutput, externalRepositoryOutput, toolFreeReasoning, sentinelPayloadOutput, noChangeSuccess,
isReviewLoopFollowUp, isWorktreeOnExistingBranch,
} = resolveTaskMetadataFlags(task, worktreeInfo);
const whenDone = task.metadata?.whenDone === 'commit-push' ? 'commit-push' : 'leave-uncommitted';
@@ -558,7 +559,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// none re-derives it. See lib/agentCompletionMode.js for the rule order.
const completionMode = resolveCompletionMode({
taskHookType: resolveTaskHookType(task),
- toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,
+ toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, externalRepositoryOutput, discardWorktree, claimFlow,
isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands, portosMergesBranch,
worktreeInfo, willOpenPR, slashdoCommand: task.metadata?.slashdoCommand,
});
@@ -612,6 +613,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
[COMPLETION_MODES.TOOL_FREE]: () => buildToolFreeReasoningCompletionSection(),
[COMPLETION_MODES.SENTINEL_PAYLOAD]: () => buildProgrammaticOutputCompletionSection(sentinelPath),
[COMPLETION_MODES.ACTION_OUTPUT]: () => buildActionOutputCompletionSection({ isTui, sentinelPath }),
+ [COMPLETION_MODES.EXTERNAL_REPOSITORY]: () => buildExternalRepositoryCompletionSection({ isTui, sentinelPath }),
[COMPLETION_MODES.DISCARD_WORKTREE]: () => buildProgrammaticOutputCompletionSection(sentinelPath),
[COMPLETION_MODES.CLAIM_FLOW]: () => buildClaimFlowCompletionSection({
isTui, sentinelPath, reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
@@ -661,6 +663,22 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
}));
}
+// Older queued inbox tasks carry noCodeOutput and JSON-string provenance from
+// TASKS.md. Recognize only their known external-code lanes, never prompt text.
+function hasExternalRepositoryOutput(meta, worktreeInfo) {
+ if (worktreeInfo || !isFalsyMeta(meta?.useWorktree) || !isFalsyMeta(meta?.openPR)) return false;
+ if (meta?.externalRepositoryOutput != null) return isTruthyMeta(meta.externalRepositoryOutput);
+ const record = value => typeof value === 'string' ? safeJSONParse(value, null) : value;
+ const security = record(meta?.githubSecurityFix);
+ if (security?.host && (security.repo || security.advisories?.length)) return true;
+ const notification = record(meta?.githubNotificationResolve);
+ return !!(notification?.host && notification.repo && (
+ notification.reason === 'ci_activity' || notification.subjectType === 'CheckSuite'
+ || notification.subjectType === 'Issue'
+ || (notification.subjectType === 'PullRequest' && notification.reason !== 'review_requested')
+ ));
+}
+
/**
* The task-metadata flags both prompt paths (`buildAgentPrompt`'s API path and
* `buildLightContextSections`) derive before resolving the completion mode.
@@ -688,6 +706,7 @@ function resolveTaskMetadataFlags(task, worktreeInfo) {
isReadOnly: isTruthyMeta(meta?.readOnly),
discardWorktree: isTruthyMeta(meta?.discardWorktree),
noCodeOutput: isTruthyMeta(meta?.noCodeOutput) || !!meta?.creativeDirector,
+ externalRepositoryOutput: hasExternalRepositoryOutput(meta, worktreeInfo),
toolFreeReasoning,
sentinelPayloadOutput: isPublicReviewRestrictedProfile(meta?.executionProfile) && !toolFreeReasoning,
noChangeSuccess: permitsNoChangeCompletion(task),
@@ -747,7 +766,7 @@ function buildSimplifySection({
? '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 = ![COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(mode) && simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
+ const simplifySection = ![COMPLETION_MODES.ACTION_OUTPUT, COMPLETION_MODES.EXTERNAL_REPOSITORY, COMPLETION_MODES.RELEASE_FLOW, COMPLETION_MODES.AUDIT_FLOW, COMPLETION_MODES.RECONCILE_FLOW, COMPLETION_MODES.CHECKOUT_RECOVERY].includes(mode) && 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`'}.
` : '';
@@ -992,7 +1011,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
task = reconcileSplitContext(task);
const {
willOpenPR, claimFlow, portosMergesBranch, prCompletion, simplifyEnabled, isReadOnly,
- discardWorktree, noCodeOutput, toolFreeReasoning, sentinelPayloadOutput, noChangeSuccess,
+ discardWorktree, noCodeOutput, externalRepositoryOutput, toolFreeReasoning, sentinelPayloadOutput, noChangeSuccess,
isReviewLoopFollowUp, isWorktreeOnExistingBranch,
} = resolveTaskMetadataFlags(task, worktreeInfo);
// Ordered reviewer list + flags for the Review Loop (task metadata wins; else
@@ -1022,7 +1041,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
// subscription-quota job can run.
const completionMode = resolveCompletionMode({
taskHookType: resolveTaskHookType(task),
- toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, discardWorktree, claimFlow,
+ toolFreeReasoning, sentinelPayloadOutput, noCodeOutput, externalRepositoryOutput, discardWorktree, claimFlow,
isReadOnly, isReviewLoopFollowUp, isTui, canRunSlashCommands: canTypeSlash,
portosMergesBranch, worktreeInfo, willOpenPR, slashdoCommand: task.metadata?.slashdoCommand,
});
@@ -1164,6 +1183,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
// 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() })),
+ [COMPLETION_MODES.EXTERNAL_REPOSITORY]: () => contractSections.push(buildExternalRepositoryCompletionSection({ 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.
[COMPLETION_MODES.DISCARD_WORKTREE]: () => contractSections.push(buildProgrammaticOutputCompletionSection(lightSentinelPath())),
diff --git a/server/services/githubExternalRepositoryPrompt.test.js b/server/services/githubExternalRepositoryPrompt.test.js
new file mode 100644
index 0000000000..f3a738478b
--- /dev/null
+++ b/server/services/githubExternalRepositoryPrompt.test.js
@@ -0,0 +1,121 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('os', async (importOriginal) => ({ ...await importOriginal(), homedir: () => '/nonexistent-test-home' }));
+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn() }));
+vi.mock('./memoryRetriever.js', () => ({ getMemorySection: vi.fn().mockResolvedValue(null) }));
+vi.mock('./digital-twin.js', () => ({ getDigitalTwinForPrompt: vi.fn().mockResolvedValue(null) }));
+vi.mock('./tools.js', () => ({ getToolsSummaryForPrompt: vi.fn().mockResolvedValue('') }));
+vi.mock('./codeReview.js', () => ({ getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: [] }) }));
+
+import { addTask } from './cosTaskStore.js';
+import { buildQueuedTask } from './cosTaskIntake.js';
+import { queueSecurityFixTask } from './githubSecurityFixTask.js';
+import { queueNotificationResolveTask } from './githubNotificationResolveTask.js';
+import { buildAgentPrompt, buildLightContextPrompt } from './agentPromptBuilder.js';
+
+const account = { id: 'example-account', host: 'github.com', login: 'example-owner' };
+const repo = 'example-owner/example-tool';
+const row = {
+ thread_id: '4242', repo_full_name: repo, subject_type: 'PullRequest', reason: 'author', trust: 'yours',
+ subject_api_url: `https://api.github.com/repos/${repo}/pulls/7`,
+};
+
+// Keep the real producer -> intake -> prompt boundary; only persistence and
+// optional personal context are doubled. No GitHub or provider requests run.
+async function queued(producer) {
+ await producer();
+ const [input, type] = vi.mocked(addTask).mock.lastCall;
+ return buildQueuedTask(input, type);
+}
+
+const compose = {
+ light: task => buildLightContextPrompt(task, '/example-portos', null, { providerId: 'codex', agentId: 'example-agent' }),
+ full: task => buildAgentPrompt(task, {}, '/example-portos', null, { providerType: 'api', agentId: 'example-agent' }),
+};
+
+function assertExternalContract(prompt) {
+ expect(prompt).toContain('## Completion (External Repository)');
+ expect(prompt).toContain('You may edit code, commit, push and open a PR there only as the task directs');
+ expect(prompt).toContain('Never edit, commit, push or open a PR from the PortOS checkout');
+ expect(prompt).toContain('PortOS will not publish or merge this work for you');
+ expect(prompt).not.toContain('## Completion (No Code Output)');
+ expect(prompt).not.toContain('do NOT run `/do:push`');
+ expect(prompt).not.toContain('commit directly to the current branch');
+ expect(prompt).not.toContain('## Simplify Step');
+}
+
+beforeEach(() => vi.mocked(addTask).mockReset().mockResolvedValue({ id: 'task-example' }));
+
+for (const [path, render] of Object.entries(compose)) {
+ describe(`${path} external repository completion`, () => {
+ it.each([
+ ['repository security alerts', () => queueSecurityFixTask({ account, repo })],
+ ['global advisory security alerts', () => queueSecurityFixTask({ account, advisories: ['GHSA-8r9p-f939-6h3c'] })],
+ ['enterprise global advisories', () => queueSecurityFixTask({ account: { ...account, host: 'ghe.example.com' }, advisories: ['GHSA-8r9p-f939-6h3c'] })],
+ ])('keeps %s deliverable in the external clone, including a verified no-op', async (_name, producer) => {
+ const task = await queued(producer);
+ expect(task.metadata).toMatchObject({ useWorktree: false, openPR: false, worktreeChangesExpected: false, externalRepositoryOutput: true });
+ expect(task.metadata.noCodeOutput).toBeUndefined();
+ const prompt = await render(task);
+ assertExternalContract(prompt);
+ expect(prompt).toContain('Otherwise update each vulnerable dependency');
+ expect(prompt).toContain('verified no-action result (such as zero open alerts) needs no commit or PR');
+ expect(prompt).toContain('absence of an existing bot PR does not block creating an authorized fix PR');
+ expect(prompt).toContain('When they pass, squash-merge');
+ if (task.metadata.githubSecurityFix.host !== 'github.com') expect(prompt).toContain('gh repo clone ghe.example.com/<repo>');
+ if (path === 'light') expect(prompt).toContain('.agent-done-example-agent');
+ });
+
+ it.each([
+ ['own PR', row],
+ ['CI', { ...row, reason: 'ci_activity', subject_type: 'CheckSuite', subject_api_url: null }],
+ ['issue', { ...row, subject_type: 'Issue', subject_api_url: `https://api.github.com/repos/${repo}/issues/7` }],
+ ])('preserves the notification %s code workflow and its no-merge restriction', async (_name, notification) => {
+ const task = await queued(() => queueNotificationResolveTask({ account, row: notification }));
+ const prompt = await render(task);
+ assertExternalContract(prompt);
+ expect(prompt).toContain('never merge a pull request');
+ expect(prompt).toContain('Push only to branches you create in this run');
+ });
+
+ it.each([
+ ['read-only', { readOnly: 'true' }],
+ ['discard', { discardWorktree: 'true' }],
+ ['sandboxed actions', { executionProfile: 'public-review-actions' }],
+ ['tool-free review', { executionProfile: 'public-review-gate' }],
+ ])('does not let an external marker bypass %s restrictions', async (_name, restrictions) => {
+ const task = await queued(() => queueSecurityFixTask({ account, repo }));
+ Object.assign(task.metadata, restrictions);
+ expect(await render(task)).not.toContain('## Completion (External Repository)');
+ });
+
+ it.each([
+ ['review', { ...row, reason: 'review_requested', trust: 'trusted' }],
+ ['release', { ...row, subject_type: 'Release', reason: 'subscribed' }],
+ ])('retains no-code restrictions for a notification %s', async (_name, notification) => {
+ const prompt = await render(await queued(() => queueNotificationResolveTask({ account, row: notification })));
+ expect(prompt).toContain('## Completion (No Code Output)');
+ expect(prompt).toContain('`git commit`, `git push`, or open a pull request');
+ expect(prompt).not.toContain('## Completion (External Repository)');
+ });
+
+ it.each([
+ ['security', () => queueSecurityFixTask({ account, repo })],
+ ['notification', () => queueNotificationResolveTask({ account, row })],
+ ])('recognizes queued legacy %s flags and JSON-string provenance without broadening API-only work', async (_name, producer) => {
+ const task = await queued(producer);
+ delete task.metadata.externalRepositoryOutput;
+ task.metadata.noCodeOutput = true;
+ task.metadata.simplify = true;
+ task.metadata = Object.fromEntries(Object.entries(task.metadata).map(([key, value]) => [key, typeof value === 'string' ? value : JSON.stringify(value)]));
+ assertExternalContract(await render(task));
+ delete task.metadata.githubSecurityFix;
+ delete task.metadata.githubNotificationResolve;
+ task.description = 'File a tracker issue using the API';
+ const apiPrompt = await render(task);
+ expect(apiPrompt).toContain('## Completion (No Code Output)');
+ expect(apiPrompt).not.toContain('## Simplify Step');
+ expect(apiPrompt).not.toContain('## Completion (External Repository)');
+ });
+ });
+}
diff --git a/server/services/githubNotificationResolveTask.js b/server/services/githubNotificationResolveTask.js
index 2f7229a16b..844874ffdd 100644
--- a/server/services/githubNotificationResolveTask.js
+++ b/server/services/githubNotificationResolveTask.js
@@ -138,9 +138,10 @@ export async function queueNotificationResolveTask({ account, row, origin = 'use
// PortOS worktree, and a clean PortOS tree is success.
useWorktree: false,
openPR: false,
- noCodeOutput: true,
+ noCodeOutput: ['review', 'other'].includes(resolveKind(row)),
worktreeChangesExpected: false,
metadata: {
+ externalRepositoryOutput: ['own-pr', 'ci', 'issue'].includes(resolveKind(row)),
githubNotificationResolve: {
accountId: account.id, threadId: row.thread_id, host: account.host, repo, subjectType: row.subject_type, reason: row.reason, origin,
},
diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.js
index 56e637357a..24972fcafb 100644
--- a/server/services/githubNotifications.db.test.js
+++ b/server/services/githubNotifications.db.test.js
@@ -909,7 +909,7 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
const tasks = vi.mocked(addTask).mock.calls.map(([task]) => task);
expect(tasks).toHaveLength(2);
const repoTask = tasks.find((task) => task.metadata.githubSecurityFix.repo);
- expect(repoTask).toMatchObject({ useWorktree: false, openPR: false, noCodeOutput: true, metadata: { githubSecurityFix: { repo: `${account.login}/tool` } } });
+ expect(repoTask).toMatchObject({ useWorktree: false, openPR: false, metadata: { externalRepositoryOutput: true, githubSecurityFix: { repo: `${account.login}/tool` } } });
expect(repoTask.description.split('\n')[0]).toBe(`Fix the open security alerts in github.com/${account.login}/tool`);
expect(repoTask.description).toContain(`gh repo clone ${account.login}/tool`);
const advisoryTask = tasks.find((task) => !task.metadata.githubSecurityFix.repo);
diff --git a/server/services/githubSecurityFixTask.js b/server/services/githubSecurityFixTask.js
index fe2fc9c926..6d5328a258 100644
--- a/server/services/githubSecurityFixTask.js
+++ b/server/services/githubSecurityFixTask.js
@@ -47,7 +47,7 @@ function buildPrompt({ host, login, repo, advisories }) {
const steps = [
`Find the repositories these advisories affect: list your repositories with \`${gh} "user/repos?affiliation=owner&per_page=100" --paginate --jq '.[] | select(.archived | not) | .full_name'\`, then for each one \`${gh} "repos/<repo>/dependabot/alerts?state=open&per_page=100" --jq '[.[] | select(${select})] | length'\`. Skip a repo whose alerts are not readable. If none is affected, stop and report that.`,
'For each affected repository, in turn:',
- ...SCRATCH_STEPS('<repo>').map((step) => ` - ${step}`),
+ ...SCRATCH_STEPS(host === 'github.com' ? '<repo>' : `${host}/<repo>`).map((step) => ` - ${step}`),
];
return [
`Fix security advisories ${ids} across your ${host} repositories`,
@@ -79,9 +79,8 @@ export async function queueSecurityFixTask({ account, repo = null, advisories =
// clone during the run: no PortOS worktree, and a clean PortOS tree is success.
useWorktree: false,
openPR: false,
- noCodeOutput: true,
worktreeChangesExpected: false,
- metadata: { githubSecurityFix: { host: account.host, repo, advisories: ids, origin } },
+ metadata: { externalRepositoryOutput: true, githubSecurityFix: { host: account.host, repo, advisories: ids, origin } },
}, 'user');
if (!task?.id) return { error: 'The task could not be queued' };
return task.duplicate ? { duplicate: true, taskId: task.id } : { taskId: task.id };
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 3d6f79b8a4..b69349ef36 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -32,6 +32,8 @@ const RECONCILE_FLOW_GUIDANCE = 'Follow the branch reconciliation task above for
const CHECKOUT_RECOVERY_GUIDANCE = 'Follow the app checkout recovery task above in the actual configured checkout. You own verified backups, backup refs, preservation branches and PRs, configured reviews, current-head required CI and merge gates, stash accounting, and final checkout verification against the latest origin default branch. Preserve active work and retain backups when blocked. Publish every unique change on a named branch with an open or merged PR; never push preservation work directly to the default branch. Existing commits may be preserved and published without making a new commit. PortOS performs no implicit commit, push, or worktree merge-back for this task. Report verified outcomes and PR URLs, or INCOMPLETE with retained work and the first unverified checkpoint; keep private paths and data out of public artifacts.';
+const EXTERNAL_REPOSITORY_GUIDANCE = 'Deliver only the external repository work explicitly authorized by the task, in a scratch clone outside the PortOS checkout. You may edit code, commit, push and open a PR there only as the task directs; merge only when the task explicitly authorizes it and its required checks pass. Never edit, commit, push or open a PR from the PortOS checkout. PortOS will not publish or merge this work for you. A verified no-action result (such as zero open alerts) needs no commit or PR. The absence of an existing bot PR does not block creating an authorized fix PR. Report checked evidence, PR links and any unresolved work or blocker; do not claim completion while required work remains.';
+
const RELEASE_FLOW_GUIDANCE = 'Follow the bundled release workflow through its final verification and report. It owns release delivery; do not stop at a prepared commit or hand publication back to PortOS. If it cannot complete, report INCOMPLETE and the first unverified checkpoint instead of claiming a successful release.';
/**
@@ -129,6 +131,7 @@ export function buildCompletionGuidelineBullet({
const bullets = {
[COMPLETION_MODES.TOOL_FREE]: () => TOOL_FREE_REASONING_BULLET,
[COMPLETION_MODES.SENTINEL_PAYLOAD]: () => REASONING_ONLY_BULLET,
+ [COMPLETION_MODES.EXTERNAL_REPOSITORY]: () => EXTERNAL_REPOSITORY_GUIDANCE,
[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.',
@@ -167,7 +170,7 @@ export function buildCompletionGuidelineBullet({
}
-// The modes whose contract forbids a commit outright, so the trailing
+// The modes whose contract owns or forbids commits, 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
@@ -176,6 +179,7 @@ const NO_COMMIT_TARGET_MODES = new Set([
COMPLETION_MODES.TOOL_FREE,
COMPLETION_MODES.SENTINEL_PAYLOAD,
COMPLETION_MODES.ACTION_OUTPUT,
+ COMPLETION_MODES.EXTERNAL_REPOSITORY,
COMPLETION_MODES.DISCARD_WORKTREE,
COMPLETION_MODES.CLAIM_FLOW,
COMPLETION_MODES.RECONCILE_FLOW,
@@ -227,6 +231,10 @@ export function buildFallbackCompletionInstructions({
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.EXTERNAL_REPOSITORY]: () => ({
+ step4: EXTERNAL_REPOSITORY_GUIDANCE,
+ gitHygiene: `- ${EXTERNAL_REPOSITORY_GUIDANCE}`,
+ }),
[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.',
@@ -451,6 +459,15 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPath
);
}
+export function buildExternalRepositoryCompletionSection({ isTui = false, sentinelPath = null } = {}) {
+ const notice = `## Completion (External Repository)\n${EXTERNAL_REPOSITORY_GUIDANCE}`;
+ if (!isTui || !sentinelPath) return notice;
+ return sentinelCompletionSection(
+ notice,
+ `After verifying the outcome or identifying a blocker, write a summary with evidence, PR links and remaining work to \`${sentinelPath}\` and stop.`
+ );
+}
+
export function buildCheckoutRecoveryCompletionSection({ sentinelPath } = {}) {
return [
'## App Checkout Recovery Handoff',