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

feat: file an issue and/or queue a fix when the goal-fidelity review finds a problem

[._.]/ Adam Eivyf2ec26d9fe8f
diff --git a/client/src/components/settings/CodeReviewersTab.jsx b/client/src/components/settings/CodeReviewersTab.jsx
index 346c81958e..32ffe4be51 100644
--- a/client/src/components/settings/CodeReviewersTab.jsx
+++ b/client/src/components/settings/CodeReviewersTab.jsx
@@ -7,6 +7,7 @@ import ReviewerPicker from '../cos/ReviewerPicker';
import GoalFidelityControls from './GoalFidelityControls';
import useReviewerModelOptions from '../../hooks/useReviewerModelOptions';
import { reviewerModelsFromDefaults, reviewerModelsToDefaults, reviewerEffortsFromDefaults, reviewerEffortsToDefaults } from '../../lib/reviewerModels';
+import { DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER } from '../../lib/reviewerPins';
import {
DEFAULT_REVIEWERS,
DEFAULT_REVIEW_STOP_MODE,
@@ -31,7 +32,10 @@ export default function CodeReviewersTab() {
const [reviewerEfforts, setReviewerEfforts] = useState({});
const [stopMode, setStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);
const [reviewerApplies, setReviewerApplies] = useState(false);
- const [goalFidelity, setGoalFidelity] = useState({ enabled: true, backend: null, model: null, effort: null });
+ const [goalFidelity, setGoalFidelity] = useState({
+ enabled: true, backend: null, model: null, effort: null,
+ fileIssue: false, queueTask: false, followUpOn: DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ });
const [installed, setInstalled] = useState({});
const [providerReviewUnsupported, setProviderReviewUnsupported] = useState({});
const modelOptions = useReviewerModelOptions();
@@ -61,6 +65,12 @@ export default function CodeReviewersTab() {
backend: defaults.goalFidelity?.backend || null,
model: defaults.goalFidelity?.model || null,
effort: defaults.goalFidelity?.effort || null,
+ // Both follow-up actions default OFF — filing on a tracker and
+ // spawning an unattended run are each opt-in — so an absent block
+ // must read as off, the mirror image of `enabled` above.
+ fileIssue: defaults.goalFidelity?.fileIssue === true,
+ queueTask: defaults.goalFidelity?.queueTask === true,
+ followUpOn: defaults.goalFidelity?.followUpOn || DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
});
setInstalled(defaults.installed && typeof defaults.installed === 'object' && !Array.isArray(defaults.installed) ? defaults.installed : {});
setProviderReviewUnsupported(defaults.providerReviewUnsupported && typeof defaults.providerReviewUnsupported === 'object' && !Array.isArray(defaults.providerReviewUnsupported) ? defaults.providerReviewUnsupported : {});
@@ -101,6 +111,12 @@ export default function CodeReviewersTab() {
...(goalFidelity.backend ? { backend: goalFidelity.backend } : {}),
...(goalFidelity.model ? { model: goalFidelity.model } : {}),
...(goalFidelity.effort ? { effort: goalFidelity.effort } : {}),
+ // Booleans always ride: unlike the scalars above, `false` here is the
+ // user turning an action OFF, not "inherit", so dropping it would make
+ // the switch un-clearable once it had been on.
+ fileIssue: goalFidelity.fileIssue === true,
+ queueTask: goalFidelity.queueTask === true,
+ followUpOn: goalFidelity.followUpOn || DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
},
};
const ok = await api.updateSettings({ codeReview: payload }, { silent: true })
diff --git a/client/src/components/settings/CodeReviewersTab.test.jsx b/client/src/components/settings/CodeReviewersTab.test.jsx
index f427a70da2..8f7d1b8054 100644
--- a/client/src/components/settings/CodeReviewersTab.test.jsx
+++ b/client/src/components/settings/CodeReviewersTab.test.jsx
@@ -166,7 +166,12 @@ describe('CodeReviewersTab', () => {
await waitFor(() => expect(api.updateSettings).toHaveBeenCalled());
const [payload] = api.updateSettings.mock.calls[0];
- expect(payload.codeReview.goalFidelity).toEqual({ enabled: true, backend: 'lmstudio' });
+ // The scalars are dropped when unset (absent = inherit), but the follow-up
+ // booleans always ride: false there is the user's OFF, not 'inherit', and
+ // dropping it would make either switch un-clearable once it had been on.
+ expect(payload.codeReview.goalFidelity).toEqual({
+ enabled: true, backend: 'lmstudio', fileIssue: false, queueTask: false, followUpOn: 'rethink',
+ });
});
it('sends an explicit off switch, and drops the unset pins rather than persisting empty ones', async () => {
@@ -186,6 +191,73 @@ describe('CodeReviewersTab', () => {
fireEvent.click(screen.getByRole('button', { name: 'Save defaults' }));
await waitFor(() => expect(api.updateSettings).toHaveBeenCalled());
- expect(api.updateSettings.mock.calls[0][0].codeReview.goalFidelity).toEqual({ enabled: false });
+ expect(api.updateSettings.mock.calls[0][0].codeReview.goalFidelity).toEqual({
+ enabled: false, fileIssue: false, queueTask: false, followUpOn: 'rethink',
+ });
+ });
+
+ // The follow-up half (#7690): what happens once the gate HAS a finding.
+ it('round-trips the follow-up actions and their trigger', async () => {
+ api.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['ollama'],
+ usernames: [],
+ optionalReviewers: [],
+ reviewerMaxRounds: {},
+ stopMode: 'all',
+ reviewerApplies: false,
+ goalFidelity: { enabled: true, fileIssue: true, queueTask: false, followUpOn: 'any-finding' },
+ });
+ api.updateSettings.mockResolvedValue({});
+
+ render(<CodeReviewersTab />);
+ expect(await screen.findByLabelText(/File an issue on the project/)).toBeChecked();
+ expect(screen.getByLabelText(/Queue an agent to reconcile it/)).not.toBeChecked();
+ expect(screen.getByLabelText('Act on which verdicts')).toHaveValue('any-finding');
+
+ fireEvent.click(screen.getByLabelText(/Queue an agent to reconcile it/));
+ fireEvent.click(screen.getByRole('button', { name: 'Save defaults' }));
+
+ await waitFor(() => expect(api.updateSettings).toHaveBeenCalled());
+ expect(api.updateSettings.mock.calls[0][0].codeReview.goalFidelity).toMatchObject({
+ fileIssue: true, queueTask: true, followUpOn: 'any-finding',
+ });
+ });
+
+ // Filing on someone's tracker and spawning an unattended run are each opt-in,
+ // so an absent block must read as off — the mirror image of `enabled` above.
+ it('defaults both follow-up actions to off when the stored block omits them', async () => {
+ api.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['ollama'],
+ usernames: [],
+ optionalReviewers: [],
+ reviewerMaxRounds: {},
+ stopMode: 'all',
+ reviewerApplies: false,
+ goalFidelity: { enabled: true },
+ });
+
+ render(<CodeReviewersTab />);
+ expect(await screen.findByLabelText(/File an issue on the project/)).not.toBeChecked();
+ expect(screen.getByLabelText(/Queue an agent to reconcile it/)).not.toBeChecked();
+ // The trigger is meaningless until an action is armed.
+ expect(screen.getByLabelText('Act on which verdicts')).toBeDisabled();
+ });
+
+ // Turning the gate off leaves no verdict for a follow-up to act on, so the
+ // actions have to go inert with it rather than reading as still armed.
+ it('disables the follow-up actions when the gate itself is off', async () => {
+ api.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['ollama'],
+ usernames: [],
+ optionalReviewers: [],
+ reviewerMaxRounds: {},
+ stopMode: 'all',
+ reviewerApplies: false,
+ goalFidelity: { enabled: false, fileIssue: true },
+ });
+
+ render(<CodeReviewersTab />);
+ expect(await screen.findByLabelText(/File an issue on the project/)).toBeDisabled();
+ expect(screen.getByLabelText(/Queue an agent to reconcile it/)).toBeDisabled();
});
});
diff --git a/client/src/components/settings/GoalFidelityControls.jsx b/client/src/components/settings/GoalFidelityControls.jsx
index 1baa40d27f..f14b24c3c4 100644
--- a/client/src/components/settings/GoalFidelityControls.jsx
+++ b/client/src/components/settings/GoalFidelityControls.jsx
@@ -1,5 +1,17 @@
import { LOCAL_LLM_EFFORT_LEVELS, LOCAL_LLM_REVIEWERS, reviewerLabel } from '../cos/constants';
-import { sanitizeReviewerModelInput } from '../../lib/reviewerPins';
+import {
+ DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ sanitizeReviewerModelInput,
+} from '../../lib/reviewerPins';
+
+// What each trigger means in the user's terms. The values mirror the server's
+// `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` enum; the prose is why one would pick the
+// wider one — `fix-first` never downgrades a run, so an issue is the only thing
+// that carries those findings past the run record.
+const FOLLOW_UP_TRIGGER_OPTIONS = [
+ { value: 'rethink', label: 'Only “rethink” — the run built the wrong thing' },
+ { value: 'any-finding', label: 'Any finding — also the advisory “fix-first”' },
+];
// The goal-fidelity gate's controls (#5994) — the SECOND review, which asks
// whether a finished run's diff delivers the objective the task stated, rather
@@ -15,7 +27,22 @@ import { sanitizeReviewerModelInput } from '../../lib/reviewerPins';
export default function GoalFidelityControls({ value, modelOptions, disabled = false, onChange }) {
const enabled = value?.enabled !== false;
const backend = value?.backend || '';
- const patch = (fields) => onChange({ enabled, backend: value?.backend || null, model: value?.model || null, effort: value?.effort || null, ...fields });
+ const fileIssue = value?.fileIssue === true;
+ const queueTask = value?.queueTask === true;
+ const followUpOn = value?.followUpOn || DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER;
+ const patch = (fields) => onChange({
+ enabled,
+ backend: value?.backend || null,
+ model: value?.model || null,
+ effort: value?.effort || null,
+ fileIssue,
+ queueTask,
+ followUpOn,
+ ...fields,
+ });
+ // The trigger only means something once one of the two actions is on, and
+ // both are meaningless with the gate itself off.
+ const followUpDisabled = disabled || !enabled;
// Only a chosen backend has a catalog to offer. With none chosen the model and
// effort fields are inert on purpose: a pin typed against "whatever the chain
@@ -104,6 +131,59 @@ export default function GoalFidelityControls({ value, modelOptions, disabled = f
</select>
</div>
</div>
+
+ <div className="border-t border-port-border/60 pt-2.5 space-y-2">
+ <p className="text-[11px] uppercase tracking-wide text-gray-500">When the review finds a problem</p>
+
+ <label className="flex items-start gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ id="goal-fidelity-file-issue"
+ checked={fileIssue}
+ disabled={followUpDisabled}
+ onChange={(e) => patch({ fileIssue: e.target.checked })}
+ className="mt-0.5 accent-port-accent disabled:opacity-50"
+ />
+ <span>
+ <span className="text-sm text-white">File an issue on the project’s tracker</span>
+ <span className="block text-xs text-gray-500">
+ Writes the finding to whichever tracker the app actually uses — GitHub, GitLab, or JIRA — so it outlives the run record. Re-filing is suppressed by a key carried in the issue body: an existing issue for the same finding is reused even after it has been closed, and a tracker PortOS can’t read refuses the filing rather than risking a duplicate.
+ </span>
+ </span>
+ </label>
+
+ <label className="flex items-start gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ id="goal-fidelity-queue-task"
+ checked={queueTask}
+ disabled={followUpDisabled}
+ onChange={(e) => patch({ queueTask: e.target.checked })}
+ className="mt-0.5 accent-port-accent disabled:opacity-50"
+ />
+ <span>
+ <span className="text-sm text-white">Queue an agent to reconcile it</span>
+ <span className="block text-xs text-gray-500">
+ Adds a CoS task that claims the filed issue — or, with no issue filed, works the finding directly. Runs in a worktree behind a PR, and shares the investigation queue’s duplicate guard and hourly circuit breaker, so a repeated drift can’t spawn one agent per run.
+ </span>
+ </span>
+ </label>
+
+ <div>
+ <label htmlFor="goal-fidelity-follow-up-on" className="block text-[11px] text-gray-500 mb-1">Act on which verdicts</label>
+ <select
+ id="goal-fidelity-follow-up-on"
+ value={followUpOn}
+ disabled={followUpDisabled || (!fileIssue && !queueTask)}
+ onChange={(e) => patch({ followUpOn: e.target.value })}
+ className="w-full sm:w-2/3 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
+ >
+ {FOLLOW_UP_TRIGGER_OPTIONS.map(({ value: option, label }) => (
+ <option key={option} value={option}>{label}</option>
+ ))}
+ </select>
+ </div>
+ </div>
</div>
);
}
diff --git a/client/src/lib/reviewerPins.js b/client/src/lib/reviewerPins.js
index 678931457c..a95b816041 100644
--- a/client/src/lib/reviewerPins.js
+++ b/client/src/lib/reviewerPins.js
@@ -58,6 +58,13 @@ export const MAX_REVIEWER_MODEL_LENGTH = 200;
// LOCAL_LLM_EFFORT_LEVELS.
export const LOCAL_LLM_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high']);
+// Which goal-fidelity verdicts fire the follow-up actions (file an issue /
+// queue a fix). Mirror of GOAL_FIDELITY_FOLLOW_UP_TRIGGERS in
+// server/lib/goalFidelityFollowUp.js — the settings schema is a `z.enum` over
+// it, so a value offered here but absent there 400s the whole settings save.
+export const GOAL_FIDELITY_FOLLOW_UP_TRIGGERS = Object.freeze(['rethink', 'any-finding']);
+export const DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER = 'rethink';
+
// The effort ladder each reviewer offers, or absent when it has no effort control
// (`copilot` is a GitHub review, and an
// `@username` reviewer is a person). A ladder means the level is PICKABLE, not
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 08190c9120..ca5f8c7b22 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -72,7 +72,7 @@ Submit tasks, manage durable autonomous agents, schedule recurring automations,
| **AI Providers & Model Runner** | `/ai` | Multi-provider configuration supporting CLI agents (Claude Code, Codex, Antigravity, OpenCode), cloud APIs (OpenAI, Anthropic, Gemini, Grok), and local endpoints (Ollama, LM Studio, vLLM, SGLang). | [Claude on Ollama](./claude-ollama.md) |
| **Prompt Manager** | `/prompts` | Reusable prompt template library, variable substitution engine, prompt versioning, and auto-upgrade migrations. | [Prompt Manager](./prompt-manager.md) |
| **Runs & Run Events Ledger** | `/cos/runs`, `/cos/run-events` | Comprehensive ledger of past and in-flight AI runs, lifecycle event replay, and orphaned process recovery. | — |
-| **Code Reviewers** | `/settings/code-reviewers` | Configurable multi-reviewer chain (Copilot, Claude, Antigravity, Codex, Grok, Cursor, OpenCode, Kimi, LM Studio, Ollama, MTPLX) with stop conditions, max rounds, per-reviewer model/effort pins, dispute workflows, and the goal-fidelity gate that re-reads a finished CoS run's diff against the task's stated objective (`ship` / `fix-first` / `rethink`). | — |
+| **Code Reviewers** | `/settings/code-reviewers` | Configurable multi-reviewer chain (Copilot, Claude, Antigravity, Codex, Grok, Cursor, OpenCode, Kimi, LM Studio, Ollama, MTPLX) with stop conditions, max rounds, per-reviewer model/effort pins, dispute workflows, and the goal-fidelity gate that re-reads a finished CoS run's diff against the task's stated objective (`ship` / `fix-first` / `rethink`) and can, on a finding, file an issue on the project's own tracker (GitHub / GitLab / JIRA, deduplicated by a key carried in the issue body) and/or queue an agent to reconcile it. | — |
---
diff --git a/server/lib/README.md b/server/lib/README.md
index 056010d67b..a381f3a82f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -525,6 +525,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |
| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. |
+| `goalFidelityFollowUp.js` | Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. `resolveGoalFidelityFollowUp(codeReview)` (`null` when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked) and `goalFidelityFollowUpApplies(review, trigger)` over `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` (`rethink` = only the verdict that holds a run, the default; `any-finding` also fires on the advisory `fix-first`). `goalFidelityFingerprint(task)` is the one dedup identity three parties share — the tracker search, the issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`, a colon-free token because every forge parses `:` as a search qualifier), and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. `buildGoalFidelityIssue` / `buildGoalFidelityFollowUpTask` compose the bodies. Pure; I/O lives in `services/goalFidelityFollowUp.js`. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. Also `getNavPageForPath(pathname)` → `{ label, section, breadcrumb }` for the most specific command that owns a route (`null` for one nothing declares) — how user-facing copy NAMES a page it links to, instead of typing "Models → LLMs" beside the link and stranding it on the next move (#7414). `expandPageToken(text, runtime)` expands a `{page}` token in `text` using `getNavPageForPath(runtime?.manageUrl)`, falling back to generic prose rather than shipping a literal `{page}` (#7419). |
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 8aa7047540..8eb9bd0a21 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -25,6 +25,7 @@ import { CLAIM_DRAIN_TASK_TYPES } from './qualitySchedulePlan.js';
import { JOB_INTERVAL_VALUES } from './autonomousJobIntervals.js';
import { jobFormFieldsSchema, jobFormValuesSchema } from './jobFormFields.js';
import { TASK_DATA_INPUT_DEFINITIONS, TASK_DATA_INPUT_IDS } from './taskDataInputCatalog.js';
+import { GOAL_FIDELITY_FOLLOW_UP_TRIGGERS } from './goalFidelityFollowUp.js';
import {
EFFORT_SELECTABLE_REVIEWERS,
KEYED_REVIEWER_PINS,
@@ -699,11 +700,21 @@ export const codeReviewSettingsSchema = z.object({
// pin no request would carry. All four absent = inherit the quality chain's own
// local reviewer (see `resolveGoalFidelityConfig`); `enabled: false` is the
// explicit off switch.
+ //
+ // `fileIssue` / `queueTask` / `followUpOn` are the FOLLOW-UP half (see
+ // `lib/goalFidelityFollowUp.js`): what to do about a finding once the review
+ // has one. Both actions default OFF — filing on someone's tracker and
+ // spawning an unattended run are each a thing a user opts into — and
+ // `followUpOn` narrows which verdicts count, defaulting to the `rethink` that
+ // already holds a run.
goalFidelity: z.object({
enabled: z.boolean().optional(),
backend: z.preprocess(emptyToUndefined, z.enum(LOCAL_LLM_REVIEWERS).optional()),
model: z.string().max(MAX_REVIEWER_MODEL_LENGTH).optional(),
effort: z.preprocess(emptyToUndefined, z.string().optional()),
+ fileIssue: z.boolean().optional(),
+ queueTask: z.boolean().optional(),
+ followUpOn: z.preprocess(emptyToUndefined, z.enum(GOAL_FIDELITY_FOLLOW_UP_TRIGGERS).optional()),
}).strict().optional(),
}).strict();
diff --git a/server/lib/goalFidelityFollowUp.js b/server/lib/goalFidelityFollowUp.js
new file mode 100644
index 0000000000..49bf0cf245
--- /dev/null
+++ b/server/lib/goalFidelityFollowUp.js
@@ -0,0 +1,271 @@
+/**
+ * Goal-fidelity FOLLOW-UP contract — pure.
+ *
+ * `goalFidelity.js` owns the second review's verdict ("did this run ship what
+ * was asked?"). This module owns what happens NEXT when that review found a
+ * problem: file the finding on the project's own tracker so it outlives the run
+ * record, and/or queue an agent to go fix it.
+ *
+ * Both are off by default and independent of each other. A user who wants a
+ * durable backlog entry but no unattended follow-up run gets one; a user who
+ * wants the fix attempted immediately without cluttering the tracker gets the
+ * other; turning both on files the issue first so the queued task can name it.
+ *
+ * The dedup identity lives here rather than in the filer because THREE parties
+ * have to agree on it — the forge search that decides "already filed", the
+ * issue body that carries the marker that search reads back, and the CoS task
+ * fingerprint that stops a second follow-up run for the same finding. A
+ * scheduled task regenerates with a fresh id every cadence, so keying on the
+ * task id alone would re-file the same finding forever; the key is instead
+ * `taskType` + app + a slug of the objective's first line, which is stable
+ * across those regenerations and distinct between genuinely different work.
+ *
+ * Pure and I/O-free: the settings resolver, the filer, the queue producer, and
+ * the tests share one definition of what a follow-up IS.
+ *
+ * DEPENDENCY-FREE by design. `cosValidation.js` imports this for the settings
+ * enum, and it is reached by most of the server suite — so the obvious edge
+ * here (`investigationTasks.js`, for its `investigationFingerprint` formatter)
+ * put five modules on ~80 suites' closures and blew the import budget for one
+ * three-segment template string. The format is inlined instead, and
+ * `goalFidelityFollowUp.test.js` pins it against the real
+ * `investigationFingerprint` so the two cannot drift: the test pays the import,
+ * production does not. See server/AGENTS.md "Import scoping".
+ */
+
+/**
+ * Which verdicts trigger a follow-up.
+ *
+ * - `rethink` — only the verdict that already holds the run. The default:
+ * it is the one the gate itself treats as "this built the
+ * wrong thing", so filing on it can't bury a tracker.
+ * - `any-finding` — `rethink` OR `fix-first`. `fix-first` deliberately does NOT
+ * downgrade a run (see `goalFidelityHoldsRun`), so on an
+ * install that wants those recorded, an issue is the only
+ * thing that carries them past the run record.
+ *
+ * `ship` never triggers a follow-up under either setting — there is no finding.
+ */
+export const GOAL_FIDELITY_FOLLOW_UP_TRIGGERS = Object.freeze(['rethink', 'any-finding']);
+
+/** The trigger an install gets when it has configured none. */
+export const DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER = 'rethink';
+
+/** The verdicts each trigger fires on. */
+const TRIGGER_VERDICTS = Object.freeze({
+ rethink: Object.freeze(['rethink']),
+ 'any-finding': Object.freeze(['rethink', 'fix-first']),
+});
+
+/** Marker label every goal-fidelity-filed issue carries, so the backlog is readable by origin. */
+export const GOAL_FIDELITY_ISSUE_LABEL = 'goal-fidelity';
+
+/** `{ color, description }` for the marker label, created lazily before the file. */
+export const GOAL_FIDELITY_ISSUE_LABEL_SPEC = Object.freeze({
+ color: 'B60205',
+ description: 'Filed by the PortOS goal-fidelity review',
+});
+
+/** `category` segment of the shared `category:kind:scope` fingerprint. */
+export const GOAL_FIDELITY_FINGERPRINT_CATEGORY = 'goal-fidelity';
+
+/** Longest objective slug folded into a fingerprint — long enough to read in a log line. */
+const SUBJECT_SLUG_MAX = 80;
+
+/** Bounds on what crosses into a world-readable issue. */
+export const GOAL_FIDELITY_ISSUE_LIMITS = Object.freeze({
+ titleChars: 160,
+ bodyChars: 12_000,
+ /** Items rendered as a bullet list; the review itself already caps at 10. */
+ maxItems: 10,
+});
+
+/**
+ * Resolve the follow-up half of the `goalFidelity` settings block.
+ *
+ * Reads the RAW block rather than the gate's resolved config, because the two
+ * answer different questions: the gate's resolve returns `null` when no local
+ * backend is callable, and a caller only reaches this code when a review
+ * already produced a verdict. Threading the follow-up through that resolve
+ * would make "which backend judged it" a precondition for "what do we do about
+ * the answer", which it is not.
+ *
+ * Returns `null` when neither action is on — the caller's cheap "nothing to do"
+ * check, distinct from an object with both flags false, which would read as
+ * configured-and-inert.
+ *
+ * @param {Object|null} codeReview - the raw `settings.codeReview` block.
+ * @returns {{ fileIssue: boolean, queueTask: boolean, trigger: string }|null}
+ */
+export function resolveGoalFidelityFollowUp(codeReview) {
+ const raw = codeReview && typeof codeReview === 'object' ? codeReview.goalFidelity : null;
+ // The gate being off takes every follow-up with it: no verdict is produced,
+ // so a stored `fileIssue: true` under it describes an action nothing can
+ // trigger. Resolving it to `null` keeps the UI and the runtime agreeing.
+ if (!raw || typeof raw !== 'object' || raw.enabled === false) return null;
+ const fileIssue = raw.fileIssue === true;
+ const queueTask = raw.queueTask === true;
+ if (!fileIssue && !queueTask) return null;
+ const trigger = GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.includes(raw.followUpOn)
+ ? raw.followUpOn
+ : DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER;
+ return { fileIssue, queueTask, trigger };
+}
+
+/** Does this verdict fire the configured trigger? */
+export function goalFidelityFollowUpApplies(review, trigger) {
+ const verdicts = TRIGGER_VERDICTS[trigger] || TRIGGER_VERDICTS[DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER];
+ return verdicts.includes(review?.verdict);
+}
+
+/** Lowercase `a-z0-9-` slug of free text, bounded. */
+function subjectSlug(text) {
+ return String(text ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, SUBJECT_SLUG_MAX)
+ .replace(/-+$/, '');
+}
+
+/** First non-blank line of a task description, trimmed. */
+function firstLine(text) {
+ return String(text ?? '').split('\n').map(line => line.trim()).find(Boolean) || '';
+}
+
+/**
+ * The durable dedup key for one goal-fidelity finding.
+ *
+ * Same three-segment `category:kind:scope` shape every other investigation key
+ * uses, built by the same function, so the CoS task side participates in the
+ * existing fingerprint dedup and loop policy for free.
+ *
+ * `scope` folds the app AND the objective slug, because one app runs many
+ * different tasks and a per-app key would collapse every finding on that app
+ * into one issue. The verdict is deliberately NOT in the key: a finding that
+ * degrades from `rethink` to `fix-first` between runs is the same unfinished
+ * work, and keying on it would file a second issue for it.
+ */
+export function goalFidelityFingerprint(task) {
+ const app = subjectSlug(task?.metadata?.app);
+ const subject = subjectSlug(firstLine(task?.description));
+ const scope = app ? `${app}/${subject}` : subject;
+ // The `category:kind:scope` shape of `investigationFingerprint`, inlined
+ // rather than imported (see the module header) and pinned against it by test.
+ return `${GOAL_FIDELITY_FINGERPRINT_CATEGORY}:${task?.taskType || 'task'}:${scope || 'none'}`;
+}
+
+/**
+ * The exact string a duplicate search looks for in an existing issue.
+ *
+ * A single hyphenated token with no colons, spaces, or quotes: every forge's
+ * full-text search treats `:` as a qualifier separator, so the raw
+ * `goal-fidelity:user:…` fingerprint would be parsed as a query rather than
+ * matched as text — and on GitHub an unknown qualifier fails the whole search.
+ * The `portosgf-` prefix keeps it from colliding with ordinary prose.
+ *
+ * The search is only a NARROWING step. Every forge tokenizes on hyphens too, so
+ * a search hit is a candidate; `issueMatchesGoalFidelityMarker` decides, by
+ * substring, on the text the forge actually returned.
+ */
+export function goalFidelityIssueMarker(fingerprint) {
+ const token = String(fingerprint ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '');
+ return `portosgf-${token}`;
+}
+
+/**
+ * Does this issue carry our marker for `fingerprint`?
+ *
+ * Reads `body` or `description` because the three trackers spell the same field
+ * two ways (`gh`/`glab` normalize to `body`; JIRA returns `description`), and a
+ * dedup that silently looked at the wrong one would read every existing issue
+ * as a non-match and re-file on every run.
+ */
+export function issueMatchesGoalFidelityMarker(issue, fingerprint) {
+ const marker = goalFidelityIssueMarker(fingerprint);
+ return `${issue?.title || ''}\n${issue?.summary || ''}\n${issue?.body || ''}\n${issue?.description || ''}`.includes(marker);
+}
+
+/** Bounded markdown bullet list, or a fallback sentence when the list is empty. */
+function bulletList(items, empty) {
+ const rows = (Array.isArray(items) ? items : [])
+ .filter(item => typeof item === 'string' && item.trim())
+ .slice(0, GOAL_FIDELITY_ISSUE_LIMITS.maxItems);
+ return rows.length ? rows.map(item => `- ${item}`).join('\n') : empty;
+}
+
+const truncate = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
+
+/**
+ * Compose the issue this finding files.
+ *
+ * Every interpolated field is either operator-authored (the task's own first
+ * line) or model-authored free text the review already trimmed and capped
+ * (`missing` / `unrequested` / `evidence`). None of it is interpolated into a
+ * command or a path, and the filer scrubs home-directory prefixes and
+ * credential-shaped strings out of BOTH the title and the body before the CLI
+ * sees them — a filed issue is world-readable the moment it lands.
+ *
+ * The body deliberately does not link the agent run: run ids are local to one
+ * install, and the tracker is shared.
+ */
+export function buildGoalFidelityIssue({ task, review, fingerprint }) {
+ const subject = firstLine(task?.description) || 'a CoS agent task';
+ const title = truncate(`Goal-fidelity ${review?.verdict || 'finding'}: ${subject}`, GOAL_FIDELITY_ISSUE_LIMITS.titleChars);
+ // The marker sits in the SECOND paragraph, not the last: a reader of this
+ // issue gets it from a truncated body just as reliably as from a whole one,
+ // and the open-issue fallback scan reads bodies the forge lister has already
+ // capped at 8k. A marker parked at the bottom would drop out of exactly the
+ // long issues most likely to be re-filed.
+ const body = truncate([
+ `A goal-fidelity review of a finished agent run returned **${review?.verdict}** — the change that shipped does not match what the task asked for.`,
+ `Filed automatically by the PortOS goal-fidelity review. Re-filing is suppressed while an issue carrying this key exists: \`${goalFidelityIssueMarker(fingerprint)}\``,
+ `## What was asked\n${subject}`,
+ `## Named as missing\n${bulletList(review?.missing, '_The review named nothing specific as missing._')}`,
+ `## Named as unrequested\n${bulletList(review?.unrequested, '_The review named nothing specific as unrequested._')}`,
+ `## Reviewer evidence\n${review?.evidence ? review.evidence : '_The review recorded no evidence note._'}`,
+ `## Review provenance\nJudged by \`${review?.backend || 'a local model'}\`${review?.model ? ` (\`${review.model}\`)` : ''}${review?.diffTruncated ? ', against a TRUNCATED diff — confirm the finding against the full change' : ''}.`,
+ ].join('\n\n'), GOAL_FIDELITY_ISSUE_LIMITS.bodyChars);
+ return { title, body };
+}
+
+/**
+ * The CoS task body for the queued follow-up run.
+ *
+ * Two different jobs depending on whether an issue was filed: with one, the
+ * agent claims that issue through the project's normal claim flow, which is
+ * where the tracker's own conventions (labels, PR linkage, closing keywords)
+ * already live. Without one, it works the finding directly from this body —
+ * which is why the finding is restated here in full rather than pointing at an
+ * issue that may not exist.
+ */
+export function buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue = null }) {
+ const subject = firstLine(task?.description) || 'a CoS agent task';
+ const header = `[Auto] Reconcile goal-fidelity ${review?.verdict} [${fingerprint}]: ${subject}`;
+ const claim = issue?.url
+ ? `## What to do\nClaim ${issue.number ? `#${issue.number}` : 'the filed issue'} (${issue.url}) and ship the reconciliation through the project's normal claim flow.`
+ : `## What to do\nRe-read the task above against what actually shipped, then reconcile the two. Ship the change through the project's normal PR flow.`;
+ return [
+ header,
+ `## What happened\nA goal-fidelity review of the finished run for task \`${task?.id || 'unknown'}\` returned **${review?.verdict}**: the diff does not deliver the stated objective.`,
+ `## Named as missing\n${bulletList(review?.missing, '_Nothing specific._')}`,
+ `## Named as unrequested\n${bulletList(review?.unrequested, '_Nothing specific._')}`,
+ claim,
+ ].join('\n\n');
+}
+
+/** One-line human summary of what the follow-up actually did, for a log line. */
+export function formatGoalFidelityFollowUpSummary(result) {
+ const parts = [
+ result?.issue?.duplicate ? `issue #${result.issue.number} already tracks it` : null,
+ result?.issue && !result.issue.duplicate ? `filed ${result.issue.number ? `#${result.issue.number}` : 'an issue'}` : null,
+ result?.issueError ? `issue not filed (${result.issueError})` : null,
+ result?.task?.duplicate ? 'follow-up task already queued' : null,
+ result?.task && !result.task.duplicate ? `queued follow-up task ${result.task.id}` : null,
+ result?.taskError ? `follow-up task not queued (${result.taskError})` : null,
+ ].filter(Boolean);
+ return parts.length ? `Goal-fidelity follow-up: ${parts.join('; ')}` : 'Goal-fidelity follow-up: nothing to do';
+}
diff --git a/server/lib/goalFidelityFollowUp.test.js b/server/lib/goalFidelityFollowUp.test.js
new file mode 100644
index 0000000000..16598eafeb
--- /dev/null
+++ b/server/lib/goalFidelityFollowUp.test.js
@@ -0,0 +1,294 @@
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ GOAL_FIDELITY_FOLLOW_UP_TRIGGERS,
+ buildGoalFidelityFollowUpTask,
+ buildGoalFidelityIssue,
+ formatGoalFidelityFollowUpSummary,
+ goalFidelityFingerprint,
+ goalFidelityFollowUpApplies,
+ goalFidelityIssueMarker,
+ issueMatchesGoalFidelityMarker,
+ resolveGoalFidelityFollowUp,
+} from './goalFidelityFollowUp.js';
+
+const review = (over = {}) => ({
+ verdict: 'rethink',
+ missing: ['the retry cap the task named'],
+ unrequested: [],
+ evidence: 'The diff rewrites the scheduler instead.',
+ backend: 'ollama',
+ model: 'qwen3',
+ ...over,
+});
+
+describe('resolveGoalFidelityFollowUp', () => {
+ it('is null when neither action is configured, so a disabled install pays nothing', () => {
+ expect(resolveGoalFidelityFollowUp(null)).toBeNull();
+ expect(resolveGoalFidelityFollowUp({})).toBeNull();
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: {} })).toBeNull();
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: { fileIssue: false, queueTask: false } })).toBeNull();
+ });
+
+ it('resolves each action independently', () => {
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: { fileIssue: true } }))
+ .toEqual({ fileIssue: true, queueTask: false, trigger: 'rethink' });
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: { queueTask: true } }))
+ .toEqual({ fileIssue: false, queueTask: true, trigger: 'rethink' });
+ });
+
+ // The gate produces no verdict when it is off, so a stored `fileIssue: true`
+ // under `enabled: false` describes an action nothing can trigger. Resolving
+ // it anyway would make the UI and the runtime disagree about what is armed.
+ it('the gate being off takes every follow-up with it', () => {
+ expect(resolveGoalFidelityFollowUp({
+ goalFidelity: { enabled: false, fileIssue: true, queueTask: true },
+ })).toBeNull();
+ });
+
+ it('falls back to the default trigger for an absent or unknown value', () => {
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: { fileIssue: true, followUpOn: 'everything' } }).trigger)
+ .toBe(DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER);
+ expect(resolveGoalFidelityFollowUp({ goalFidelity: { fileIssue: true, followUpOn: 'any-finding' } }).trigger)
+ .toBe('any-finding');
+ });
+});
+
+describe('goalFidelityFollowUpApplies', () => {
+ it('`rethink` fires only on the verdict that already holds a run', () => {
+ expect(goalFidelityFollowUpApplies({ verdict: 'rethink' }, 'rethink')).toBe(true);
+ expect(goalFidelityFollowUpApplies({ verdict: 'fix-first' }, 'rethink')).toBe(false);
+ expect(goalFidelityFollowUpApplies({ verdict: 'ship' }, 'rethink')).toBe(false);
+ });
+
+ it('`any-finding` adds the advisory verdict but never a clean one', () => {
+ expect(goalFidelityFollowUpApplies({ verdict: 'fix-first' }, 'any-finding')).toBe(true);
+ expect(goalFidelityFollowUpApplies({ verdict: 'rethink' }, 'any-finding')).toBe(true);
+ expect(goalFidelityFollowUpApplies({ verdict: 'ship' }, 'any-finding')).toBe(false);
+ });
+
+ // An unreadable verdict is `null` by contract (`normalizeGoalFidelityVerdict`),
+ // and nothing judged the run — it must not file an issue.
+ it('never fires on an absent verdict, under either trigger', () => {
+ for (const trigger of GOAL_FIDELITY_FOLLOW_UP_TRIGGERS) {
+ expect(goalFidelityFollowUpApplies(null, trigger)).toBe(false);
+ expect(goalFidelityFollowUpApplies({}, trigger)).toBe(false);
+ }
+ });
+
+ it('an unknown trigger degrades to the default rather than firing on everything', () => {
+ expect(goalFidelityFollowUpApplies({ verdict: 'fix-first' }, 'bogus')).toBe(false);
+ expect(goalFidelityFollowUpApplies({ verdict: 'rethink' }, 'bogus')).toBe(true);
+ });
+});
+
+describe('goalFidelityFingerprint', () => {
+ // The whole point of the key: a perpetual/scheduled task is regenerated with a
+ // FRESH id every cadence, so a key derived from the id would re-file forever.
+ it('is stable across a regenerated task with a new id', () => {
+ const first = goalFidelityFingerprint({ id: 'task-1', taskType: 'user', description: 'Add retry caps\nmore', metadata: { app: 'comics' } });
+ const second = goalFidelityFingerprint({ id: 'task-999', taskType: 'user', description: 'Add retry caps\ndifferent tail', metadata: { app: 'comics' } });
+ expect(first).toBe(second);
+ });
+
+ it('separates different apps, task types, and objectives', () => {
+ const base = { id: 'a', taskType: 'user', description: 'Add retry caps', metadata: { app: 'comics' } };
+ const key = goalFidelityFingerprint(base);
+ expect(goalFidelityFingerprint({ ...base, metadata: { app: 'bookloom' } })).not.toBe(key);
+ expect(goalFidelityFingerprint({ ...base, taskType: 'internal' })).not.toBe(key);
+ expect(goalFidelityFingerprint({ ...base, description: 'Rewrite the scheduler' })).not.toBe(key);
+ });
+
+ // A verdict that softens from `rethink` to `fix-first` between runs is the same
+ // unfinished work; keying on it would file a second issue for one finding.
+ it('does not vary with the verdict', () => {
+ const task = { taskType: 'user', description: 'Add retry caps', metadata: { app: 'comics' } };
+ expect(goalFidelityFingerprint(task)).toBe(goalFidelityFingerprint(task));
+ });
+
+ it('keeps the three-segment shape even with nothing to key on', () => {
+ expect(goalFidelityFingerprint(undefined).split(':')).toHaveLength(3);
+ });
+
+ // The key is inlined rather than imported (the module is dependency-free so
+ // `cosValidation.js` can take the settings enum without dragging the
+ // investigation-task graph onto most of the server suite). This is what stops
+ // the two formats drifting: the CoS task side dedupes with the real one.
+ it('is byte-identical to the shared investigation fingerprint format', async () => {
+ const { investigationFingerprint } = await import('./investigationTasks.js');
+ const cases = [
+ { taskType: 'user', description: 'Add retry caps', metadata: { app: 'comics' } },
+ { taskType: 'internal', description: 'Rewrite the scheduler' },
+ undefined,
+ ];
+ for (const task of cases) {
+ const app = String(task?.metadata?.app ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+ const subject = String(task?.description ?? '').split('\n')[0].trim()
+ .toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+ expect(goalFidelityFingerprint(task)).toBe(investigationFingerprint({
+ category: 'goal-fidelity',
+ kind: task?.taskType,
+ scope: app ? `${app}/${subject}` : subject,
+ }));
+ }
+ });
+});
+
+describe('goalFidelityIssueMarker', () => {
+ // Every forge parses `:` as a search-qualifier separator, and GitHub fails the
+ // whole search on an unknown qualifier — a marker carrying one would make the
+ // dedup read as "nothing filed" on every run.
+ it('is a single token with no forge search metacharacters', () => {
+ const marker = goalFidelityIssueMarker('goal-fidelity:user:comics/add-retry-caps');
+ expect(marker).toBe('portosgf-goal-fidelity-user-comics-add-retry-caps');
+ expect(marker).toMatch(/^[a-z0-9-]+$/);
+ });
+
+ it('distinct fingerprints keep distinct markers', () => {
+ expect(goalFidelityIssueMarker('goal-fidelity:user:a')).not.toBe(goalFidelityIssueMarker('goal-fidelity:user:b'));
+ });
+});
+
+describe('issueMatchesGoalFidelityMarker', () => {
+ const fingerprint = 'goal-fidelity:user:comics/add-retry-caps';
+ const marker = goalFidelityIssueMarker(fingerprint);
+
+ // `gh`/`glab` normalize to `body`; JIRA returns `description`. Reading only one
+ // would silently treat every existing ticket as a non-match on the other forge.
+ it('reads the body OR the description, because the trackers disagree on the field', () => {
+ expect(issueMatchesGoalFidelityMarker({ body: `text ${marker}` }, fingerprint)).toBe(true);
+ expect(issueMatchesGoalFidelityMarker({ description: `text ${marker}` }, fingerprint)).toBe(true);
+ });
+
+ it('does not match a different fingerprint or an unmarked issue', () => {
+ expect(issueMatchesGoalFidelityMarker({ body: marker }, 'goal-fidelity:user:other')).toBe(false);
+ expect(issueMatchesGoalFidelityMarker({ body: 'a goal-fidelity finding' }, fingerprint)).toBe(false);
+ expect(issueMatchesGoalFidelityMarker(null, fingerprint)).toBe(false);
+ });
+
+ it('round-trips against the body the filer actually writes', () => {
+ const { body } = buildGoalFidelityIssue({
+ task: { description: 'Add retry caps' }, review: review(), fingerprint,
+ });
+ expect(issueMatchesGoalFidelityMarker({ body }, fingerprint)).toBe(true);
+ });
+});
+
+describe('buildGoalFidelityIssue', () => {
+ const fingerprint = 'goal-fidelity:user:comics/add-retry-caps';
+
+ it('names the verdict, the objective, and both item lists', () => {
+ const { title, body } = buildGoalFidelityIssue({
+ task: { description: 'Add retry caps to the queue\nplus detail' },
+ review: review({ unrequested: ['a new settings page'] }),
+ fingerprint,
+ });
+ expect(title).toBe('Goal-fidelity rethink: Add retry caps to the queue');
+ expect(body).toContain('the retry cap the task named');
+ expect(body).toContain('a new settings page');
+ expect(body).toContain('The diff rewrites the scheduler instead.');
+ expect(body).toContain('`ollama`');
+ });
+
+ // A marker parked at the bottom drops out of exactly the long issues most
+ // likely to be re-filed: the forge lister caps bodies at 8k before the dedup
+ // rescan ever sees them.
+ it('puts the dedup marker in the first 500 characters', () => {
+ const { body } = buildGoalFidelityIssue({
+ task: { description: 'Add retry caps' },
+ review: review({ missing: Array.from({ length: 10 }, (_, i) => 'x'.repeat(400) + i) }),
+ fingerprint,
+ });
+ expect(body.slice(0, 500)).toContain(goalFidelityIssueMarker(fingerprint));
+ });
+
+ it('says so explicitly when the review judged a truncated diff', () => {
+ const { body } = buildGoalFidelityIssue({
+ task: { description: 'Add retry caps' }, review: review({ diffTruncated: true }), fingerprint,
+ });
+ expect(body).toContain('TRUNCATED diff');
+ });
+
+ it('bounds the title and the body', () => {
+ const { title, body } = buildGoalFidelityIssue({
+ task: { description: 'x'.repeat(5_000) },
+ review: review({ missing: Array.from({ length: 40 }, () => 'y'.repeat(400)) }),
+ fingerprint,
+ });
+ expect(title.length).toBeLessThanOrEqual(160);
+ expect(body.length).toBeLessThanOrEqual(12_000);
+ });
+
+ it('reads as a finding even when the review named nothing specific', () => {
+ const { body } = buildGoalFidelityIssue({
+ task: { description: 'Add retry caps' },
+ review: review({ missing: [], unrequested: [], evidence: '' }),
+ fingerprint,
+ });
+ expect(body).toContain('named nothing specific as missing');
+ expect(body).toContain('recorded no evidence note');
+ });
+});
+
+describe('buildGoalFidelityFollowUpTask', () => {
+ const fingerprint = 'goal-fidelity:user:comics/add-retry-caps';
+ const task = { id: 'task-7', description: 'Add retry caps' };
+
+ // With an issue the agent runs the project's normal claim flow, where the
+ // tracker's own conventions live; without one it must work the finding from
+ // this body, which is why the finding is restated in both shapes.
+ it('points the agent at the filed issue when there is one', () => {
+ const body = buildGoalFidelityFollowUpTask({
+ task, review: review(), fingerprint, issue: { number: 42, url: 'https://example.com/issues/42' },
+ });
+ expect(body).toContain('#42');
+ expect(body).toContain('https://example.com/issues/42');
+ expect(body).toContain('claim flow');
+ });
+
+ it('restates the finding when no issue was filed', () => {
+ const body = buildGoalFidelityFollowUpTask({ task, review: review(), fingerprint });
+ expect(body).not.toContain('claim flow');
+ expect(body).toContain('the retry cap the task named');
+ expect(body).toContain('task-7');
+ });
+
+ // The fingerprint rides in the headline for the same reason the investigation
+ // producer's does: `addTask`'s first-line dedup is what catches a repeat whose
+ // metadata scan has not landed yet.
+ it('carries the fingerprint in the first line', () => {
+ const body = buildGoalFidelityFollowUpTask({ task, review: review(), fingerprint });
+ expect(body.split('\n')[0]).toContain(fingerprint);
+ });
+});
+
+describe('formatGoalFidelityFollowUpSummary', () => {
+ it('distinguishes a fresh file from a duplicate and from a failure', () => {
+ expect(formatGoalFidelityFollowUpSummary({ issue: { number: 42 } })).toContain('filed #42');
+ expect(formatGoalFidelityFollowUpSummary({ issue: { number: 42, duplicate: true } })).toContain('already tracks it');
+ expect(formatGoalFidelityFollowUpSummary({ issueError: 'gh unreachable' })).toContain('gh unreachable');
+ });
+
+ it('reports both arms, since one can succeed while the other fails', () => {
+ const summary = formatGoalFidelityFollowUpSummary({
+ issueError: 'gh unreachable', task: { id: 'task-9' },
+ });
+ expect(summary).toContain('gh unreachable');
+ expect(summary).toContain('task-9');
+ });
+
+ it('says nothing happened rather than nothing at all', () => {
+ expect(formatGoalFidelityFollowUpSummary({})).toContain('nothing to do');
+ });
+});
+
+// The settings schema is a `z.enum` over the server list, so a value the picker
+// offers but the enum omits 400s the whole settings save — silently, from the
+// user's point of view, since the rest of the form saved fine last time.
+describe('client mirror of the follow-up trigger vocabulary', () => {
+ it('matches the client leaf the picker reads', async () => {
+ const client = await import('../../client/src/lib/reviewerPins.js');
+ expect([...client.GOAL_FIDELITY_FOLLOW_UP_TRIGGERS]).toEqual([...GOAL_FIDELITY_FOLLOW_UP_TRIGGERS]);
+ expect(client.DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER).toBe(DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 8c8e0a0c2c..d6bffcc207 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -374,6 +374,7 @@ export * from './repoUrl.js';
export * from './glabArgs.js';
export * from './goalFeatureMap.js';
export * from './goalFidelity.js';
+export * from './goalFidelityFollowUp.js';
export * from './interactiveShellResolver.js';
export * from './killWithEscalation.js';
export * from './npmGlobalBin.js';
diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.js
index 662754557b..c0f8b6e8b1 100644
--- a/server/services/agentFinalization.goalFidelity.test.js
+++ b/server/services/agentFinalization.goalFidelity.test.js
@@ -71,6 +71,14 @@ vi.mock('./taskTypeHooks.js', () => ({
getTaskOutputHook: vi.fn(async () => null),
getTaskOutputPayloadPredicate: vi.fn(async () => null),
}));
+// The follow-up (file an issue / queue a fix) is dispatched through a LAZY
+// import, so it is doubled here rather than left to load the real filer's
+// apps + forge + JIRA graph into a suite that only cares about the wiring.
+const runGoalFidelityFollowUpMock = vi.fn(async () => ({ ran: false }));
+vi.mock('./goalFidelityFollowUp.js', () => ({
+ runGoalFidelityFollowUp: (...args) => runGoalFidelityFollowUpMock(...args),
+}));
+
vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));
vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));
@@ -360,6 +368,60 @@ describe('finalizeAgent — goal-fidelity gate', () => {
}
});
+// The follow-up is what carries a finding past this run's record — but the
+ // filer reaches the network, so a failure there must never change the run's
+ // own verdict.
+ describe('follow-up dispatch', () => {
+ beforeEach(() => {
+ runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'rethink', missing: ['the retry'] }));
+ });
+
+ it('hands the follow-up the review, and records what it did on the run', async () => {
+ runGoalFidelityFollowUpMock.mockResolvedValue({
+ ran: true,
+ issue: { number: 42, url: 'https://example.com/issues/42', duplicate: false },
+ task: { id: 'cos-9' },
+ });
+ await finalize();
+ expect(runGoalFidelityFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({
+ agentId: 'agent-1', review: expect.objectContaining({ verdict: 'rethink' }),
+ }));
+ expect(completion().goalFidelity.followUp).toEqual({
+ issue: { number: 42, url: 'https://example.com/issues/42', duplicate: false },
+ taskId: 'cos-9',
+ });
+ });
+
+ it('records the reason when an arm could not run', async () => {
+ runGoalFidelityFollowUpMock.mockResolvedValue({ ran: true, issueError: 'gh unreachable', task: null, taskError: 'circuit open' });
+ await finalize();
+ expect(completion().goalFidelity.followUp).toEqual({ issueError: 'gh unreachable', taskError: 'circuit open' });
+ });
+
+ it('leaves no followUp key when nothing was configured', async () => {
+ runGoalFidelityFollowUpMock.mockResolvedValue({ ran: false });
+ await finalize();
+ expect(completion().goalFidelity.followUp).toBeUndefined();
+ });
+
+ it('a throwing follow-up does not change the run verdict', async () => {
+ runGoalFidelityFollowUpMock.mockRejectedValue(new Error('forge exploded'));
+ await finalize();
+ // Still held by the rethink verdict — and held for THAT reason, not the throw.
+ expect(completion()).toMatchObject({ success: false, completionReason: GOAL_FIDELITY_CATEGORY });
+ expect(completion().goalFidelity.followUp).toBeUndefined();
+ });
+
+ // A ship verdict is still a verdict: the gate ran and cleared the run, so
+ // the follow-up is asked and declines on the trigger, not skipped here.
+ it('is consulted on a clean verdict too, and stays silent', async () => {
+ runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'ship' }));
+ await finalize();
+ expect(runGoalFidelityFollowUpMock).toHaveBeenCalled();
+ expect(completion().success).toBe(true);
+ });
+ });
+
it('never re-judges a run that already failed — the original diagnosis is the better one', async () => {
await finalize({ success: false, errorAnalysis: { category: 'timeout', message: 'agent timed out' } });
expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index db62187fbf..d342dad2f2 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -49,6 +49,7 @@ import {
goalFidelityHoldsRun,
taskObjective,
} from '../lib/goalFidelity.js';
+import { formatGoalFidelityFollowUpSummary } from '../lib/goalFidelityFollowUp.js';
import { getGoalFidelityConfig, runLocalGoalFidelityReview } from './codeReview.js';
import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
@@ -1191,6 +1192,31 @@ export async function finalizeAgent({
// named missing/unrequested items are what make the hold actionable.
cosEvents.emit(GOAL_FIDELITY_HOLD_EVENT, { agentId, taskId: task?.id, review: fidelity.review });
}
+ // A finding that lives only in this run's record dies with the agent card
+ // nobody opened. When the user has configured it, the follow-up files the
+ // finding on the project's own tracker and/or queues the run that fixes it.
+ // Lazily imported: the filer reaches the apps roster, both forge CLIs, and
+ // (for a JIRA-tracked app) the JIRA client, and a static edge would put all
+ // of it on the closure of every suite that reaches finalization.
+ if (fidelity.review) {
+ const followUp = await import('./goalFidelityFollowUp.js')
+ .then(({ runGoalFidelityFollowUp }) => runGoalFidelityFollowUp({ agentId, task, review: fidelity.review }))
+ .catch(err => {
+ emitLog('warn', `⚠️ Goal-fidelity follow-up failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id });
+ return null;
+ });
+ if (followUp?.ran) {
+ emitLog('info', `📌 ${formatGoalFidelityFollowUpSummary(followUp)} for ${agentId}`, { agentId, taskId: task?.id });
+ // Recorded on the review so the agent card can link the issue and the
+ // queued task without re-deriving either from the tracker.
+ fidelity.review.followUp = {
+ ...(followUp.issue ? { issue: { number: followUp.issue.number, url: followUp.issue.url, duplicate: followUp.issue.duplicate === true } } : {}),
+ ...(followUp.issueError ? { issueError: followUp.issueError } : {}),
+ ...(followUp.task?.id ? { taskId: followUp.task.id } : {}),
+ ...(followUp.taskError ? { taskError: followUp.taskError } : {}),
+ };
+ }
+ }
if (verdict.success && isTruthyMetaFn) {
await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 5c56a52b96..600b96044c 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -50,6 +50,10 @@ import {
normalizeGoalFidelityVerdict,
resolveGoalFidelityConfig,
} from '../lib/goalFidelity.js'
+import {
+ DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ GOAL_FIDELITY_FOLLOW_UP_TRIGGERS,
+} from '../lib/goalFidelityFollowUp.js'
import { getSettings, settingsEvents } from './settings.js'
// LM Studio (`:1234`), Ollama (`:11434`) and MTPLX (`:8000/v1`) all ship
@@ -131,6 +135,14 @@ export function pickCodeReviewDefaults(settings) {
backend: typeof raw?.goalFidelity?.backend === 'string' ? raw.goalFidelity.backend : null,
model: typeof raw?.goalFidelity?.model === 'string' ? raw.goalFidelity.model : null,
effort: typeof raw?.goalFidelity?.effort === 'string' ? raw.goalFidelity.effort : null,
+ // Follow-up actions. `enabled` above defaults ON, so an absent block reads
+ // as on; these two default OFF, so an absent block reads as off — the
+ // asymmetry is deliberate and matches what the resolver does at runtime.
+ fileIssue: raw?.goalFidelity?.fileIssue === true,
+ queueTask: raw?.goalFidelity?.queueTask === true,
+ followUpOn: GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.includes(raw?.goalFidelity?.followUpOn)
+ ? raw.goalFidelity.followUpOn
+ : DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
},
// Faithful mirror of the stored scalars, deliberately NOT shape-checked here:
// `/api/code-review/local` passes these as a JSON request-body field where a
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index 94d15f4ade..79b997ea52 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -96,7 +96,9 @@ describe('codeReview helpers', () => {
// inheriting whatever the chain runs". Deliberately its own block rather
// than more `<reviewer>*` scalars: it is a different review with a different
// question, and the user can run it on a different model.
- const NO_GOAL_FIDELITY = { goalFidelity: { enabled: true, backend: null, model: null, effort: null } }
+ // The two follow-up actions default OFF — the mirror image of enabled — so an
+ // unset block reads as the gate on and nothing armed to act on its verdict.
+ const NO_GOAL_FIDELITY = { goalFidelity: { enabled: true, backend: null, model: null, effort: null, fileIssue: false, queueTask: false, followUpOn: 'rethink' } }
it('returns no reviewers when settings has no codeReview slice', () => {
expect(pickCodeReviewDefaults(null)).toEqual({
reviewers: [],
diff --git a/server/services/goalFidelityFollowUp.js b/server/services/goalFidelityFollowUp.js
new file mode 100644
index 0000000000..ce4f658763
--- /dev/null
+++ b/server/services/goalFidelityFollowUp.js
@@ -0,0 +1,367 @@
+/**
+ * Goal-fidelity follow-up — file the finding, and/or queue the fix.
+ *
+ * The goal-fidelity gate (`lib/goalFidelity.js`, run from `agentFinalization`)
+ * answers "did this run ship what was asked?". Until now a `rethink` verdict
+ * held the run and raised a Review Hub alert, and that was the end of it: the
+ * finding lived in one install's run record, where it could only be acted on by
+ * the person who happened to open the agent card.
+ *
+ * This module is the durable half. On a verdict the user configured as
+ * actionable it can:
+ *
+ * - FILE the finding on whichever tracker the project actually uses — GitHub,
+ * GitLab, or JIRA, resolved from the app's own `workTracker` so the issue
+ * lands where a claim would read it; and/or
+ * - QUEUE a CoS follow-up task so an agent reconciles it without a human
+ * relaying the finding by hand.
+ *
+ * The two are independent switches. Filing first means the queued task can name
+ * the issue and run the project's normal claim flow instead of re-deriving the
+ * work from prose.
+ *
+ * DUPLICATE SUPPRESSION is the load-bearing part, because the producer is a
+ * scheduled unattended loop: a perpetual task that keeps drifting the same way
+ * would otherwise file the same issue every cadence, forever. Three guards, all
+ * keyed on the one fingerprint `lib/goalFidelityFollowUp.js` derives:
+ *
+ * 1. an all-states marker search on the tracker, so a CLOSED issue for the
+ * same finding is not re-filed;
+ * 2. an open-issue rescan, because forge full-text indexes lag by minutes and
+ * two runs of the same schedule inside that window are ordinary;
+ * 3. the shared investigation-task fingerprint dedup + circuit breaker on the
+ * queued task, via `fileInvestigationTask`.
+ *
+ * FAIL-CLOSED on the issue side, on purpose and against the usual convention: a
+ * tracker we could not read is NOT "nothing is filed". That is exactly how a
+ * transient `gh` blip files a duplicate. Refusing to file costs one missed
+ * issue on a finding that will recur; filing blind costs a tracker.
+ *
+ * Nothing here can fail a run. `agentFinalization` calls this after the verdict
+ * is decided, records what happened, and proceeds either way.
+ */
+
+import { execGh, ensureForgeReachable } from './github.js';
+import { execGlab, execGlabJson } from './gitlab.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
+import { listAppIssues } from './appIssues.js';
+import { getAppById } from './apps.js';
+import { ROOT_DIR } from './cosState.js';
+import { getSettings } from './settings.js';
+import { fileInvestigationTask } from './investigationTaskProducer.js';
+import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { boundedErrorMessage } from '../lib/errorHandler.js';
+import { scrubHomePath } from '../lib/homePath.js';
+import { scrubSecretTokens } from '../lib/secretText.js';
+import {
+ GOAL_FIDELITY_ISSUE_LABEL,
+ GOAL_FIDELITY_ISSUE_LABEL_SPEC,
+ buildGoalFidelityFollowUpTask,
+ buildGoalFidelityIssue,
+ goalFidelityFingerprint,
+ goalFidelityFollowUpApplies,
+ goalFidelityIssueMarker,
+ issueMatchesGoalFidelityMarker,
+ resolveGoalFidelityFollowUp,
+} from '../lib/goalFidelityFollowUp.js';
+
+/** Candidates a marker search may return before we substring-confirm them. */
+const SEARCH_LIMIT = 30;
+/** Page size for the open-issue rescan on GitLab and the JIRA marker search. */
+const PAGE_LIMIT = 100;
+
+/**
+ * The last thing that happens to a title/body before a tracker sees it.
+ *
+ * Same enforcement as the persistent mind's filer, for the same reason: a filed
+ * issue is world-readable the moment it lands, and the free text here is
+ * model-authored prose derived from an untrusted diff. `scrubHomePath` collapses
+ * the running user's home prefix (which embeds the OS username in
+ * `/Users/<name>/…`); `scrubSecretTokens` replaces credential-shaped substrings.
+ * Applied to the TITLE too — it is as public as the body.
+ *
+ * Deliberately NOT applied to the fingerprint marker's own text: it is derived
+ * from a slug of the task's first line and carries no path or credential shape,
+ * and a scrub that rewrote it would break the dedup it exists to serve.
+ */
+const scrubForgeText = (value) => scrubSecretTokens(scrubHomePath(value));
+
+/**
+ * The repository this task's work lives in, as an app-record shape the forge
+ * resolvers accept.
+ *
+ * A task with no `metadata.app` is PortOS's own work, which runs against the
+ * install root — the same fallback `agentWorkspacePrep` uses to pick a
+ * workspace, so the tracker this files to is the tracker the run touched.
+ */
+async function resolveFollowUpRepo(task) {
+ const appId = task?.metadata?.app;
+ if (!appId) return { id: null, name: 'PortOS', repoPath: ROOT_DIR, workTracker: 'auto' };
+ const app = await getAppById(appId).catch(() => null);
+ if (!app?.repoPath) return null;
+ return app;
+}
+
+/**
+ * GitHub: candidates carrying the marker, across OPEN and CLOSED.
+ *
+ * `--search` is a narrowing step whose ranking we do not trust — the caller
+ * substring-confirms every row. Returns `null` for "could not read", which the
+ * caller treats as a refusal to file rather than an absence of duplicates.
+ */
+async function searchGithubMarker({ target, repoPath, forgeAccount, marker }) {
+ const { cwd, env, customEnv } = await resolveForgeExecOptions(repoPath, { forgeAccount });
+ const forge = await ensureForgeReachable('goal-fidelity-followup', {
+ hostname: target.apiHost,
+ ...(customEnv ? { env: customEnv } : {}),
+ });
+ if (!forge.ok) return null;
+ const raw = await execGh([
+ 'issue', 'list', '--repo', target.repoSpec, '--state', 'all',
+ '--search', marker, '--limit', String(SEARCH_LIMIT),
+ '--json', 'number,title,body,url,state',
+ ], undefined, { cwd, env }).catch((err) => {
+ console.error(`❌ goal-fidelity follow-up: gh marker search failed for ${target.repoSpec}: ${err.message}`);
+ return null;
+ });
+ const rows = safeJSONParse(raw, null);
+ return Array.isArray(rows) ? rows : null;
+}
+
+/**
+ * GitLab: `glab issue list --all` is every STATE, not every page — the page cap
+ * rides separately. glab has no reliable cross-version full-text issue search
+ * flag, so this reads a bounded page and the caller substring-confirms; the
+ * marker sits in the second paragraph of the body precisely so a capped read
+ * still finds it.
+ */
+async function searchGitlabMarker({ repoPath }) {
+ const { rows } = await execGlabJson(['issue', 'list', '--all', '--per-page', String(PAGE_LIMIT)], repoPath);
+ if (!Array.isArray(rows)) return null;
+ return rows.map((row) => ({
+ number: row?.iid ?? null,
+ title: row?.title || '',
+ body: row?.description || '',
+ url: row?.web_url || '',
+ state: row?.state || '',
+ }));
+}
+
+/**
+ * JIRA: a `text ~` marker match inside the app's own project. The project is
+ * scoped explicitly — a marker search across every project the token can see
+ * would dedupe one app's finding against another's.
+ *
+ * `jira.js` is imported lazily here and in the filer below: only a JIRA-tracked
+ * app ever reaches it, and a static edge would put the whole JIRA client (and
+ * its axios/client graph) on the closure of every suite that transitively
+ * reaches agent finalization. See server/AGENTS.md "Import scoping".
+ */
+async function searchJiraMarker({ jira, marker }) {
+ const { searchIssues, escapeJql } = await import('./jira.js');
+ const jql = `project = "${escapeJql(jira.projectKey)}" AND text ~ "${escapeJql(marker)}"`;
+ const rows = await searchIssues(jira.instanceId, jql, {
+ fields: 'summary,description,status',
+ maxResults: SEARCH_LIMIT,
+ }).catch((err) => {
+ console.error(`❌ goal-fidelity follow-up: JIRA marker search failed for ${jira.projectKey}: ${err.message}`);
+ return null;
+ });
+ if (!Array.isArray(rows)) return null;
+ return rows.map((row) => ({
+ number: row?.key ?? null,
+ title: row?.summary || '',
+ body: row?.description || '',
+ url: row?.url || '',
+ state: row?.status || '',
+ }));
+}
+
+/**
+ * Every place a duplicate could already be, for one forge tracker: the marker
+ * search (all states) and the open-issue list (index-lag backstop).
+ *
+ * Returns `{ issue }` on a confirmed duplicate, `{ issue: null }` when both
+ * reads answered and neither matched, and `{ error }` when a read we needed
+ * could not be made. The three are distinct on purpose — collapsing the last
+ * into the middle is how a blip files a duplicate.
+ */
+async function findExistingForgeIssue({ app, target, tracker, fingerprint }) {
+ const marker = goalFidelityIssueMarker(fingerprint);
+ const candidates = tracker === 'github'
+ ? await searchGithubMarker({
+ target, repoPath: app.repoPath, forgeAccount: app.forgeAccount, marker,
+ })
+ : await searchGitlabMarker({ repoPath: app.repoPath });
+ if (!candidates) return { error: `could not read the ${tracker} issue list` };
+ const searchHit = candidates.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
+ if (searchHit) return { issue: searchHit };
+
+ // Index-lag backstop. GitHub's search index trails a creation by minutes, and
+ // two runs of one schedule inside that window is ordinary traffic — without
+ // this the second run files a duplicate the search genuinely could not see.
+ // GitLab's page read above is already a direct listing, so it needs no rescan.
+ if (tracker !== 'github') return { issue: null };
+ const open = await listAppIssues(app);
+ if (open.transient) return { error: `could not read the open ${tracker} issues (${open.reason})` };
+ const openHit = open.issues.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
+ return { issue: openHit || null };
+}
+
+/**
+ * Create the marker label, then the issue. The label create is idempotent and
+ * its failure is swallowed — both CLIs fail the whole `issue create` with a 422
+ * on an undefined label, so a label we could not create resurfaces as the
+ * create's own error if it actually mattered.
+ */
+async function createForgeIssue({ app, target, tracker, title, body }) {
+ const cli = tracker === 'gitlab' ? 'glab' : 'gh';
+ const spec = { name: GOAL_FIDELITY_ISSUE_LABEL, ...GOAL_FIDELITY_ISSUE_LABEL_SPEC };
+ await (cli === 'glab'
+ ? execGlab(forgeLabelCreateArgs(cli, spec), app.repoPath)
+ : execGh(forgeLabelCreateArgs(cli, spec, { repo: target.repoSpec }))).catch(() => null);
+
+ const args = forgeIssueCreateArgs(cli, {
+ title, body, labels: [GOAL_FIDELITY_ISSUE_LABEL], repo: cli === 'glab' ? null : target.repoSpec,
+ });
+ return (cli === 'glab'
+ ? execGlab(args, app.repoPath, undefined, { rejectOnError: true })
+ : execGh(args)
+ ).then(
+ (stdout) => ({ ok: true, ...parseCreatedForgeIssue(stdout) }),
+ (error) => ({ ok: false, error: boundedErrorMessage(error, 'Issue creation failed') }),
+ );
+}
+
+/**
+ * File one goal-fidelity finding on the app's tracker.
+ *
+ * @returns {Promise<{issue: object|null, error: string|null}>} `issue` carries
+ * `duplicate: true` when an existing item already tracks this fingerprint —
+ * the queued task still wants that item's URL, so a duplicate is a usable
+ * result, not a failure.
+ */
+async function fileFollowUpIssue({ task, review, fingerprint }) {
+ const app = await resolveFollowUpRepo(task);
+ if (!app) return { issue: null, error: `app '${task?.metadata?.app}' has no configured repository` };
+
+ const { tracker, target } = await resolveAppForgeTarget(app).catch(() => ({ tracker: null, target: null }));
+ const { title, body } = buildGoalFidelityIssue({ task, review, fingerprint });
+ // Scrubbed BEFORE the duplicate check, not just before the create: the text
+ // that dedupes has to be the text that gets filed.
+ const safeTitle = scrubForgeText(title);
+ const safeBody = scrubForgeText(body);
+
+ if (tracker === 'jira') return fileJiraFollowUpIssue({ app, fingerprint, title: safeTitle, body: safeBody });
+ if (tracker !== 'github' && tracker !== 'gitlab') {
+ return { issue: null, error: `this project's work tracker is ${tracker || 'unresolved'}, which has no issue to file` };
+ }
+ if (!target || target.forge !== tracker) {
+ return { issue: null, error: `the ${tracker} tracker does not match this repository's remote` };
+ }
+
+ const existing = await findExistingForgeIssue({ app, target, tracker, fingerprint });
+ if (existing.error) return { issue: null, error: `${existing.error}; nothing was filed` };
+ if (existing.issue) {
+ return { issue: { ...existing.issue, duplicate: true }, error: null };
+ }
+
+ const created = await createForgeIssue({ app, target, tracker, title: safeTitle, body: safeBody });
+ if (!created.ok) return { issue: null, error: created.error };
+ return { issue: { number: created.number, url: created.url, duplicate: false }, error: null };
+}
+
+/** The JIRA arm of the same contract: same marker dedup, a ticket instead of an issue. */
+async function fileJiraFollowUpIssue({ app, fingerprint, title, body }) {
+ const jira = app?.jira;
+ if (!jira?.enabled || !jira.instanceId || !jira.projectKey) {
+ return { issue: null, error: 'this project tracks work in JIRA, but its JIRA instance and project are not configured' };
+ }
+ const marker = goalFidelityIssueMarker(fingerprint);
+ const candidates = await searchJiraMarker({ jira, marker });
+ if (!candidates) return { issue: null, error: 'could not read the JIRA project to check for duplicates; nothing was filed' };
+ const hit = candidates.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
+ if (hit) return { issue: { ...hit, duplicate: true }, error: null };
+
+ const { createTicket } = await import('./jira.js');
+ const created = await createTicket(jira.instanceId, {
+ projectKey: jira.projectKey,
+ summary: title,
+ description: body,
+ issueType: jira.defaultIssueType || 'Task',
+ }).catch((err) => ({ success: false, error: boundedErrorMessage(err, 'JIRA ticket creation failed') }));
+ if (!created?.success) return { issue: null, error: created?.error || 'JIRA ticket creation failed' };
+ return { issue: { number: created.ticketId, url: created.url, duplicate: false }, error: null };
+}
+
+/**
+ * Queue the CoS follow-up run.
+ *
+ * Goes through the shared investigation producer rather than `addTask`
+ * directly, so this participates in the machinery every other failure-driven
+ * task already does: the durable fingerprint dedup (a second finding for the
+ * same cause folds into the open task), the rolling circuit breaker (a drift
+ * storm cannot mint one agent per failure), the loop policy (a cause we already
+ * queued a fix for and that came back is held for the human), and the
+ * worktree + PR delivery posture.
+ */
+async function queueFollowUpTask({ task, review, fingerprint, issue }) {
+ const description = buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue });
+ const filed = await fileInvestigationTask({
+ fingerprint,
+ description,
+ affectedTasks: task?.id ? [task.id] : [],
+ priority: 'MEDIUM',
+ context: `Auto-generated from a goal-fidelity ${review?.verdict} verdict`,
+ ...(task?.metadata?.app ? { app: task.metadata.app } : {}),
+ });
+ return filed?.task || null;
+}
+
+/**
+ * Run whatever follow-up the user configured for this verdict.
+ *
+ * Returns `{ ran: false }` when nothing is configured or the verdict does not
+ * fire the configured trigger — the overwhelmingly common path, and the reason
+ * this costs a disabled install nothing but one settings read.
+ *
+ * Every arm is individually fallible and individually reported: a tracker that
+ * refused the file must not also cancel the queued task, because the task is
+ * the arm that actually gets the work done.
+ *
+ * @param {{ agentId: string, task: object, review: object }} args
+ * @returns {Promise<{ran: boolean, fingerprint?: string, issue?: object|null,
+ * issueError?: string|null, task?: object|null, taskError?: string|null}>}
+ */
+export async function runGoalFidelityFollowUp({ agentId, task, review }) {
+ const settings = await getSettings().catch(() => null);
+ const config = resolveGoalFidelityFollowUp(settings?.codeReview);
+ if (!config) return { ran: false };
+ if (!goalFidelityFollowUpApplies(review, config.trigger)) return { ran: false };
+
+ const fingerprint = goalFidelityFingerprint(task);
+ const result = { ran: true, fingerprint, issue: null, issueError: null, task: null, taskError: null };
+
+ if (config.fileIssue) {
+ const filed = await fileFollowUpIssue({ task, review, fingerprint })
+ .catch((err) => ({ issue: null, error: boundedErrorMessage(err, 'Issue filing failed') }));
+ result.issue = filed.issue;
+ result.issueError = filed.error;
+ }
+
+ if (config.queueTask) {
+ const queued = await queueFollowUpTask({ task, review, fingerprint, issue: result.issue })
+ .catch((err) => {
+ console.error(`❌ goal-fidelity follow-up: could not queue a task for ${agentId}: ${err.message}`);
+ return null;
+ });
+ result.task = queued;
+ if (!queued) result.taskError = 'the follow-up task could not be queued';
+ }
+
+ return result;
+}
+
+export const __testing = { resolveFollowUpRepo, findExistingForgeIssue };
diff --git a/server/services/goalFidelityFollowUp.test.js b/server/services/goalFidelityFollowUp.test.js
new file mode 100644
index 0000000000..cbf6c2b5e7
--- /dev/null
+++ b/server/services/goalFidelityFollowUp.test.js
@@ -0,0 +1,387 @@
+/**
+ * The goal-fidelity follow-up filer, at its public boundary:
+ * `runGoalFidelityFollowUp({ agentId, task, review })` in → an issue on the
+ * right tracker and/or a queued CoS task out.
+ *
+ * The failure this suite exists to catch is a DUPLICATE. The producer is an
+ * unattended loop, so an issue filed twice is filed forever — which is why
+ * every tracker arm gets the same three cases: no existing issue (file), an
+ * existing one carrying the marker (reuse, including a CLOSED one), and a
+ * tracker we could not read (refuse, never file blind).
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const execGh = vi.fn();
+const execGlab = vi.fn();
+const execGlabJson = vi.fn();
+const ensureForgeReachable = vi.fn();
+const listAppIssues = vi.fn();
+const getAppById = vi.fn();
+const getSettings = vi.fn();
+const fileInvestigationTask = vi.fn();
+const resolveAppForgeTarget = vi.fn();
+const searchIssues = vi.fn();
+const createTicket = vi.fn();
+
+vi.mock('./github.js', () => ({ execGh, ensureForgeReachable }));
+vi.mock('./gitlab.js', () => ({ execGlab, execGlabJson }));
+vi.mock('./forgeExecOptions.js', () => ({
+ resolveForgeExecOptions: async () => ({ cwd: '/repo', env: {}, customEnv: null }),
+}));
+vi.mock('./appIssues.js', () => ({ listAppIssues }));
+vi.mock('./apps.js', () => ({ getAppById }));
+vi.mock('./cosState.js', () => ({ ROOT_DIR: '/portos' }));
+vi.mock('./settings.js', () => ({ getSettings }));
+vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask }));
+vi.mock('./jira.js', () => ({ searchIssues, createTicket, escapeJql: (s) => String(s) }));
+vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget }));
+
+const { runGoalFidelityFollowUp } = await import('./goalFidelityFollowUp.js');
+const { goalFidelityFingerprint, goalFidelityIssueMarker } = await import('../lib/goalFidelityFollowUp.js');
+
+const TASK = { id: 'task-7', taskType: 'user', description: 'Add retry caps', metadata: { app: 'comics' } };
+const REVIEW = {
+ verdict: 'rethink',
+ missing: ['the retry cap'],
+ unrequested: [],
+ evidence: 'Rewrote the scheduler instead.',
+ backend: 'ollama',
+ model: 'qwen3',
+};
+const FINGERPRINT = goalFidelityFingerprint(TASK);
+const MARKER = goalFidelityIssueMarker(FINGERPRINT);
+
+const GITHUB_APP = { id: 'comics', repoPath: '/repo', workTracker: 'github' };
+const GITHUB_TARGET = { forge: 'github', repoSpec: 'github.com/acme/comics', apiHost: 'github.com', fullName: 'acme/comics' };
+
+const settings = (goalFidelity) => getSettings.mockResolvedValue({ codeReview: { goalFidelity } });
+const run = () => runGoalFidelityFollowUp({ agentId: 'agent-1', task: TASK, review: REVIEW });
+
+/** A `gh issue list --json` reply. */
+const ghRows = (rows) => JSON.stringify(rows);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ ensureForgeReachable.mockResolvedValue({ ok: true });
+ getAppById.mockResolvedValue(GITHUB_APP);
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target: GITHUB_TARGET });
+ listAppIssues.mockResolvedValue({ transient: false, issues: [], reason: 'no-open-issues' });
+ execGh.mockResolvedValue(ghRows([]));
+ fileInvestigationTask.mockResolvedValue({ task: { id: 'cos-9' }, approvalRequired: false });
+});
+
+describe('runGoalFidelityFollowUp — when it runs at all', () => {
+ it('does nothing when neither action is configured', async () => {
+ settings({ enabled: true });
+ await expect(run()).resolves.toEqual({ ran: false });
+ expect(execGh).not.toHaveBeenCalled();
+ expect(fileInvestigationTask).not.toHaveBeenCalled();
+ });
+
+ it('does nothing on a verdict the configured trigger does not cover', async () => {
+ settings({ fileIssue: true, followUpOn: 'rethink' });
+ const result = await runGoalFidelityFollowUp({
+ agentId: 'agent-1', task: TASK, review: { ...REVIEW, verdict: 'fix-first' },
+ });
+ expect(result).toEqual({ ran: false });
+ expect(execGh).not.toHaveBeenCalled();
+ });
+
+ it('acts on fix-first once the wider trigger is chosen', async () => {
+ settings({ fileIssue: true, followUpOn: 'any-finding' });
+ execGh.mockResolvedValueOnce(ghRows([])).mockResolvedValue('https://github.com/acme/comics/issues/12');
+ const result = await runGoalFidelityFollowUp({
+ agentId: 'agent-1', task: TASK, review: { ...REVIEW, verdict: 'fix-first' },
+ });
+ expect(result.ran).toBe(true);
+ expect(result.issue).toMatchObject({ number: 12, duplicate: false });
+ });
+
+ // `ship` is not a finding under either trigger — the run delivered what was
+ // asked, so there is nothing to file and nothing to fix.
+ it('never acts on a clean verdict', async () => {
+ settings({ fileIssue: true, queueTask: true, followUpOn: 'any-finding' });
+ const result = await runGoalFidelityFollowUp({
+ agentId: 'agent-1', task: TASK, review: { ...REVIEW, verdict: 'ship' },
+ });
+ expect(result).toEqual({ ran: false });
+ });
+});
+
+describe('runGoalFidelityFollowUp — GitHub', () => {
+ it('files the issue with the marker label and reports its number', async () => {
+ settings({ fileIssue: true });
+ execGh
+ .mockResolvedValueOnce(ghRows([])) // marker search
+ .mockResolvedValueOnce('') // label create
+ .mockResolvedValueOnce('https://github.com/acme/comics/issues/42');
+ const result = await run();
+ expect(result.issue).toEqual({ number: 42, url: 'https://github.com/acme/comics/issues/42', duplicate: false });
+ const createArgs = execGh.mock.calls.at(-1)[0];
+ expect(createArgs.slice(0, 2)).toEqual(['issue', 'create']);
+ expect(createArgs).toContain('--label');
+ expect(createArgs).toContain('goal-fidelity');
+ // The body carries the key the next run's search reads back.
+ expect(createArgs[createArgs.indexOf('--body') + 1]).toContain(MARKER);
+ });
+
+ // The whole feature's point of failure. A closed issue is still a filed
+ // issue — re-filing it is exactly the "same issue over and over" loop.
+ it('reuses an existing issue carrying the marker, even when it is CLOSED', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce(ghRows([
+ { number: 5, title: 'Goal-fidelity rethink: Add retry caps', body: `stuff ${MARKER}`, url: 'u5', state: 'CLOSED' },
+ ]));
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 5, duplicate: true });
+ expect(execGh).toHaveBeenCalledTimes(1); // searched, never created
+ });
+
+ it('searches every state, not just the open ones', async () => {
+ settings({ fileIssue: true });
+ await run();
+ const searchArgs = execGh.mock.calls[0][0];
+ expect(searchArgs[searchArgs.indexOf('--state') + 1]).toBe('all');
+ expect(searchArgs[searchArgs.indexOf('--search') + 1]).toBe(MARKER);
+ });
+
+ // The forge search index trails a creation by minutes; two runs of one
+ // schedule inside that window are ordinary, and without the rescan the
+ // second files a duplicate the search genuinely could not see.
+ it('catches a just-filed issue the search index has not indexed yet', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce(ghRows([])); // search: index lag, no hit
+ listAppIssues.mockResolvedValue({
+ transient: false,
+ issues: [{ number: 6, title: 't', body: `fresh ${MARKER}`, url: 'u6' }],
+ });
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 6, duplicate: true });
+ expect(execGh).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not match another finding's marker", async () => {
+ settings({ fileIssue: true });
+ execGh
+ .mockResolvedValueOnce(ghRows([{ number: 5, title: 't', body: 'portosgf-goal-fidelity-user-other', url: 'u5' }]))
+ .mockResolvedValueOnce('')
+ .mockResolvedValueOnce('https://github.com/acme/comics/issues/43');
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 43, duplicate: false });
+ });
+
+ // Fail-CLOSED, against the usual sentinel convention: a tracker we could not
+ // read is not "nothing is filed". Filing blind is how a `gh` blip duplicates.
+ it('refuses to file when the marker search could not be read', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce('not json');
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toMatch(/could not read/);
+ expect(execGh).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses to file when the open-issue rescan is transient', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce(ghRows([]));
+ listAppIssues.mockResolvedValue({ transient: true, issues: [], reason: 'gh-offline' });
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toMatch(/gh-offline/);
+ expect(execGh).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses to file when the forge is unreachable', async () => {
+ settings({ fileIssue: true });
+ ensureForgeReachable.mockResolvedValue({ ok: false, status: 'offline' });
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toMatch(/could not read/);
+ });
+
+ it('reports a failed create rather than claiming an issue exists', async () => {
+ settings({ fileIssue: true });
+ execGh
+ .mockResolvedValueOnce(ghRows([]))
+ .mockResolvedValueOnce('')
+ .mockRejectedValueOnce(new Error('422 label missing'));
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toContain('422');
+ });
+});
+
+describe('runGoalFidelityFollowUp — GitLab', () => {
+ beforeEach(() => {
+ resolveAppForgeTarget.mockResolvedValue({
+ tracker: 'gitlab',
+ target: { forge: 'gitlab', repoSpec: null, fullName: 'acme/comics' },
+ });
+ });
+
+ it('files through glab when no existing issue carries the marker', async () => {
+ settings({ fileIssue: true });
+ execGlabJson.mockResolvedValue({ rows: [], reason: 'ok' });
+ execGlab.mockResolvedValueOnce('').mockResolvedValueOnce('https://gitlab.com/acme/comics/-/issues/8');
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 8, duplicate: false });
+ });
+
+ // `--all` on `glab issue list` is every STATE, which is what makes a closed
+ // duplicate visible at all.
+ it('reads every state, so a closed issue still dedupes', async () => {
+ settings({ fileIssue: true });
+ execGlabJson.mockResolvedValue({
+ rows: [{ iid: 3, title: 't', description: `x ${MARKER}`, web_url: 'u3', state: 'closed' }],
+ reason: 'ok',
+ });
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 3, duplicate: true });
+ expect(execGlabJson.mock.calls[0][0]).toContain('--all');
+ expect(execGlab).not.toHaveBeenCalled();
+ });
+
+ it('refuses to file when glab could not answer', async () => {
+ settings({ fileIssue: true });
+ execGlabJson.mockResolvedValue({ rows: null, reason: 'cli-failed' });
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toMatch(/could not read/);
+ expect(execGlab).not.toHaveBeenCalled();
+ });
+});
+
+describe('runGoalFidelityFollowUp — JIRA', () => {
+ const JIRA_APP = {
+ id: 'comics', repoPath: '/repo', workTracker: 'jira',
+ jira: { enabled: true, instanceId: 'inst-1', projectKey: 'COM' },
+ };
+
+ beforeEach(() => {
+ getAppById.mockResolvedValue(JIRA_APP);
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'jira', target: null });
+ });
+
+ it("creates a ticket in the app's project", async () => {
+ settings({ fileIssue: true });
+ searchIssues.mockResolvedValue([]);
+ createTicket.mockResolvedValue({ success: true, ticketId: 'COM-12', url: 'https://jira/browse/COM-12' });
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 'COM-12', duplicate: false });
+ expect(createTicket.mock.calls[0][1].projectKey).toBe('COM');
+ expect(createTicket.mock.calls[0][1].description).toContain(MARKER);
+ });
+
+ // JIRA returns the body as `description`, not `body` — a dedup that read only
+ // `body` would treat every existing ticket as a non-match and re-file forever.
+ it('dedupes on the description field JIRA actually returns', async () => {
+ settings({ fileIssue: true });
+ searchIssues.mockResolvedValue([{ key: 'COM-4', summary: 't', description: `x ${MARKER}`, url: 'u' }]);
+ const result = await run();
+ expect(result.issue).toMatchObject({ number: 'COM-4', duplicate: true });
+ expect(createTicket).not.toHaveBeenCalled();
+ });
+
+ it("scopes the marker search to the app's own project", async () => {
+ settings({ fileIssue: true });
+ searchIssues.mockResolvedValue([]);
+ createTicket.mockResolvedValue({ success: true, ticketId: 'COM-13', url: 'u' });
+ await run();
+ expect(searchIssues.mock.calls[0][1]).toContain('project = "COM"');
+ expect(searchIssues.mock.calls[0][1]).toContain(MARKER);
+ });
+
+ it('refuses to file when the JIRA search failed', async () => {
+ settings({ fileIssue: true });
+ searchIssues.mockRejectedValue(new Error('401'));
+ const result = await run();
+ expect(result.issue).toBeNull();
+ expect(result.issueError).toMatch(/could not read the JIRA project/);
+ expect(createTicket).not.toHaveBeenCalled();
+ });
+
+ it('says what is missing when the app tracks JIRA but configured no project', async () => {
+ settings({ fileIssue: true });
+ getAppById.mockResolvedValue({ ...JIRA_APP, jira: { enabled: true, instanceId: 'inst-1' } });
+ const result = await run();
+ expect(result.issueError).toMatch(/not configured/);
+ });
+});
+
+describe('runGoalFidelityFollowUp — unfilable trackers', () => {
+ it('reports rather than throws for a PLAN.md app', async () => {
+ settings({ fileIssue: true });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'plan', target: null });
+ const result = await run();
+ expect(result.ran).toBe(true);
+ expect(result.issueError).toMatch(/plan/);
+ });
+
+ it('refuses when the configured tracker and the remote disagree', async () => {
+ settings({ fileIssue: true });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target: { forge: 'gitlab' } });
+ const result = await run();
+ expect(result.issueError).toMatch(/does not match/);
+ });
+
+ it('reports an app with no repository', async () => {
+ settings({ fileIssue: true });
+ getAppById.mockResolvedValue(null);
+ const result = await run();
+ expect(result.issueError).toMatch(/no configured repository/);
+ });
+
+ // A task with no `metadata.app` is PortOS's own work, which runs against the
+ // install root — the same fallback that picks its workspace.
+ it('falls back to the install root for a task with no app', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce(ghRows([])).mockResolvedValueOnce('').mockResolvedValueOnce('u/1');
+ await runGoalFidelityFollowUp({
+ agentId: 'agent-1', task: { id: 't', taskType: 'user', description: 'Fix it' }, review: REVIEW,
+ });
+ expect(getAppById).not.toHaveBeenCalled();
+ expect(resolveAppForgeTarget.mock.calls[0][0].repoPath).toBe('/portos');
+ });
+});
+
+describe('runGoalFidelityFollowUp — the queued task', () => {
+ it('queues through the shared investigation producer with the shared fingerprint', async () => {
+ settings({ queueTask: true });
+ const result = await run();
+ expect(result.task).toEqual({ id: 'cos-9' });
+ const [args] = fileInvestigationTask.mock.calls[0];
+ expect(args.fingerprint).toBe(FINGERPRINT);
+ expect(args.affectedTasks).toEqual(['task-7']);
+ expect(args.app).toBe('comics');
+ expect(execGh).not.toHaveBeenCalled(); // no issue filing was asked for
+ });
+
+ it('hands the filed issue to the queued task so it can claim it', async () => {
+ settings({ fileIssue: true, queueTask: true });
+ execGh
+ .mockResolvedValueOnce(ghRows([]))
+ .mockResolvedValueOnce('')
+ .mockResolvedValueOnce('https://github.com/acme/comics/issues/42');
+ await run();
+ expect(fileInvestigationTask.mock.calls[0][0].description).toContain('#42');
+ });
+
+ // The task is the arm that actually gets the work done; a tracker that
+ // refused the file must not cancel it.
+ it('still queues the task when the issue could not be filed', async () => {
+ settings({ fileIssue: true, queueTask: true });
+ execGh.mockResolvedValueOnce('not json');
+ const result = await run();
+ expect(result.issueError).toBeTruthy();
+ expect(result.task).toEqual({ id: 'cos-9' });
+ });
+
+ it('reports a suppressed queue rather than silently returning nothing', async () => {
+ settings({ queueTask: true });
+ fileInvestigationTask.mockResolvedValue({ task: null });
+ const result = await run();
+ expect(result.task).toBeNull();
+ expect(result.taskError).toBeTruthy();
+ });
+});