Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
queue a calibration task when a goal-fidelity finding turns out to be wrong
[._.]/ Adam Eivyef2544432239
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex ca5f8c7b22..099042c308 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`) 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. | — |+| **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. That agent checks the finding first: when the objective turns out to have been delivered and the reviewer misjudged it, it reports which context the reviewer was missing instead of shipping a change, and PortOS queues a calibration task against its own repo to close that blind spot — deduped on the gap, so many false positives from one cause fold into one fix. | — |---diff --git a/server/lib/README.md b/server/lib/README.mdindex ac107a0104..dadcf56c3a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -274,7 +274,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `openAiChatStream.js` | `iterateOpenAiChat(...)` → normalized async content/reasoning chunks and `streamOpenAiChat(...)` → the streamed text — one streaming `POST {base}/chat/completions` against any OpenAI-compatible endpoint; both own timeout/abort composition, retries, parsing, backpressure, and reader cleanup. `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by Ask (`services/askService.js`), `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record), and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. || `callerModePolicy.js` | The one caller EXECUTION-MODE policy: `CALLER_MODE_POLICIES` (`agent-harness`, `cli-harness`, `direct-api`, `any-text`) plus `resolveCallerModePolicy` / `allowedModesFor` / `callerModeRejection` / `isCallerModeEligible` / `filterCallerModeEligible`. Answers "may THIS caller run on THAT route mode?" for an explicit pin, `activeProvider` inheritance and every fallback candidate alike — `allowedModesFor()` is what rides on `requestCapabilities.allowedModes` into the toolkit's `getFallbackProvider`. Pure and dependency-light so the out-of-process autofixer can import it; `enabled`/benched state, prerequisites and text-transport consent stay with their existing owners. Unknown never becomes true: a record with no executable mode, and a required model capability with no positive evidence, are both refused. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: filters the inherited base to runtime essentials/provider auth, then layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |-| `agentApiToken.js` | `AGENT_API_TOKEN_ENV` (`PORTOS_API_TOKEN`) + `AGENT_API_AUTH_CURL_ARG` — the name of the loopback session token PortOS injects into a spawned agent's environment (`services/agentApiAuth.js`) and the quoted `curl` argument that spends it, so the prompt builders writing agent-facing `curl` snippets and the spawn sites injecting the variable cannot drift. Pure. |+| `agentApiToken.js` | `AGENT_API_TOKEN_ENV` (`PORTOS_API_TOKEN`) + `AGENT_API_AUTH_CURL_ARG` — the name of the loopback session token PortOS injects into a spawned agent's environment (`services/agentApiAuth.js`) and the quoted `curl` argument that spends it, so the prompt builders writing agent-facing `curl` snippets and the spawn sites injecting the variable cannot drift. `agentApiCurl({ apiBase, path, payload })` and `agentApiAuthNote({ alsoCovering })` assemble the whole call and the paragraph that must travel with it — one shape for every agent-facing API call in the tree, after two hand-written copies had already drifted on whether the install "gates" or "may gate" `/api/*` (it is opt-in and off by default). Pure, zero-import. || `localReviewBridge.js` | `LOCAL_REVIEW_BRIDGE_SCRIPT` — absolute path of `server/scripts/run-local-code-review.mjs`, the stdin bridge into the local-review service (same reviewers and `timeoutMs` forwarding as `POST /api/code-review/local`, no HTTP and so no instance-password gate). Shared by the two prompt builders that hand it to agents, so renaming the script cannot break one while the other keeps working. || `agentExecutionProfiles.js` | Named agent execution postures shared by lifecycle dispatch, CLI/TUI spawners, and child-environment filtering. A stage declares a PROFILE (`PUBLIC_REVIEW_EXECUTION_PROFILE`, `PUBLIC_REVIEW_GATE_EXECUTION_PROFILE`, `PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE`); `publicReviewPostureForProfile` maps it to the enforceable POSTURE a provider must carry a maintained recipe for (`no-tool` or `sandboxed-actions`), which is how a pipeline stage stays vendor-agnostic. || `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |@@ -528,6 +528,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)`. `mergeOutcomeObjective(task)` / `mergeOutcomeReview({ number, prState })` / `GOAL_FIDELITY_SOURCE_FORGE` are the second answer shape: a review-loop follow-up is asked to LAND a change request, which no diff evidences, so its verdict is established from forge state (`MERGED` ⇒ `ship`, everything else ⇒ nothing). `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. |+| `goalFidelityCalibration.js` | Goal-fidelity CALIBRATION contract — what happens when the follow-up investigation overturns a finding, i.e. the objective WAS delivered and the reviewer misjudged it. `GOAL_FIDELITY_CONTEXT_GAPS` is the closed vocabulary of what the reviewer could not see (`truncated-diff`, `truncated-objective`, `objective-omits-context`, `work-outside-diff`, `execution-step-misread`, `rubric-gap`, `other`), enforced ONLY by `normalizeGoalFidelityContextGap` (the report route takes a bounded string, so a near-miss gap name folds to `other` with its diagnosis intact instead of 400ing the report away). `GOAL_FIDELITY_REVIEW_SURFACES` addresses the reviewer's three context surfaces once — objective / diff / rubric — and `GOAL_FIDELITY_CONTEXT_GAP_FIXES` maps each gap onto one of them, so a rename cannot leave seven prose copies lying (`goalFidelityCalibration.pointers.test.js` walks the table against the real files). `goalFidelityCalibrationFingerprint(gap)` keys the dedup on the GAP alone, so many false positives from one blind spot fold into one fix instead of minting an agent each. `buildGoalFidelityCalibrationTask` composes the PortOS-side task body (including the do-not-disarm-the-detector contract) and `buildGoalFidelityFalsePositiveReportBlock` the `curl` instructions appended to a follow-up task, taking `apiBase` as an argument and the call shape from `agentApiToken.js`. I/O lives in `services/goalFidelityCalibration.js`. || `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), `normalizeGoalFidelityFollowUpTrigger` (shared with the settings projection so the form and the runtime cannot disagree), 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 issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`), the tracker listing that reads it back, 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. Closure-free apart from `textUtils.js` (see the header); 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`). |diff --git a/server/lib/agentApiToken.js b/server/lib/agentApiToken.jsindex 3b811e4eab..0a9ebd8fb5 100644--- a/server/lib/agentApiToken.js+++ b/server/lib/agentApiToken.js@@ -24,3 +24,32 @@ export const AGENT_API_TOKEN_ENV = 'PORTOS_API_TOKEN';* one quoted argument, so a token is never word-split.*/export const AGENT_API_AUTH_CURL_ARG = `-H "Authorization: Bearer \${${AGENT_API_TOKEN_ENV}:-}"`;++/**+ * One agent-facing `curl` against this install's own API, with the credential+ * already spent on it.+ *+ * Every prompt that hands an agent an API call needs the same five pieces in+ * the same order, and a call assembled by hand is one `-H` away from a bare+ * `401` the agent reads as a broken endpoint. `payload` is emitted inside+ * single quotes, so it is JSON the caller built — never interpolated shell.+ */+export const agentApiCurl = ({ apiBase, path, payload }) => (+ `curl -sS -X POST ${apiBase}${path} -H 'Content-Type: application/json' ${AGENT_API_AUTH_CURL_ARG}${payload ? ` -d '${payload}'` : ''}`+);++/**+ * The sentence that has to travel with every one of those calls.+ *+ * "MAY gate" is the accurate reading and the one that matters: auth is opt-in+ * and OFF by default (root `AGENTS.md`, Security Model), the `:-` default keeps+ * the command valid either way, and an agent told the install definitely gates+ * `/api/*` draws the wrong conclusion from a 200. What it must not conclude is+ * the reverse — that a `401` means the endpoint is gone.+ *+ * `alsoCovering` names the other calls in the same prompt the header applies+ * to, so a multi-call protocol does not have to restate the whole paragraph.+ */+export const agentApiAuthNote = ({ alsoCovering = '' } = {}) => (+ `Keep that \`Authorization\` header on every PortOS API call you make${alsoCovering ? `, ${alsoCovering}` : ''}: this install may gate \`/api/*\` behind its instance password, and \`$${AGENT_API_TOKEN_ENV}\` is the session token PortOS put in your environment for exactly this. A bare \`401 AUTH_REQUIRED\` means the header was dropped, not that the endpoint is unavailable.`+);diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 8eb9bd0a21..2eaf1c18fa 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -393,6 +393,32 @@ export const resolveChallengeSchema = z.object({{ message: 'Provide exactly one of `outcome` or `recheck`.', path: ['outcome'] },);+// A follow-up investigator reporting that a goal-fidelity finding was WRONG —+// the objective was delivered and the reviewer misjudged it+// (`lib/goalFidelityCalibration.js`).+//+// Every field is a BOUNDED STRING, including `gap`, which is the one field that+// changes behaviour (the queued calibration dedupes on it). Deliberately not the+// `GOAL_FIDELITY_CONTEXT_GAPS` enum: `normalizeGoalFidelityContextGap` is the+// single gate, and it folds an unrecognized gap onto `other` rather than+// dropping the report. Rejecting here instead would throw away the prose+// diagnosis — the expensive part, produced by an agent that investigated a+// finished run — over a near-miss enum value, and would put that module in the+// closure of the 283 suites this file is reached from to re-check what the+// normalizer already checks.+//+// `fingerprint` / `taskId` / `verdict` are provenance the server never trusts as+// identity: the dedup key is derived from the gap, and the verdict is restated+// in the task body as text with nothing branching on it.+export const goalFidelityFalsePositiveSchema = z.object({+ gap: z.string().trim().min(1).max(60),+ detail: z.string().trim().max(5000).optional(),+ evidence: z.string().trim().max(20_000).optional(),+ fingerprint: z.string().trim().max(500).optional(),+ taskId: z.string().trim().max(200).optional(),+ verdict: z.string().trim().max(40).optional(),+});+// =============================================================================// LOOP SCHEMAS// =============================================================================diff --git a/server/lib/goalFidelityCalibration.js b/server/lib/goalFidelityCalibration.jsnew file mode 100644index 0000000000..8179596f8b--- /dev/null+++ b/server/lib/goalFidelityCalibration.js@@ -0,0 +1,331 @@+/**+ * Goal-fidelity CALIBRATION contract — pure.+ *+ * `goalFidelity.js` owns the verdict, `goalFidelityFollowUp.js` owns what+ * happens when the verdict found a problem. This module owns the third case,+ * which until now had nowhere to go: the follow-up investigator looked at the+ * finding, checked it against what actually shipped, and concluded **the goal+ * WAS met — the detector was wrong**.+ *+ * That outcome is not a no-op. A false `rethink` held a successful run, raised+ * a Review Hub alert, possibly filed an issue on the project's tracker, and+ * spent an agent to discover it was nothing. It will keep doing that on every+ * future run with the same shape, because the reason it misjudged is structural+ * — the reviewer sees ONLY the objective and the diff (see+ * `services/codeReview.js#GOAL_FIDELITY_SYSTEM_PROMPT`), so anything the+ * delivery depended on that isn't in those two blocks is invisible to it. The+ * overturned finding is the only evidence that ever names which piece was+ * missing, and discarding it means re-discovering the same blind spot forever.+ *+ * So an overturned finding queues a task against PortOS's OWN repo to close the+ * gap. The existing prompt already carries one such patch, added by hand after+ * exactly this failure ("Claiming/selecting that issue, creating a worktree,+ * and shipping a PR are execution steps; do not require those steps to appear+ * as code in the diff") — this module is that loop, automated.+ *+ * TWO design points carry the feature:+ *+ * 1. The fingerprint is keyed on the GAP, not on the run. Ten false positives+ * from one missing piece of context are ONE fix, and keying on the run+ * would mint ten agents to make it. Keying on the gap folds them into one+ * task that accumulates `affectedTasks` (see `goalFidelityCalibrationFingerprint`).+ * 2. The calibration lands on PORTOS, never on the app the finding was about.+ * The finding belonged to the app; the judge that produced it is PortOS+ * code. Filing the fix where the finding was would put a PortOS prompt+ * change in a managed app's backlog, where nothing can act on it.+ *+ * NEARLY CLOSURE-FREE by design, like its sibling: both imports are zero-import+ * leaves (`textUtils.js`, `agentApiToken.js`). The `curl` block takes its API+ * base as an ARGUMENT rather than importing `networkExposure.js` — resolving a+ * loopback port is I/O, it would drag seven modules (TLS cert metadata,+ * Tailscale state) behind a constant, and it belongs to the service anyway.+ *+ * The vocabulary is enforced HERE and only here: `normalizeGoalFidelityContextGap`+ * is the single gate, and the report route takes a bounded string rather than+ * this enum. Two reasons, and the second is the one that keeps it that way.+ * Behaviour: a report is expensive — an agent investigated a finished run to+ * produce it — so a near-miss gap name folds to `other` with the diagnosis+ * intact instead of 400'ing the whole report away. Cost: `cosValidation.js` is+ * statically reached by 283 of the ~1,920 server suites, so importing this+ * module there to type one field would have added 283 module instantiations to+ * a tree-wide budget (`lib/importScoping.test.js`) for a check the normalizer+ * already performs. See server/AGENTS.md "Import scoping".+ */++import { agentApiAuthNote, agentApiCurl } from './agentApiToken.js';+import { trimTo } from './textUtils.js';++/**+ * What the reviewer was missing, as a closed vocabulary.+ *+ * Closed rather than free text because the vocabulary IS the dedup key: two+ * investigators describing the same blind spot in different prose would file+ * two tasks to make one fix. Each value names a distinct place the context+ * assembly can fail, and every value maps to a different file to edit — which+ * is what makes `GOAL_FIDELITY_CONTEXT_GAP_FIXES` below a usable starting point+ * rather than a restatement of the problem.+ *+ * - `truncated-diff` — the change was larger than `MAX_FIDELITY_DIFF_CHARS`,+ * so the reviewer judged a fragment. The gate already+ * KNOWS this (`review.diffTruncated`); the bug is that+ * it judged anyway instead of declining.+ * - `truncated-objective` — the objective was over `MAX_OBJECTIVE_CHARS` and the+ * requirement the diff delivered fell off the end.+ * - `objective-omits-context` — the objective pointed OUT of itself (an issue body, a+ * linked plan, a prior run's decision) and the reviewer+ * never received the thing it pointed at.+ * - `work-outside-diff` — the delivery was real but invisible in the run-window+ * diff: already on the base branch, in a sibling branch,+ * a generated or git-ignored artifact, or a pure deletion.+ * - `execution-step-misread` — the reviewer demanded process (claim the issue, open a+ * PR, merge) as code in the diff.+ * - `rubric-gap` — the prompt's own rubric misjudged a legitimate shape: a+ * supporting change read as `unrequested`, real verification+ * read as absent, a refactor read as "something else".+ * - `other` — a gap none of the above describes. Files the same task;+ * the investigator's prose carries the diagnosis.+ */+export const GOAL_FIDELITY_CONTEXT_GAPS = Object.freeze([+ 'truncated-diff',+ 'truncated-objective',+ 'objective-omits-context',+ 'work-outside-diff',+ 'execution-step-misread',+ 'rubric-gap',+ 'other',+]);++/** The gap a report gets when it named none, or named one we do not know. */+export const DEFAULT_GOAL_FIDELITY_CONTEXT_GAP = 'other';++/**+ * The reviewer's ENTIRE context, as three surfaces — and where each one lives.+ *+ * Addressed once, here, rather than re-spelled in every gap's advice. These are+ * prose pointers into code, so nothing compiles against them; describing one+ * surface seven times means a rename can leave four copies quietly lying to an+ * unattended agent, in a task whose whole value is "here is the shortest path to+ * the code". `goalFidelityCalibration.pointers.test.js` walks this table and+ * fails when a named file or exported symbol no longer exists.+ */+export const GOAL_FIDELITY_REVIEW_SURFACES = Object.freeze({+ objective: Object.freeze({+ file: 'server/lib/goalFidelity.js',+ symbol: 'taskObjective',+ describe: 'the OBJECTIVE block — `taskObjective()` in `server/lib/goalFidelity.js`, which composes the task\'s own `description` plus `taskContextBlock(task)` (`server/lib/cosTaskPrompt.js`) and nothing else, capped at `MAX_OBJECTIVE_CHARS`',+ }),+ diff: Object.freeze({+ file: 'server/services/agentFinalization.js',+ symbol: 'evaluateGoalFidelity',+ describe: 'the DIFF block — the run-window diff assembled by `evaluateGoalFidelity` in `server/services/agentFinalization.js`, capped at `MAX_FIDELITY_DIFF_CHARS`',+ }),+ rubric: Object.freeze({+ file: 'server/services/codeReview.js',+ symbol: 'GOAL_FIDELITY_SYSTEM_PROMPT',+ describe: 'the RUBRIC it judges them with — `GOAL_FIDELITY_SYSTEM_PROMPT` in `server/services/codeReview.js`',+ }),+});++/**+ * Which surface each gap sits on, and the one thing worth knowing about that+ * gap beyond the address.+ *+ * `surface: null` means all three — the `other` case, where the report's prose+ * is the only thing that narrows it.+ */+export const GOAL_FIDELITY_CONTEXT_GAP_FIXES = Object.freeze({+ 'truncated-diff': Object.freeze({+ surface: 'diff',+ note: 'The gate already KNOWS the diff was truncated (`runLocalGoalFidelityReview` refuses over the cap, and `review.diffTruncated` marks a partial one) — so the question is whether a truncated diff may produce a run-HOLDING verdict at all, or only an advisory one.',+ }),+ 'truncated-objective': Object.freeze({+ surface: 'objective',+ note: 'Either the cap is wrong for this install\'s objectives, or the truncation drops the requirement-bearing part — prefer preserving the requirements over trailing prose to raising a fixed cap.',+ }),+ 'objective-omits-context': Object.freeze({+ surface: 'objective',+ note: 'The objective referenced something the task carries elsewhere (an issue body, metadata, a linked plan). That is what has to be folded into the objective block — trusted, and still bounded.',+ }),+ 'work-outside-diff': Object.freeze({+ surface: 'diff',+ note: 'Either the window missed real work (wrong base, wrong branch, excluded path) or the delivery genuinely is not a diff — in which case the gate needs to be able to say "not judgeable from a diff" instead of `rethink`.',+ }),+ 'execution-step-misread': Object.freeze({+ surface: 'rubric',+ note: 'The rubric already carves out claim-flow execution steps. Extend that carve-out to the shape that was misread — narrowly, naming it, not by weakening the rubric.',+ }),+ 'rubric-gap': Object.freeze({+ surface: 'rubric',+ note: 'The rubric defines what counts as missing, unrequested, and verified. Fix the specific misreading and pin it with a regression case.',+ }),+ other: Object.freeze({+ surface: null,+ note: 'None of the known gaps fit, so start from the whole context surface and let the diagnosis below narrow it.',+ }),+});++/** One gap's advice: where to look, then what to know. */+export const describeGoalFidelityContextGap = (gap) => {+ const { surface, note } = GOAL_FIDELITY_CONTEXT_GAP_FIXES[normalizeGoalFidelityContextGap(gap)];+ const where = surface+ ? `Look at ${GOAL_FIDELITY_REVIEW_SURFACES[surface].describe}.`+ : `Look at all three: ${Object.values(GOAL_FIDELITY_REVIEW_SURFACES).map(s => s.describe).join('; ')}.`;+ return `${where} ${note}`;+};++/** One reported gap, validated. Anything unknown becomes `other` rather than being dropped. */+export function normalizeGoalFidelityContextGap(value) {+ return GOAL_FIDELITY_CONTEXT_GAPS.includes(value) ? value : DEFAULT_GOAL_FIDELITY_CONTEXT_GAP;+}++/** `category` / `kind` segments of the shared `category:kind:scope` fingerprint. */+const CALIBRATION_CATEGORY = 'goal-fidelity-calibration';+const CALIBRATION_KIND = 'context-gap';++/**+ * Bound on the investigator's free text, which rides into a queued task body.+ *+ * This is the EFFECTIVE limit, and deliberately below the report schema's own+ * caps: a report is expensive to produce (an agent investigated a finished run),+ * so an over-long field is trimmed here rather than 400'd away with the+ * diagnosis still inside it.+ */+export const GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS = 4_000;++/**+ * The dedup key for one calibration, keyed on the GAP ALONE.+ *+ * This is the design decision that makes the loop affordable. A false positive+ * is not an incident, it is a symptom of one structural blind spot, and that+ * blind spot fires on every run with the same shape — a scheduled task drifting+ * the same way produces one overturned finding per cadence. Keyed on the run+ * (or on the overturned finding's own fingerprint, which is keyed on the task)+ * every one of those would mint its own agent to make the SAME edit to the same+ * prompt, and the second one would land on a tree the first already changed.+ *+ * Keyed on the gap they all fold into one task, and `fileInvestigationTask`'s+ * dedup unions the later reports' `affectedTasks` into it — so the agent that+ * picks it up sees every run the gap cost, which is the evidence that tells it+ * how far to go.+ *+ * Nothing about the app is in the key on purpose: the judge is one piece of+ * PortOS code shared by every app, so two apps hitting the same blind spot are+ * one fix, not two. The three-segment `category:kind:scope` shape matches every+ * other investigation key so the queued task participates in the shared loop+ * policy and circuit breaker for free.+ */+export function goalFidelityCalibrationFingerprint(gap) {+ return `${CALIBRATION_CATEGORY}:${CALIBRATION_KIND}:${normalizeGoalFidelityContextGap(gap)}`;+}++/** Bounded free text, or a stated absence — never a silent empty section. */+const reported = (text, empty) => {+ const trimmed = typeof text === 'string' ? text.trim() : '';+ return trimmed ? trimTo(trimmed, GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS) : empty;+};++/**+ * The CoS task body for one calibration.+ *+ * Written for an agent that has never seen the overturned finding, because it+ * has not: this task is queued from a REPORT, runs later, and may fold in+ * reports from runs that finished days apart. So it restates the diagnosis, and+ * it names the reviewer's whole context surface rather than assuming the agent+ * will find it.+ *+ * The scope contract is the load-bearing paragraph. The cheapest way to make a+ * false positive stop is to make the detector never say `rethink` again, and an+ * unattended agent optimizing for "this finding must not recur" will find that+ * path. So the task states the failure mode it must not produce and asks for+ * the regression test that proves it did not.+ */+export function buildGoalFidelityCalibrationTask({ gap, detail, evidence, findingFingerprint, taskId, verdict } = {}) {+ const resolved = normalizeGoalFidelityContextGap(gap);+ const header = `[Auto] Goal-fidelity calibration (${resolved}): the reviewer judged a delivered objective as not delivered`;+ return [+ header,+ [+ '## What happened',+ `A goal-fidelity review returned **${verdict || 'a finding'}** on a finished agent run${taskId ? ` (task \`${taskId}\`)` : ''}, and the follow-up investigation overturned it: the objective WAS delivered. The run was held, and an agent was spent, for a judgement the evidence does not support.`,+ findingFingerprint ? `The overturned finding's own key was \`${findingFingerprint}\`.` : null,+ ].filter(Boolean).join('\n'),+ `## What the reviewer was missing\n**${resolved}** — ${describeGoalFidelityContextGap(resolved)}`,+ `## The investigator's diagnosis\n${reported(detail, '_The report named no detail beyond the gap._')}`,+ `## Evidence the objective was delivered\n${reported(evidence, '_The report cited no specific evidence._')}`,+ [+ '## The reviewer\'s entire context',+ 'The goal-fidelity reviewer is a tool-free local model handed exactly two blocks and nothing else — no repository, no file list, no PR, no history. Anything a delivery depended on that is not in those two blocks is invisible to it:',+ '',+ // Rendered from the surface table rather than restated, so the addresses+ // here and the one the gap above points at cannot disagree — and so the+ // pointers test, which walks that table against the real files, covers+ // this list too.+ ...Object.values(GOAL_FIDELITY_REVIEW_SURFACES).map(surface => `- ${surface.describe};`),+ ].join('\n'),+ [+ '## What to do',+ 'Close the named gap so a run of this shape is judged correctly, then prove it. The fix belongs in whichever of the three surfaces above actually produced the misjudgement — do not fix a context gap by editing the rubric, or a rubric gap by widening a cap.',+ '',+ '**Do not disarm the detector.** The cheap way to stop this false positive is to make the reviewer stop returning `rethink`, and that would silently give every future run a free pass — the exact failure the gate exists to catch (`server/lib/goalFidelity.js` opens with it). A change that broadens what counts as `ship`, weakens a hold, or removes a check is only acceptable when it names the shape it exempts, and it must exempt that shape and nothing wider.',+ '',+ '**Ship a regression test** that reconstructs this case and asserts the corrected judgement — a prompt/rubric change with no test pinning it is one rebase away from being reverted by the next person who reads it as noise.',+ ].join('\n'),+ ].join('\n\n');+}++/**+ * The path the prompt tells an agent to POST to — absolute, since the agent+ * types it into a `curl`.+ *+ * The route declares its own path relative to the `/api/cos` mount, so the two+ * cannot be one literal. They are pinned from both ends instead: the block test+ * asserts this string appears in the rendered `curl`, and the route test POSTs+ * to it — a rename that moves one without the other fails the second.+ */+export const GOAL_FIDELITY_FALSE_POSITIVE_PATH = '/api/cos/goal-fidelity/false-positive';++/**+ * The block appended to a follow-up task telling the investigator how to report+ * an overturned finding.+ *+ * Lives here, beside the vocabulary it names, so the enum an agent is told to+ * pick from and the enum the server normalizes against cannot drift apart.+ *+ * `apiBase` is an ARGUMENT because resolving the loopback base is I/O+ * (`localApiBaseUrl`), which belongs to the caller; the `curl` line and the+ * auth paragraph come from `agentApiToken.js`, which owns that shape for every+ * agent-facing API call in the tree.+ */+export function buildGoalFidelityFalsePositiveReportBlock({ apiBase, findingFingerprint, taskId } = {}) {+ const payload = JSON.stringify({+ gap: `<one of: ${GOAL_FIDELITY_CONTEXT_GAPS.join(' | ')}>`,+ detail: '<what the reviewer could not see, in one or two sentences>',+ evidence: '<file:line, commit, or PR that shows the objective WAS delivered>',+ ...(findingFingerprint ? { fingerprint: findingFingerprint } : {}),+ ...(taskId ? { taskId } : {}),+ });+ return [+ '## First: is the finding actually right?',+ 'Check the objective against what shipped BEFORE changing anything. A goal-fidelity verdict is one local model\'s reading of a diff it saw without the repository, and it is wrong often enough that "reconcile it" is the wrong first move. If the objective was in fact delivered, do NOT ship a reconciliation — there is nothing to reconcile, and a change made to satisfy a false finding is a regression.',+ '',+ 'Report the overturned finding instead, so the blind spot that produced it gets fixed rather than re-encountered:',+ '',+ '```bash',+ agentApiCurl({ apiBase, path: GOAL_FIDELITY_FALSE_POSITIVE_PATH, payload }),+ '```',+ '',+ agentApiAuthNote(),+ '',+ '`gap` is what the REVIEWER could not see, not what you did about it — it is what the queued calibration is keyed on, so pick the one that names the missing context. Reports sharing a gap fold into one calibration task. Then finish: say in your summary that the finding was overturned and that you reported it, and ship nothing else.',+ ].join('\n');+}++/** One-line human summary of a calibration report, for a log line. */+export function formatGoalFidelityCalibrationSummary(result) {+ if (!result?.queued) {+ return `Goal-fidelity calibration not queued${result?.reason ? ` (${result.reason})` : ''}`;+ }+ const state = result.duplicate ? 'folded into' : result.approvalRequired ? 'queued for approval as' : 'queued as';+ return `Goal-fidelity calibration (${result.gap}) ${state} ${result.taskId}`;+}+diff --git a/server/lib/goalFidelityCalibration.pointers.test.js b/server/lib/goalFidelityCalibration.pointers.test.jsnew file mode 100644index 0000000000..a145f5df16--- /dev/null+++ b/server/lib/goalFidelityCalibration.pointers.test.js@@ -0,0 +1,64 @@+/**+ * The calibration task's code pointers, checked against the code.+ *+ * `GOAL_FIDELITY_REVIEW_SURFACES` addresses the three places the goal-fidelity+ * reviewer's context is assembled, and every calibration task is handed one of+ * those addresses as its starting point. They are PROSE — nothing compiles+ * against them — so a rename of `evaluateGoalFidelity`, a move of+ * `GOAL_FIDELITY_SYSTEM_PROMPT` out of `codeReview.js`, or a file split leaves+ * the table silently pointing at nothing, in a task whose whole value+ * proposition is "here is the shortest path to the code" and whose reader is an+ * unattended agent that will act on it.+ *+ * Split into its own file rather than folded into `goalFidelityCalibration.test.js`+ * because it reads source off disk: the contract suite stays pure and fast, and+ * this one pays the I/O.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ GOAL_FIDELITY_CONTEXT_GAPS,+ GOAL_FIDELITY_CONTEXT_GAP_FIXES,+ GOAL_FIDELITY_REVIEW_SURFACES,+ describeGoalFidelityContextGap,+} from './goalFidelityCalibration.js';++const REPO_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));+const surfaces = Object.entries(GOAL_FIDELITY_REVIEW_SURFACES);++describe('the review-surface pointers', () => {+ it.each(surfaces)('%s names a file that exists and a symbol it still declares', (_name, surface) => {+ const source = readFileSync(join(REPO_ROOT, surface.file), 'utf8');+ // Declaration, not mention: a pointer that only matches because the symbol+ // appears in a comment or an import would survive the move it exists to catch.+ expect(source).toMatch(new RegExp(`(export\\s+(async\\s+)?(function|const)|^(async\\s+)?function|^const)\\s+${surface.symbol}\\b`, 'm'));+ });++ it.each(surfaces)('%s describes itself using the file and symbol it names', (_name, surface) => {+ expect(surface.describe).toContain(surface.file);+ expect(surface.describe).toContain(surface.symbol);+ });++ it('routes every gap onto a real surface, or onto all three', () => {+ for (const gap of GOAL_FIDELITY_CONTEXT_GAPS) {+ const { surface, note } = GOAL_FIDELITY_CONTEXT_GAP_FIXES[gap];+ expect(note, `${gap} has no note`).toBeTruthy();+ if (surface !== null) expect(GOAL_FIDELITY_REVIEW_SURFACES, `${gap} names an unknown surface`).toHaveProperty(surface);+ }+ });++ it('hands every gap an address and a reason, not one or the other', () => {+ for (const gap of GOAL_FIDELITY_CONTEXT_GAPS) {+ const advice = describeGoalFidelityContextGap(gap);+ const { surface, note } = GOAL_FIDELITY_CONTEXT_GAP_FIXES[gap];+ expect(advice).toContain(note);+ // `other` is the all-three case, which is why the assertion is on the set+ // of surfaces the gap maps to rather than on one file name.+ const named = surface ? [GOAL_FIDELITY_REVIEW_SURFACES[surface]] : Object.values(GOAL_FIDELITY_REVIEW_SURFACES);+ for (const entry of named) expect(advice, `${gap} omits ${entry.file}`).toContain(entry.file);+ }+ });+});diff --git a/server/lib/goalFidelityCalibration.test.js b/server/lib/goalFidelityCalibration.test.jsnew file mode 100644index 0000000000..3d0da21ecc--- /dev/null+++ b/server/lib/goalFidelityCalibration.test.js@@ -0,0 +1,197 @@+/**+ * The goal-fidelity calibration contract.+ *+ * Two properties carry the feature, and neither is visible from the service's+ * behaviour on one report:+ *+ * - the fingerprint is keyed on the GAP ALONE, so N false positives from one+ * blind spot fold into ONE fix rather than minting an agent each. Keying it+ * on the run (or on the overturned finding, which is keyed on the task) is+ * the regression, and it looks correct from a single report;+ * - the calibration task must not read as permission to disarm the detector.+ * The cheapest way to stop a false positive recurring is to stop the gate+ * holding runs, an unattended agent will find that path, and the only thing+ * standing between it and a silently-disabled gate is prose in this body.+ *+ * The report block is pinned against the vocabulary rather than against a+ * transcript: the gaps an agent is told to choose from and the gaps the server+ * dedupes on are the same list, and a drift between them silently files every+ * report under `other` — one undifferentiated task for every blind spot.+ */++import { describe, it, expect } from 'vitest';+import {+ DEFAULT_GOAL_FIDELITY_CONTEXT_GAP,+ GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS,+ GOAL_FIDELITY_CONTEXT_GAPS,+ GOAL_FIDELITY_REVIEW_SURFACES,+ buildGoalFidelityCalibrationTask,+ buildGoalFidelityFalsePositiveReportBlock,+ describeGoalFidelityContextGap,+ formatGoalFidelityCalibrationSummary,+ goalFidelityCalibrationFingerprint,+ normalizeGoalFidelityContextGap,+} from './goalFidelityCalibration.js';+import { investigationFingerprint } from './investigationTasks.js';++describe('the context-gap vocabulary', () => {+ it('routes every gap to a named file, so a calibration never says only "context was missing"', () => {+ for (const gap of GOAL_FIDELITY_CONTEXT_GAPS) {+ // A pointer that names no source file sends the next agent back to+ // re-deriving the architecture, which is the cost this table exists to+ // remove. `goalFidelityCalibration.pointers.test.js` checks those paths+ // against the real files; here it is only that every gap gets one.+ expect(describeGoalFidelityContextGap(gap), `${gap}'s advice names no file`)+ .toMatch(/server\/(lib|services)\/[\w/]+\.js/);+ }+ });++ it('normalizes an unrecognized gap to `other` instead of dropping the report', () => {+ // A report with a bad enum still carries a real diagnosis in its prose; the+ // gap only decides which task it folds into.+ expect(normalizeGoalFidelityContextGap('the-model-was-confused')).toBe(DEFAULT_GOAL_FIDELITY_CONTEXT_GAP);+ expect(normalizeGoalFidelityContextGap(undefined)).toBe(DEFAULT_GOAL_FIDELITY_CONTEXT_GAP);+ expect(normalizeGoalFidelityContextGap('rubric-gap')).toBe('rubric-gap');+ });+});++describe('goalFidelityCalibrationFingerprint', () => {+ it('keeps distinct gaps distinct — they are different fixes in different files', () => {+ const keys = new Set(GOAL_FIDELITY_CONTEXT_GAPS.map(goalFidelityCalibrationFingerprint));+ expect(keys.size).toBe(GOAL_FIDELITY_CONTEXT_GAPS.length);+ });++ // The whole affordability argument, and the regression this pins: a scheduled+ // task drifting the same way produces one overturned finding per cadence, and+ // each must fold into the single fix rather than queue its own agent. The+ // literal fails the moment anything run-specific — a task id, an app, a+ // timestamp — enters the key.+ it('carries the gap and nothing else, so every report of one blind spot folds into one fix', () => {+ expect(goalFidelityCalibrationFingerprint('truncated-diff'))+ .toBe('goal-fidelity-calibration:context-gap:truncated-diff');+ });++ // The module inlines the `category:kind:scope` template rather than importing+ // `investigationTasks.js`, which would drag its closure into every consumer —+ // the same trade `goalFidelityFollowUp.js` makes, pinned the same way. The+ // test pays the import so production does not, and the two cannot drift.+ it('builds the same key the shared investigation formatter would', () => {+ expect(goalFidelityCalibrationFingerprint('rubric-gap')).toBe(investigationFingerprint({+ category: 'goal-fidelity-calibration', kind: 'context-gap', scope: 'rubric-gap',+ }));+ });+});++describe('buildGoalFidelityCalibrationTask', () => {+ const build = (over = {}) => buildGoalFidelityCalibrationTask({+ gap: 'objective-omits-context',+ detail: 'The objective referenced issue #41; the reviewer never received its body.',+ evidence: 'server/lib/retry.js:88 implements the cap the issue asked for.',+ findingFingerprint: 'goal-fidelity:user:comics/add-retry-caps',+ taskId: 'task-7',+ verdict: 'rethink',+ ...over,+ });++ it('states the gap, its fix pointer, and the investigator\'s own diagnosis', () => {+ const body = build();+ expect(body).toContain('objective-omits-context');+ expect(body).toContain(describeGoalFidelityContextGap('objective-omits-context'));+ expect(body).toContain('the reviewer never received its body');+ expect(body).toContain('server/lib/retry.js:88');+ expect(body).toContain('task-7');+ expect(body).toContain('goal-fidelity:user:comics/add-retry-caps');+ });++ it('forbids the cheap fix — weakening the gate — and demands a regression test', () => {+ // Without this the task is an unattended instruction to make a `rethink`+ // stop happening, and the shortest path to that is a detector that never+ // returns one again.+ const body = build();+ expect(body).toMatch(/do not disarm the detector/i);+ expect(body).toMatch(/regression test/i);+ });++ it('names the reviewer\'s whole context surface, which the agent cannot discover from the diff', () => {+ // Rendered from the surface table, so this is also what keeps the body's+ // addresses and the gap's own pointer from disagreeing.+ const body = build();+ for (const surface of Object.values(GOAL_FIDELITY_REVIEW_SURFACES)) {+ expect(body, `the body omits ${surface.symbol}`).toContain(surface.symbol);+ expect(body, `the body omits ${surface.file}`).toContain(surface.file);+ }+ });++ it('states an absent detail or evidence rather than leaving a blank section', () => {+ const body = build({ detail: ' ', evidence: undefined });+ expect(body).toContain('_The report named no detail beyond the gap._');+ expect(body).toContain('_The report cited no specific evidence._');+ });++ it('bounds model-authored free text before it lands in a task body', () => {+ const body = build({ detail: 'x'.repeat(GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS + 500) });+ expect(body).not.toContain('x'.repeat(GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS + 1));+ });++ it('normalizes an unknown gap in the body too, so the prose and the dedup key agree', () => {+ const body = build({ gap: 'nonsense' });+ expect(body).toContain(describeGoalFidelityContextGap(DEFAULT_GOAL_FIDELITY_CONTEXT_GAP));+ });++ it('still produces a usable task when the report named no run', () => {+ const body = buildGoalFidelityCalibrationTask({ gap: 'rubric-gap' });+ expect(body.startsWith('[Auto] Goal-fidelity calibration (rubric-gap)')).toBe(true);+ expect(body).toContain('## What to do');+ });+});++describe('buildGoalFidelityFalsePositiveReportBlock', () => {+ const block = buildGoalFidelityFalsePositiveReportBlock({+ apiBase: 'http://127.0.0.1:5553',+ findingFingerprint: 'goal-fidelity:user:comics/add-retry-caps',+ taskId: 'task-7',+ });++ it('tells the investigator to check the finding before reconciling it', () => {+ expect(block).toMatch(/is the finding actually right/i);+ expect(block).toMatch(/do NOT ship a reconciliation/);+ });++ it('offers every gap the server can key a calibration on', () => {+ // The drift this catches: a vocabulary change on one side only, after which+ // the prompt keeps offering a value that now folds onto `other` — so two+ // distinct blind spots share one task and neither gets its own fix.+ for (const gap of GOAL_FIDELITY_CONTEXT_GAPS) expect(block).toContain(gap);+ });++ it('targets the report endpoint and keeps the auth argument the install needs', () => {+ expect(block).toContain('http://127.0.0.1:5553/api/cos/goal-fidelity/false-positive');+ expect(block).toContain('Authorization: Bearer ${PORTOS_API_TOKEN:-}');+ });++ it('carries the run\'s provenance so a report can be traced back to its finding', () => {+ expect(block).toContain('goal-fidelity:user:comics/add-retry-caps');+ expect(block).toContain('task-7');+ });++ it('omits provenance keys it was not given rather than sending empty ones', () => {+ const bare = buildGoalFidelityFalsePositiveReportBlock({ apiBase: 'http://127.0.0.1:5553' });+ expect(bare).not.toContain('"fingerprint"');+ expect(bare).not.toContain('"taskId"');+ });+});++describe('formatGoalFidelityCalibrationSummary', () => {+ it('distinguishes queued, folded, held-for-approval, and refused', () => {+ expect(formatGoalFidelityCalibrationSummary({ queued: true, gap: 'rubric-gap', taskId: 't1' }))+ .toBe('Goal-fidelity calibration (rubric-gap) queued as t1');+ expect(formatGoalFidelityCalibrationSummary({ queued: true, gap: 'rubric-gap', taskId: 't1', duplicate: true }))+ .toContain('folded into');+ // A held task is not a queued one — saying "queued" about a task nothing+ // will pick up is the one wrong thing to report.+ expect(formatGoalFidelityCalibrationSummary({ queued: true, gap: 'rubric-gap', taskId: 't1', approvalRequired: true }))+ .toContain('queued for approval as');+ expect(formatGoalFidelityCalibrationSummary({ queued: false, reason: 'the gate is disabled' }))+ .toBe('Goal-fidelity calibration not queued (the gate is disabled)');+ });+});diff --git a/server/lib/goalFidelityFollowUp.js b/server/lib/goalFidelityFollowUp.jsindex 52f57050b3..0d3df879bf 100644--- a/server/lib/goalFidelityFollowUp.js+++ b/server/lib/goalFidelityFollowUp.js@@ -242,20 +242,31 @@ export function buildGoalFidelityIssue({ task, review, fingerprint }) {* 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.+ *+ * `falsePositiveBlock` is the THIRD job, and it comes first in the body because+ * it has to happen first: the finding may be wrong. A verdict is one local+ * model's reading of a diff it saw without the repository, and an agent told+ * only to "reconcile" will reconcile — inventing a change to satisfy a finding+ * that had nothing behind it. The block (built by+ * `lib/goalFidelityCalibration.js`, rendered by the service that knows this+ * install's API base) tells the investigator to check first and, when the+ * objective WAS delivered, to report the blind spot instead of shipping.+ * Optional so a caller with no API base to offer still produces a valid task.*/-export function buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue = null }) {+export function buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue = null, falsePositiveBlock = 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.`;+ ? `## If the finding is right\nClaim ${issue.number ? `#${issue.number}` : 'the filed issue'} (${issue.url}) and ship the reconciliation through the project's normal claim flow.`+ : `## If the finding is right\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._')}`,+ falsePositiveBlock,claim,- ].join('\n\n');+ ].filter(Boolean).join('\n\n');}/** One-line human summary of what the follow-up actually did, for a log line. */diff --git a/server/lib/goalFidelityFollowUp.test.js b/server/lib/goalFidelityFollowUp.test.jsindex 2e2fd23470..c8a42db7d1 100644--- a/server/lib/goalFidelityFollowUp.test.js+++ b/server/lib/goalFidelityFollowUp.test.js@@ -263,6 +263,26 @@ describe('buildGoalFidelityFollowUpTask', () => {const body = buildGoalFidelityFollowUpTask({ task, review: review(), fingerprint });expect(body.split('\n')[0]).toContain(fingerprint);});++ // The finding may be wrong — it is one local model's reading of a diff it saw+ // without the repository. An agent told only to reconcile will reconcile,+ // inventing a change to satisfy a finding with nothing behind it, so the+ // check-first instructions have to reach it BEFORE the reconcile instructions.+ it('puts the check-the-finding block ahead of the reconcile instructions', () => {+ const body = buildGoalFidelityFollowUpTask({+ task, review: review(), fingerprint, falsePositiveBlock: '## First: is the finding actually right?\nCheck it.',+ });+ expect(body.indexOf('## First: is the finding actually right?'))+ .toBeLessThan(body.indexOf('## If the finding is right'));+ });++ it('still produces a valid task when no report block was supplied', () => {+ // The block needs an API base the pure builder cannot resolve; a caller+ // without one must still get a task, not a body with a hole in it.+ const body = buildGoalFidelityFollowUpTask({ task, review: review(), fingerprint });+ expect(body).toContain('## If the finding is right');+ expect(body).not.toContain('\n\n\n');+ });});describe('formatGoalFidelityFollowUpSummary', () => {diff --git a/server/lib/index.js b/server/lib/index.jsindex 6e11a01f25..01bb2cf55d 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 './goalFidelityCalibration.js';export * from './goalFidelityFollowUp.js';export * from './interactiveShellResolver.js';export * from './killWithEscalation.js';diff --git a/server/lib/investigationTasks.js b/server/lib/investigationTasks.jsindex c0bd3bdd0a..a65281294d 100644--- a/server/lib/investigationTasks.js+++ b/server/lib/investigationTasks.js@@ -32,13 +32,16 @@ export const INVESTIGATION_TASK_DELIVERY = Object.freeze({prCompletion: PR_COMPLETIONS.MERGE_ON_GREEN,});-// Delivery for an investigation a USER queued from the UI (#6043) — the-// installer-failure "Queue agent to investigate" button today. Same isolation as-// the unattended posture above, but the PR waits for a review instead of merging-// on green: `merge-on-green` exists because an auto-filed investigation has-// nobody watching it, and that reason is gone the moment a human clicked the-// button. They are here to look at the fix, so let them.-export const CLIENT_INVESTIGATION_DELIVERY = Object.freeze({+// The SUPERVISED posture: same isolation as the unattended one above, but the PR+// waits for a review instead of merging on green. `merge-on-green` exists+// because an auto-filed investigation has nobody watching it, so this is the+// posture for every investigation where somebody WILL look — whoever they are,+// and for whatever reason.+//+// One literal rather than one per caller. The reason a caller picks supervision+// is call-site knowledge and belongs in a comment there; the VALUE is a policy,+// and two copies of it drift the moment the posture gains a field.+export const SUPERVISED_INVESTIGATION_DELIVERY = Object.freeze({// Verification may establish that the reported finding is already resolved.noChangeSuccess: true,useWorktree: true,@@ -46,6 +49,11 @@ export const CLIENT_INVESTIGATION_DELIVERY = Object.freeze({prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,});+// The supervised posture under the name its first caller knows it by (#6043) —+// an investigation a USER queued from the UI, the installer-failure "Queue agent+// to investigate" button today. They clicked it; they are here to look at the fix.+export const CLIENT_INVESTIGATION_DELIVERY = SUPERVISED_INVESTIGATION_DELIVERY;+// `kind` segment reserved for client-queued investigations. Auto-filed keys take// their kind from an analysis/self-improvement/task type, so this value keeps the// two populations in separate fingerprint namespaces: a client can neither@@ -130,6 +138,43 @@ export function investigationFingerprint({ category, kind, scope } = {}) {return `${category || 'unknown'}:${kind || 'task'}:${scope || 'none'}`;}+/**+ * One reading of what `fileInvestigationTask` just did, in the shape a caller+ * reports to a user.+ *+ * Every caller makes the same three judgements about that return, and two of+ * them are easy to get subtly wrong in a way nothing fails on: a task the loop+ * policy HELD is not a queued one, and a duplicate FOLD is a usable outcome+ * rather than a failure. Re-deriving them per caller is how one copy keeps a+ * `=== true` coercion the next one loses, and how a deliberate suppression gets+ * reported as "could not be queued" — the least actionable thing that can be+ * said about it.+ *+ * Pure, and HERE rather than beside the producer, so a suite that doubles the+ * filing side still reads the real interpretation of what its double returned.+ *+ * `subject` names the thing in the refusal sentence ("the calibration task was+ * suppressed (…)"), which is the only genuinely per-caller part.+ */+export function investigationOutcome(filed, { subject = 'the investigation task' } = {}) {+ if (!filed?.task) {+ return {+ queued: false,+ loopReason: filed?.loopReason || null,+ reason: filed?.loopReason+ ? `${subject} was suppressed (${filed.loopReason})`+ : `${subject} could not be queued`,+ };+ }+ return {+ queued: true,+ taskId: filed.task.id,+ approvalRequired: filed.approvalRequired === true,+ duplicate: filed.task.duplicate === true,+ loopReason: filed.loopReason || null,+ };+}+// ===== Approval policy (#3714) =====/**diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 4eb395f436..ef2de93e08 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -19,6 +19,7 @@ import { NON_PM2_TYPES } from '../services/streamingDetect.js';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { recordUserAction } from '../services/userActions.js';import { fileInvestigationTask } from '../services/investigationTaskProducer.js';+import { reportGoalFidelityFalsePositive } from '../services/goalFidelityCalibration.js';import { CLIENT_INVESTIGATION_DELIVERY, clientInvestigationFingerprint } from '../lib/investigationTasks.js';import {createCosTaskSchema,@@ -26,6 +27,7 @@ import {updateCosTaskSchema,challengeTaskSchema,resolveChallengeSchema,+ goalFidelityFalsePositiveSchema,validateRequest,isPaginationRequested,parsePagination,@@ -604,6 +606,19 @@ router.post('/tasks/:id/challenge/resolve', asyncHandler(async (req, res) => {res.json(result);}));+// POST /api/cos/goal-fidelity/false-positive - A follow-up investigator reports that+// a goal-fidelity finding was WRONG: the objective was delivered and the reviewer+// misjudged it. Queues a calibration task against PortOS's own repo to close the+// context gap that produced the misjudgement, deduped on the gap so many reports+// of one blind spot fold into one fix. Never 4xx on a report it cannot act on —+// the refusal reason rides in the body, because the reporting agent's job is to+// say what it found, not to retry a queue decision it does not own.+router.post('/goal-fidelity/false-positive', asyncHandler(async (req, res) => {+ const report = validateRequest(goalFidelityFalsePositiveSchema, req.body);+ const result = await reportGoalFidelityFalsePositive(report);+ res.json(result);+}));+// POST /api/cos/evaluate - Force task evaluationrouter.post('/evaluate', asyncHandler(async (req, res) => {await cos.evaluateTasks();diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex cb304785c8..54b184ef93 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -67,6 +67,7 @@ vi.mock('../services/apps.js', () => ({ getAppById: vi.fn(), getAppWorkTracker:vi.mock('../services/streamingDetect.js', () => ({ NON_PM2_TYPES: new Set() }));vi.mock('../services/instances.js', () => ({ getAssignableInstances: vi.fn() }));vi.mock('../services/managedAppRepositories.js', () => ({ resolveManagedAppIssueTarget: vi.fn() }));+vi.mock('../services/goalFidelityCalibration.js', () => ({ reportGoalFidelityFalsePositive: vi.fn() }));import * as cos from '../services/cos.js';import { getAssignableInstances } from '../services/instances.js';@@ -76,6 +77,7 @@ import cosTaskRoutes from './cosTaskRoutes.js';import { listUserActions } from '../services/userActions.js';import { __resetInvestigationCircuit } from '../services/investigationTaskProducer.js';import { clientInvestigationFingerprint } from '../lib/investigationTasks.js';+import { reportGoalFidelityFalsePositive } from '../services/goalFidelityCalibration.js';const SELF = 'self-instance-id';const PEER = 'peer-instance-id';@@ -512,3 +514,49 @@ describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () =expect(res.body.user.grouped.pending.map((t) => t.id)).toEqual(['user/42', 'user/43']);});});++// The agent-facing half of the calibration loop (`lib/goalFidelityCalibration.js`).+// A follow-up investigator that overturned a fidelity finding POSTs here; the+// route's whole job is to keep the gap vocabulary honest and to never turn a+// queue decision into an error the reporting agent would try to recover from.+describe('POST /api/cos/goal-fidelity/false-positive', () => {+ const post = (body) => request(buildApp()).post('/api/cos/goal-fidelity/false-positive').send(body);++ it('passes a well-formed report through and answers with what was queued', async () => {+ reportGoalFidelityFalsePositive.mockResolvedValue({ queued: true, gap: 'rubric-gap', taskId: 'calib-1' });+ const res = await post({ gap: 'rubric-gap', detail: 'A supporting change read as unrequested.', taskId: 'task-7' });+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ queued: true, taskId: 'calib-1' });+ expect(reportGoalFidelityFalsePositive).toHaveBeenCalledWith(+ expect.objectContaining({ gap: 'rubric-gap', taskId: 'task-7' }),+ );+ });++ // The gap is a BOUNDED STRING here, not the enum: a report costs an agent an+ // investigation, and `normalizeGoalFidelityContextGap` folds a near-miss onto+ // `other` with the prose diagnosis intact. Rejecting here would throw the+ // expensive part away over a word.+ it('accepts a gap outside the vocabulary and lets the service fold it', async () => {+ reportGoalFidelityFalsePositive.mockResolvedValue({ queued: true, gap: 'other', taskId: 'calib-1' });+ const res = await post({ gap: 'the-model-was-confused', detail: 'the cap was already on main' });+ expect(res.status).toBe(200);+ expect(reportGoalFidelityFalsePositive).toHaveBeenCalledWith(+ expect.objectContaining({ gap: 'the-model-was-confused' }),+ );+ });++ it('still requires a gap — a report naming no missing context cannot be keyed at all', async () => {+ expect((await post({ detail: 'it was wrong' })).status).toBe(400);+ expect(reportGoalFidelityFalsePositive).not.toHaveBeenCalled();+ });++ // A refusal is an outcome, not an error: the reporting agent cannot fix a+ // disabled gate or an open circuit breaker, and a 4xx would send it into a+ // retry loop over a decision it does not own.+ it('answers 200 with the reason when the calibration was not queued', async () => {+ reportGoalFidelityFalsePositive.mockResolvedValue({ queued: false, gap: 'other', reason: 'the goal-fidelity gate is disabled on this install' });+ const res = await post({ gap: 'other' });+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ queued: false, reason: expect.stringContaining('disabled') });+ });+});diff --git a/server/services/goalFidelityCalibration.js b/server/services/goalFidelityCalibration.jsnew file mode 100644index 0000000000..9fef0bb2c1--- /dev/null+++ b/server/services/goalFidelityCalibration.js@@ -0,0 +1,135 @@+/**+ * Goal-fidelity calibration — queue the fix for a detector that was wrong.+ *+ * The follow-up investigator (`goalFidelityFollowUp.js` queues it) is sent to+ * reconcile a fidelity finding. Sometimes it gets there and finds nothing to+ * reconcile: the objective WAS delivered and the reviewer misjudged it. Until+ * now that was where the signal died — the agent shipped nothing, the run+ * record kept a `rethink` nobody could contest, and the same blind spot held+ * the next run of the same shape.+ *+ * This module is the other end of that report. It turns "the detector was+ * wrong, and here is what it could not see" into a task against PortOS's own+ * repo to close that gap. `lib/goalFidelityCalibration.js` owns the vocabulary,+ * the dedup identity and the task body; this owns the settings read, the queue+ * write, and the refusals.+ *+ * THREE things here are deliberate and easy to get backwards:+ *+ * - The calibration is queued against PORTOS, never the app whose run produced+ * the finding. `fileInvestigationTask` takes `app` from the caller and+ * defaults to PortOS when it is absent, so this simply never passes one. The+ * finding belonged to the managed app; the judge that produced it is PortOS+ * code, and a PortOS prompt fix sitting in a managed app's queue is work+ * nothing can do.+ * - It is gated on the GATE, not on the follow-up switches. `fileIssue` /+ * `queueTask` decide whether a finding reaches a tracker or an agent — both+ * outward, both off by default. A calibration report writes one local queue+ * entry and only ever exists because something explicitly reported a false+ * positive, so requiring a second opt-in would discard the single most+ * valuable signal the feature produces from the installs most likely to+ * produce it. The gate being off is still a refusal: with no reviewer there+ * are no verdicts, so a report against it describes something that cannot+ * have happened.+ * - Nothing here can fail a run or a request beyond its own result. The caller+ * reports what happened and moves on.+ *+ * Still open: the overturn is not written back onto the run record, so the agent+ * card keeps rendering the disproved verdict and keeps offering to investigate+ * it. Tracked in #7694, which spans the client surface and a task→agent lookup+ * a report does not currently carry.+ */++import { getSettings } from './settings.js';+import { fileInvestigationTask } from './investigationTaskProducer.js';+import { SUPERVISED_INVESTIGATION_DELIVERY, investigationOutcome } from '../lib/investigationTasks.js';+import {+ buildGoalFidelityCalibrationTask,+ formatGoalFidelityCalibrationSummary,+ goalFidelityCalibrationFingerprint,+ normalizeGoalFidelityContextGap,+} from '../lib/goalFidelityCalibration.js';++/**+ * Is the goal-fidelity gate configured at all on this install?+ *+ * Reads the RAW `enabled` flag rather than `resolveGoalFidelityConfig`, which+ * also requires a callable local backend. The backend answers "can we judge a+ * run right now"; by the time a report arrives a run was already judged, and a+ * user who has since swapped local models would otherwise have their report+ * dropped for a reason that has nothing to do with it.+ */+const gateEnabled = (codeReview) => codeReview?.goalFidelity?.enabled !== false;++/**+ * Record an overturned goal-fidelity finding and queue the calibration.+ *+ * @param {Object} args+ * @param {string} args.gap - which context the reviewer was missing+ * (`GOAL_FIDELITY_CONTEXT_GAPS`); anything unknown normalizes to `other`+ * rather than being refused, because a report with a bad enum still carries a+ * real diagnosis in its prose.+ * @param {string} [args.detail] - the investigator's diagnosis, free text.+ * @param {string} [args.evidence] - what proves the objective was delivered.+ * @param {string} [args.fingerprint] - the overturned finding's own key, kept as+ * provenance only. Never the dedup key: that is derived from the gap here, so+ * a caller cannot choose (or collide with) the identity its report files under.+ * @param {string} [args.taskId] - the task whose run was misjudged, recorded on+ * the calibration as an affected task so a repeat report accumulates rather+ * than replacing.+ * @param {string} [args.verdict] - the verdict that was overturned, for the body.+ * @returns {Promise<{queued: boolean, gap: string, fingerprint: string,+ * taskId?: string, approvalRequired?: boolean, duplicate?: boolean,+ * reason?: string}>}+ */+export async function reportGoalFidelityFalsePositive({ gap, detail, evidence, fingerprint, taskId, verdict } = {}) {+ const resolvedGap = normalizeGoalFidelityContextGap(gap);+ const calibrationFingerprint = goalFidelityCalibrationFingerprint(resolvedGap);+ const settings = await getSettings().catch(() => null);+ if (!gateEnabled(settings?.codeReview)) {+ return report({+ queued: false,+ gap: resolvedGap,+ fingerprint: calibrationFingerprint,+ reason: 'the goal-fidelity gate is disabled on this install, so no review could have produced this finding',+ });+ }++ const description = buildGoalFidelityCalibrationTask({+ gap: resolvedGap,+ detail,+ evidence,+ findingFingerprint: fingerprint,+ taskId,+ verdict,+ });+ const filed = await fileInvestigationTask({+ fingerprint: calibrationFingerprint,+ description,+ affectedTasks: taskId ? [taskId] : [],+ priority: 'MEDIUM',+ context: `Auto-generated from an overturned goal-fidelity finding (${resolvedGap})`,+ // SUPERVISED rather than the unattended merge-on-green default, and the+ // reason is specific to what this task edits: the judge itself. Every other+ // auto-filed investigation fixes one failure. A calibration rewrites the+ // objective assembly, the diff window, or the rubric that every FUTURE run+ // is judged against — and the cheapest way to stop a false positive+ // recurring is to stop the gate holding runs at all. That change would pass+ // CI, look like a fix, and silently disarm the gate for good.+ }, { delivery: SUPERVISED_INVESTIGATION_DELIVERY });++ return report({ gap: resolvedGap, fingerprint: calibrationFingerprint, ...investigationOutcome(filed, { subject: 'the calibration task' }) });+}++/**+ * Log what happened, then hand the result back unchanged.+ *+ * The route answers a reporting AGENT, so without this the only record that a+ * calibration was queued — or refused — lives in an HTTP response nobody reads.+ * Counts and identifiers only: the report's prose is model-authored text derived+ * from an untrusted diff and belongs in the task body, not a log line.+ */+function report(result) {+ console.log(`${result.queued ? '🎯' : '⚠️'} ${formatGoalFidelityCalibrationSummary(result)}`);+ return result;+}diff --git a/server/services/goalFidelityCalibration.test.js b/server/services/goalFidelityCalibration.test.jsnew file mode 100644index 0000000000..b6a963224f--- /dev/null+++ b/server/services/goalFidelityCalibration.test.js@@ -0,0 +1,144 @@+/**+ * The calibration producer at its public boundary: an overturned goal-fidelity+ * finding in → a task queued against PortOS's own repo out.+ *+ * Three things here would each be invisible in production until they had+ * already cost something:+ *+ * - the calibration must land on PORTOS, not on the app whose run produced the+ * finding. Passing the app through would put a PortOS prompt fix in a managed+ * app's backlog, where nothing can act on it — and it would look like it+ * worked;+ * - the dedup key must be DERIVED from the gap, never taken from the report.+ * The reporter is a model writing JSON; a key it chose could collide with (or+ * evict) an unrelated investigation;+ * - the PR must wait for a human. A calibration edits the judge every future+ * run is scored by, and "merge on green" on that is how a gate gets disarmed+ * quietly.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++const getSettings = vi.fn();+const fileInvestigationTask = vi.fn();++vi.mock('./settings.js', () => ({ getSettings }));+vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask }));++const { reportGoalFidelityFalsePositive } = await import('./goalFidelityCalibration.js');+const { SUPERVISED_INVESTIGATION_DELIVERY } = await import('../lib/investigationTasks.js');+const { goalFidelityCalibrationFingerprint } = await import('../lib/goalFidelityCalibration.js');++const REPORT = {+ gap: 'work-outside-diff',+ detail: 'The cap already existed on the base branch; the run only added its test.',+ evidence: 'server/lib/retry.js:88',+ fingerprint: 'goal-fidelity:user:comics/add-retry-caps',+ taskId: 'task-7',+ verdict: 'rethink',+};++/** The single `fileInvestigationTask` call's two arguments. */+const filed = () => ({ args: fileInvestigationTask.mock.calls[0][0], opts: fileInvestigationTask.mock.calls[0][1] });++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({ codeReview: { goalFidelity: { enabled: true } } });+ fileInvestigationTask.mockResolvedValue({ task: { id: 'calib-1' }, approvalRequired: false, loopReason: null });+});++describe('reportGoalFidelityFalsePositive', () => {+ it('queues the calibration against PortOS, never the app the finding was about', async () => {+ const result = await reportGoalFidelityFalsePositive({ ...REPORT, app: 'comics' });+ expect(result.queued).toBe(true);+ expect(result.taskId).toBe('calib-1');+ // `fileInvestigationTask` resolves the repo from `app` and defaults to+ // PortOS when it is absent, so the assertion is that we never pass one —+ // the judge is PortOS code however the finding got here.+ expect(filed().args).not.toHaveProperty('app');+ });++ // The reporter is a model writing JSON, so the key it names is provenance and+ // nothing else. The hostile input is the probe: a report pointing at an+ // unrelated investigation's key must not be able to fold into — or evict — it.+ it('derives the dedup key from the gap and ignores the key the reporter supplied', async () => {+ await reportGoalFidelityFalsePositive({ ...REPORT, fingerprint: 'crash:provider:ollama-timeout' });+ expect(filed().args.fingerprint).toBe(goalFidelityCalibrationFingerprint('work-outside-diff'));+ expect(filed().args.fingerprint).not.toBe('crash:provider:ollama-timeout');+ });++ it('records the misjudged run as an affected task, so repeat reports accumulate', async () => {+ await reportGoalFidelityFalsePositive(REPORT);+ expect(filed().args.affectedTasks).toEqual(['task-7']);+ });++ it('sends no affected tasks when the report named no run', async () => {+ await reportGoalFidelityFalsePositive({ gap: 'rubric-gap' });+ expect(filed().args.affectedTasks).toEqual([]);+ });++ it('makes the PR wait for a human, because the change edits the judge itself', async () => {+ await reportGoalFidelityFalsePositive(REPORT);+ expect(filed().opts.delivery).toBe(SUPERVISED_INVESTIGATION_DELIVERY);+ expect(SUPERVISED_INVESTIGATION_DELIVERY.prCompletion).toBe('review-then-merge');+ });++ it('carries the investigator\'s diagnosis into the queued body', async () => {+ await reportGoalFidelityFalsePositive(REPORT);+ expect(filed().args.description).toContain('the run only added its test');+ expect(filed().args.description).toContain('server/lib/retry.js:88');+ });++ it('normalizes an unknown gap and still queues it', async () => {+ const result = await reportGoalFidelityFalsePositive({ ...REPORT, gap: 'the-model-was-confused' });+ expect(result.queued).toBe(true);+ expect(result.gap).toBe('other');+ expect(filed().args.fingerprint).toBe(goalFidelityCalibrationFingerprint('other'));+ });++ it('refuses when the gate is off — no review could have produced this finding', async () => {+ getSettings.mockResolvedValue({ codeReview: { goalFidelity: { enabled: false } } });+ const result = await reportGoalFidelityFalsePositive(REPORT);+ expect(result.queued).toBe(false);+ expect(result.reason).toMatch(/disabled/);+ expect(fileInvestigationTask).not.toHaveBeenCalled();+ });++ it('runs on an install that configured nothing, since the gate defaults on', async () => {+ // The follow-up switches (`fileIssue` / `queueTask`) gate outward actions and+ // are off by default; a calibration writes one local queue entry and would be+ // lost on exactly the installs most likely to produce it.+ getSettings.mockResolvedValue({ codeReview: {} });+ expect((await reportGoalFidelityFalsePositive(REPORT)).queued).toBe(true);+ });++ it('survives an unreadable settings file rather than dropping the report', async () => {+ getSettings.mockRejectedValue(new Error('EACCES'));+ expect((await reportGoalFidelityFalsePositive(REPORT)).queued).toBe(true);+ });++ it('reports a fold into the open calibration as a usable outcome, not a failure', async () => {+ fileInvestigationTask.mockResolvedValue({ task: { id: 'calib-1', duplicate: true }, approvalRequired: false });+ const result = await reportGoalFidelityFalsePositive(REPORT);+ expect(result).toMatchObject({ queued: true, duplicate: true, taskId: 'calib-1' });+ });++ it('names the loop policy\'s own reason when it suppressed the calibration', async () => {+ fileInvestigationTask.mockResolvedValue({ task: null, loopReason: 'repeat-fingerprint' });+ const result = await reportGoalFidelityFalsePositive(REPORT);+ expect(result.queued).toBe(false);+ expect(result.reason).toContain('repeat-fingerprint');+ });++ it('still answers when the producer returned nothing at all', async () => {+ fileInvestigationTask.mockResolvedValue(null);+ const result = await reportGoalFidelityFalsePositive(REPORT);+ expect(result).toMatchObject({ queued: false, gap: 'work-outside-diff' });+ expect(result.reason).toBeTruthy();+ });++ it('surfaces an approval hold rather than reporting it as queued', async () => {+ fileInvestigationTask.mockResolvedValue({ task: { id: 'calib-1' }, approvalRequired: true });+ expect((await reportGoalFidelityFalsePositive(REPORT)).approvalRequired).toBe(true);+ });+});diff --git a/server/services/goalFidelityFollowUp.js b/server/services/goalFidelityFollowUp.jsindex 8dc2651cbf..1207c8e67f 100644--- a/server/services/goalFidelityFollowUp.js+++ b/server/services/goalFidelityFollowUp.js@@ -20,6 +20,16 @@* the issue and run the project's normal claim flow instead of re-deriving the* work from prose.*+ * The queued task is told to CHECK THE FINDING before acting on it. A verdict is+ * one local model's reading of a diff it saw without the repository, and an+ * agent told only to reconcile will reconcile — inventing a change to satisfy a+ * finding that had nothing behind it. When the objective turns out to have been+ * delivered, the investigator reports the blind spot instead+ * (`services/goalFidelityCalibration.js`), which queues the fix for the detector+ * rather than for the run. The instructions come from+ * `lib/goalFidelityCalibration.js`; this module supplies the loopback API base,+ * which is the one half of it a pure builder cannot resolve.+ ** 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. Two guards, both@@ -50,9 +60,12 @@ import { PORTOS_APP_ID, getAppById } from './apps.js';import { getSettings } from './settings.js';import { fileInvestigationTask } from './investigationTaskProducer.js';import { fileForgeIssue, probeForgeReachability, scrubForgeIssueText } from './appIssues.js';+import { investigationOutcome } from '../lib/investigationTasks.js';import { forgeCliForTracker, resolveAppForgeTarget } from '../lib/workTracker.js';import { safeJSONParse } from '../lib/fileUtils.js';import { boundedErrorMessage } from '../lib/errorHandler.js';+import { localApiBaseUrl } from '../lib/networkExposure.js';+import { buildGoalFidelityFalsePositiveReportBlock } from '../lib/goalFidelityCalibration.js';import {GOAL_FIDELITY_ISSUE_LABEL,GOAL_FIDELITY_ISSUE_LABEL_SPEC,@@ -328,7 +341,15 @@ async function fileFollowUpIssue({ task, review, fingerprint }) {* nothing will pick up is the one wrong thing to say about it.*/async function queueFollowUpTask({ task, review, fingerprint, issue }) {- const description = buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue });+ // The API base is resolved here because it is this layer's to know: the pure+ // builder cannot read the install's live network exposure to find the loopback+ // port the agent should call.+ const falsePositiveBlock = buildGoalFidelityFalsePositiveReportBlock({+ apiBase: localApiBaseUrl(),+ findingFingerprint: fingerprint,+ taskId: task?.id,+ });+ const description = buildGoalFidelityFollowUpTask({ task, review, fingerprint, issue, falsePositiveBlock });const filed = await fileInvestigationTask({fingerprint,description,@@ -337,15 +358,10 @@ async function queueFollowUpTask({ task, review, fingerprint, issue }) {context: `Auto-generated from a goal-fidelity ${review?.verdict} verdict`,...(task?.metadata?.app ? { app: task.metadata.app } : {}),});- if (!filed?.task) return { task: null, loopReason: filed?.loopReason || null };- return {- task: filed.task,- approvalRequired: filed.approvalRequired === true,- // A duplicate fold is addTask's signal that an open task already tracks- // this cause — a usable outcome, not a failure.- duplicate: filed.task.duplicate === true,- loopReason: filed.loopReason || null,- };+ // One reading of the producer's return, shared with the calibration producer:+ // a HELD task is not a queued one, and a duplicate fold is a usable outcome+ // rather than a failure. Both are easy to re-derive slightly differently.+ return investigationOutcome(filed, { subject: 'the follow-up task' });}/**@@ -385,21 +401,18 @@ export async function runGoalFidelityFollowUp({ agentId, task, review }) {console.error(`❌ goal-fidelity follow-up: could not queue a task for ${agentId}: ${err.message}`);return null;});- result.task = queued?.task+ result.task = queued?.queued? {- id: queued.task.id,- approvalRequired: queued.approvalRequired === true,- duplicate: queued.duplicate === true,+ id: queued.taskId,+ approvalRequired: queued.approvalRequired,+ duplicate: queued.duplicate,...(queued.loopReason ? { loopReason: queued.loopReason } : {}),}: null;- // Name the loop policy's own reason when it has one: "could not be queued"- // is the least actionable thing we could say about a deliberate suppression.- if (!result.task) {- result.taskError = queued?.loopReason- ? `the follow-up task was suppressed (${queued.loopReason})`- : 'the follow-up task could not be queued';- }+ // The producer's own refusal sentence, which names the loop policy's reason+ // when it has one — "could not be queued" is the least actionable thing we+ // could say about a deliberate suppression.+ if (!result.task) result.taskError = queued?.reason || 'the follow-up task could not be queued';}return result;diff --git a/server/services/goalFidelityFollowUp.test.js b/server/services/goalFidelityFollowUp.test.jsindex 5ce6a85458..a6cf41bdba 100644--- a/server/services/goalFidelityFollowUp.test.js+++ b/server/services/goalFidelityFollowUp.test.js@@ -429,6 +429,19 @@ describe('runGoalFidelityFollowUp — the queued task', () => {expect(execGh).not.toHaveBeenCalled(); // no issue filing was asked for});+ // The investigator can only report an overturned finding if the task it is+ // handed tells it how, with THIS install's loopback base and the bearer+ // argument — neither of which the pure body builder can resolve. Without them+ // a false positive ends where it always did: an agent spent, nothing learned.+ it('tells the investigator to check the finding and how to report it if it was wrong', async () => {+ settings({ queueTask: true });+ await run();+ const { description } = fileInvestigationTask.mock.calls[0][0];+ expect(description).toMatch(/is the finding actually right/i);+ expect(description).toMatch(/http:\/\/127\.0\.0\.1:\d+\/api\/cos\/goal-fidelity\/false-positive/);+ expect(description).toContain('Authorization: Bearer ${PORTOS_API_TOKEN:-}');+ });+// The loop policy can HOLD a follow-up for a human; reporting "queued" for a// task nothing will pick up is the one wrong thing to say about it.it('carries the producer approval verdict, so a held task is not reported as queued', async () => {diff --git a/server/services/investigationTaskProducer.js b/server/services/investigationTaskProducer.jsindex bd1534ec49..3a8e5927d9 100644--- a/server/services/investigationTaskProducer.js+++ b/server/services/investigationTaskProducer.js@@ -155,3 +155,4 @@ export async function fileInvestigationTask(if (!task?.duplicate) noteInvestigationFiled(now);return { task, approvalRequired: verdict.approvalRequired, loopReason: verdict.loopReason };}+diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txtindex 6fb3440878..570482aa72 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-compact.txt@@ -32,7 +32,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txtindex f71ecf2426..a92f34a776 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-leaveopen-verbose.txt@@ -40,7 +40,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txtindex c6f96bbc3a..89bd9e81e9 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt@@ -37,7 +37,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txtindex 1556ee8e0a..f601c055b3 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt@@ -45,7 +45,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txtindex 3be3bc83b8..4f447eb1ea 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-compact.txt@@ -32,7 +32,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txtindex 66284829b1..aabc56bb5e 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-leaveopen-verbose.txt@@ -40,7 +40,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txtindex 92b7f2223e..c3f72e3033 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt@@ -36,7 +36,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txtindex 44e535710d..9399d047cc 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt@@ -44,7 +44,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txtindex 2ed4409604..385fc20fad 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt@@ -25,7 +25,7 @@ A previous agent finished task **task-example** and opened **PR https://github.c```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txtindex 794b34e31e..0f6cdb1b88 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-compact.txt@@ -40,7 +40,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txtindex 1b9c786559..29aea54e9f 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-leaveopen-verbose.txt@@ -48,7 +48,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txtindex a2c8dccd82..312ea879b3 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-compact.txt@@ -46,7 +46,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txtindex 5a7ef81c83..313e31cb37 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-gh-merge-verbose.txt@@ -54,7 +54,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a PR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txtindex 4330ad315e..9452705362 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-compact.txt@@ -40,7 +40,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txtindex 3be922cad8..f14aca1885 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-leaveopen-verbose.txt@@ -48,7 +48,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txtindex 5624180d12..fb32d53f82 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-compact.txt@@ -45,7 +45,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txtindex ac7ef6d7bf..5a860eb76a 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/inline-glab-merge-verbose.txt@@ -53,7 +53,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, post a MR comment and stop. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to merge; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.PR Details:diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txtindex 5942a38aed..123eb9cea4 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt@@ -33,7 +33,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, stop without pushing or opening a PR/MR. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to the PR/MR creation step; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txtindex 5942a38aed..123eb9cea4 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/local-glab.txt@@ -33,7 +33,7 @@ Only a successfully extracted `.findings` value is the review text; treat it lik```bashcurl -sS -X POST http://127.0.0.1:5555/api/cos/tasks/task-example/challenge -H 'Content-Type: application/json' -H "Authorization: Bearer ${PORTOS_API_TOKEN:-}" -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'```-Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install gates `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.+Keep that `Authorization` header on every PortOS API call you make, including the `/resolve` POST below: this install may gate `/api/*` behind its instance password, and `$PORTOS_API_TOKEN` is the session token PortOS put in your environment for exactly this. A bare `401 AUTH_REQUIRED` means the header was dropped, not that the endpoint is unavailable.A `409` (`CHALLENGE_EXHAUSTED` = the one challenge is spent, or `CHALLENGE_BUDGET_EXHAUSTED` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, stop without pushing or opening a PR/MR. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → `POST .../challenge/resolve` with `{"outcome":"upheld"}` and continue to the PR/MR creation step; confirmed → fix it, or send `{"outcome":"escalated"}` to hand the dispute to the user. For a local reviewer you may instead POST `{"recheck":{"backend":"ollama","diff":"<unified diff>"}}` and let the server re-run it and auto-derive the outcome.### CLI Reviewer Procedure (codex)diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex 91fb9c371f..441180237a 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -7,7 +7,7 @@ import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';import { detectForgeCli } from '../../lib/gitForge.js';import { shellQuote } from '../../lib/shellQuote.js';import { localApiBaseUrl } from '../../lib/networkExposure.js';-import { AGENT_API_AUTH_CURL_ARG } from '../../lib/agentApiToken.js';+import { agentApiAuthNote, agentApiCurl } from '../../lib/agentApiToken.js';import { LOCAL_REVIEW_BRIDGE_SCRIPT } from '../../lib/localReviewBridge.js';import { INLINE_REVIEW_LOOP_STEP } from './constants.js';import { normalizeForgeCli } from './forge.js';@@ -818,9 +818,13 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const challengeProtocolNote = ['**Challenge protocol (dispute a wrong rejection — use sparingly):** If a reviewer raises a BLOCKING finding you have strong, specific evidence is a false positive (it misread the diff, flagged intended behavior, or contradicts a documented repo convention), do NOT silently "fix" it or accept a false block — dispute it **exactly once** for this task:','```bash',- `curl -sS -X POST ${apiBase}/api/cos/tasks/${sourceTaskId}/challenge -H 'Content-Type: application/json' ${AGENT_API_AUTH_CURL_ARG} -d '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}'`,+ agentApiCurl({+ apiBase,+ path: `/api/cos/tasks/${sourceTaskId}/challenge`,+ payload: '{"reason":"<why the finding is wrong>","evidence":"<file:line or diff quote>","reviewer":"<disputed reviewer>"}',+ }),'```',- `Keep that \`Authorization\` header on every PortOS API call you make, including the \`/resolve\` POST below: this install gates \`/api/*\` behind its instance password, and \`$PORTOS_API_TOKEN\` is the session token PortOS put in your environment for exactly this. A bare \`401 AUTH_REQUIRED\` means the header was dropped, not that the endpoint is unavailable.`,+ agentApiAuthNote({ alsoCovering: 'including the `/resolve` POST below' }),`A \`409\` (\`CHALLENGE_EXHAUSTED\` = the one challenge is spent, or \`CHALLENGE_BUDGET_EXHAUSTED\` = the task is out of retry budget) means you can't dispute — then fix the finding or, if genuinely blocked, ${phase.challengeBlockedText(forge)}. After filing, RE-CHECK: re-run the disputed reviewer (or another configured reviewer) against the current diff, then resolve — overturned → \`POST .../challenge/resolve\` with \`{"outcome":"upheld"}\` and continue to ${phase.challengeContinueText}; confirmed → fix it, or send \`{"outcome":"escalated"}\` to hand the dispute to the user.` + (hasLocalLlm ? ` For a local reviewer you may instead POST \`{"recheck":{"backend":"${localLlmBackendToken}","diff":"<unified diff>"}}\` and let the server re-run it and auto-derive the outcome.` : ''),].join('\n');// Per-reviewer round caps. This prompt drives the loop in PROSE (it isn't