Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix three opencode review findings in the goal-fidelity calibration loop

[._.]/ Adam Eivy442391d26067
diff --git a/server/lib/agentApiToken.js b/server/lib/agentApiToken.js
index 0a9ebd8fb5..0b371a1d1b 100644
--- a/server/lib/agentApiToken.js
+++ b/server/lib/agentApiToken.js
@@ -5,10 +5,13 @@
* (`services/agentApiAuth.js` and the three env-composition sites) and the
* prompt builders that write the `curl` snippets an agent copy-pastes.
*
- * Pure and dependency-free so a prompt section can name the credential without
- * pulling the auth/settings subtree into its import closure.
+ * Pure so a prompt section can name the credential without pulling the
+ * auth/settings subtree into its import closure; `shellQuote.js` is itself a
+ * zero-import leaf, so the one edge costs nothing.
*/
+import { shellQuote } from './shellQuote.js';
+
export const AGENT_API_TOKEN_ENV = 'PORTOS_API_TOKEN';
/**
@@ -31,11 +34,17 @@ export const AGENT_API_AUTH_CURL_ARG = `-H "Authorization: Bearer \${${AGENT_API
*
* 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.
+ * `401` the agent reads as a broken endpoint.
+ *
+ * `payload` is JSON the caller built, and it goes through `shellQuote` rather
+ * than into hand-written `'…'`: the agent pastes this line into a shell, so a
+ * single apostrophe anywhere in it — one interpolated task id or fingerprint is
+ * enough — would close the quoting and turn the rest of the JSON into shell
+ * words. Today's payloads happen not to contain one, which is exactly why the
+ * bug would ship silently.
*/
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}'` : ''}`
+ `curl -sS -X POST ${apiBase}${path} -H 'Content-Type: application/json' ${AGENT_API_AUTH_CURL_ARG}${payload ? ` -d ${shellQuote(payload)}` : ''}`
);
/**
diff --git a/server/lib/agentApiToken.test.js b/server/lib/agentApiToken.test.js
new file mode 100644
index 0000000000..c646985617
--- /dev/null
+++ b/server/lib/agentApiToken.test.js
@@ -0,0 +1,66 @@
+/**
+ * The agent-facing API call shape.
+ *
+ * Both halves of this module end up in a prompt an autonomous agent pastes into
+ * a shell, which is what makes them worth pinning:
+ *
+ * - the `curl` line carries a JSON payload we build. It used to go into
+ * hand-written `'…'`, so one apostrophe — in a task id, a fingerprint, or any
+ * field a future caller interpolates — would close the quoting and hand the
+ * rest of the JSON to the shell as words. No payload in the tree contains one
+ * today, which is exactly why nothing would have caught it;
+ * - the auth note tells the agent what a `401` means. Two hand-written copies
+ * had already drifted on whether the install "gates" or "may gate" `/api/*`,
+ * and only one of those is true: auth is opt-in and OFF by default, so an
+ * agent told the install definitely gates it draws the wrong conclusion from
+ * a 200.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { AGENT_API_AUTH_CURL_ARG, AGENT_API_TOKEN_ENV, agentApiAuthNote, agentApiCurl } from './agentApiToken.js';
+
+describe('agentApiCurl', () => {
+ const call = agentApiCurl({ apiBase: 'http://127.0.0.1:5553', path: '/api/cos/x', payload: '{"a":1}' });
+
+ it('spends the session token on every call it builds', () => {
+ expect(call).toContain(AGENT_API_AUTH_CURL_ARG);
+ expect(call).toContain("-H 'Content-Type: application/json'");
+ expect(call.startsWith('curl -sS -X POST http://127.0.0.1:5553/api/cos/x')).toBe(true);
+ });
+
+ it('keeps an apostrophe in the payload from escaping the quoting', () => {
+ // The failure it prevents: `-d '{"detail":"it'`… ends the quoted argument at
+ // the apostrophe, and the shell parses the remaining JSON as commands.
+ //
+ // Asserted by running the emitted argument through a REAL shell and reading
+ // the argument back, rather than by matching the escaped spelling: the
+ // property that matters is "the agent's shell hands curl exactly this JSON",
+ // and a literal-string assertion would pass for any escaping that merely
+ // looks plausible.
+ const payload = `{"detail":"it's wrong","evidence":"a $(touch /tmp/pwned) b"}`;
+ const line = agentApiCurl({ apiBase: 'http://x', path: '/p', payload });
+ const dataArg = line.slice(line.indexOf(' -d ') + 4);
+ const roundTripped = execFileSync('sh', ['-c', `printf '%s' ${dataArg}`], { encoding: 'utf8' });
+ expect(roundTripped).toBe(payload);
+ });
+
+ it('omits the data flag entirely when there is no payload', () => {
+ expect(agentApiCurl({ apiBase: 'http://x', path: '/p' })).not.toContain(' -d ');
+ });
+});
+
+describe('agentApiAuthNote', () => {
+ it('says the install MAY gate /api/*, because auth is opt-in and off by default', () => {
+ const note = agentApiAuthNote();
+ expect(note).toContain('may gate');
+ expect(note).toContain(`$${AGENT_API_TOKEN_ENV}`);
+ // The one conclusion an agent must not draw from a 401.
+ expect(note).toContain('not that the endpoint is unavailable');
+ });
+
+ it('names the other calls in a multi-call protocol without restating the paragraph', () => {
+ expect(agentApiAuthNote({ alsoCovering: 'including the `/resolve` POST below' }))
+ .toContain('you make, including the `/resolve` POST below:');
+ });
+});
diff --git a/server/lib/goalFidelityCalibration.js b/server/lib/goalFidelityCalibration.js
index 8179596f8b..cf34f3b51b 100644
--- a/server/lib/goalFidelityCalibration.js
+++ b/server/lib/goalFidelityCalibration.js
@@ -28,7 +28,8 @@
* 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`).
+ * task, which the service then unions each further run into (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
@@ -203,10 +204,10 @@ export const GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS = 4_000;
* 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.
+ * Keyed on the gap they all fold into one task, and the producer unions each
+ * later report's run into it (`unionAffectedRun` in the service — `addTask`'s
+ * own dedup returns the survivor untouched) — 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
@@ -218,12 +219,41 @@ 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) => {
+/**
+ * Is this value still the `<…>` placeholder the report block handed the agent?
+ *
+ * The block gives the investigator a ready-to-run `curl` with every field
+ * spelled as `<what the reviewer could not see, …>`. An agent that runs it
+ * unchanged sends those literals, and without this they land in the calibration
+ * body as if they were a diagnosis — a task that reads like a real report and
+ * says nothing. Shape-matched rather than compared against the exact template
+ * strings, so rewording the block cannot quietly stop detecting it.
+ */
+const isPlaceholder = (text) => /^<[^>]*>$/.test(String(text ?? '').trim());
+
+/** One reported free-text field, or `''` when it is absent or still the template. */
+export const reportedField = (text) => {
const trimmed = typeof text === 'string' ? text.trim() : '';
- return trimmed ? trimTo(trimmed, GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS) : empty;
+ return !trimmed || isPlaceholder(trimmed) ? '' : trimTo(trimmed, GOAL_FIDELITY_CALIBRATION_FREE_TEXT_CHARS);
};
+/**
+ * Did this report carry anything real at all?
+ *
+ * False only for the wholly-unfilled template: no recognized gap (so it
+ * normalized to `other`) AND no usable detail or evidence. A partially-filled
+ * report still queues — a named gap alone points at a file, which is more than
+ * nothing — so this refuses the one case that is pure noise.
+ */
+export function goalFidelityReportIsSubstantive({ gap, detail, evidence } = {}) {
+ return GOAL_FIDELITY_CONTEXT_GAPS.includes(gap)
+ || Boolean(reportedField(detail))
+ || Boolean(reportedField(evidence));
+}
+
+/** Bounded free text, or a stated absence — never a silent empty section. */
+const reported = (text, empty) => reportedField(text) || empty;
+
/**
* The CoS task body for one calibration.
*
diff --git a/server/lib/goalFidelityCalibration.test.js b/server/lib/goalFidelityCalibration.test.js
index 3d0da21ecc..b89443664f 100644
--- a/server/lib/goalFidelityCalibration.test.js
+++ b/server/lib/goalFidelityCalibration.test.js
@@ -26,6 +26,7 @@ import {
GOAL_FIDELITY_CONTEXT_GAPS,
GOAL_FIDELITY_REVIEW_SURFACES,
buildGoalFidelityCalibrationTask,
+ goalFidelityReportIsSubstantive,
buildGoalFidelityFalsePositiveReportBlock,
describeGoalFidelityContextGap,
formatGoalFidelityCalibrationSummary,
@@ -145,6 +146,42 @@ describe('buildGoalFidelityCalibrationTask', () => {
});
});
+describe('the unfilled-template guard', () => {
+ // The report block hands the agent a ready-to-run curl whose every field is a
+ // `<…>` placeholder. Running it verbatim used to queue an `other` calibration
+ // whose "diagnosis" was the template — a task that reads like a report, says
+ // nothing, and costs a whole agent run to discover that.
+ it('rejects the template exactly as the report block emits it', () => {
+ expect(goalFidelityReportIsSubstantive({
+ gap: '<one of: truncated-diff | other>',
+ detail: '<what the reviewer could not see, in one or two sentences>',
+ evidence: '<file:line, commit, or PR that shows the objective WAS delivered>',
+ })).toBe(false);
+ });
+
+ it('accepts a report that filled in ANY one field, since a partial report still points somewhere', () => {
+ expect(goalFidelityReportIsSubstantive({ gap: 'rubric-gap' })).toBe(true);
+ expect(goalFidelityReportIsSubstantive({ gap: '<one of: …>', detail: 'the cap was already on main' })).toBe(true);
+ expect(goalFidelityReportIsSubstantive({ gap: '<one of: …>', evidence: 'server/lib/retry.js:88' })).toBe(true);
+ });
+
+ it('rejects an empty report, which carries no more than the template does', () => {
+ expect(goalFidelityReportIsSubstantive({})).toBe(false);
+ expect(goalFidelityReportIsSubstantive({ gap: 'nonsense', detail: ' ' })).toBe(false);
+ });
+
+ it('keeps placeholder prose out of the task body when other fields were filled', () => {
+ const body = buildGoalFidelityCalibrationTask({
+ gap: 'rubric-gap',
+ detail: '<what the reviewer could not see, in one or two sentences>',
+ evidence: 'server/lib/retry.js:88',
+ });
+ expect(body).not.toContain('what the reviewer could not see');
+ expect(body).toContain('_The report named no detail beyond the gap._');
+ expect(body).toContain('server/lib/retry.js:88');
+ });
+});
+
describe('buildGoalFidelityFalsePositiveReportBlock', () => {
const block = buildGoalFidelityFalsePositiveReportBlock({
apiBase: 'http://127.0.0.1:5553',
diff --git a/server/services/goalFidelityCalibration.js b/server/services/goalFidelityCalibration.js
index 9fef0bb2c1..07459e7b86 100644
--- a/server/services/goalFidelityCalibration.js
+++ b/server/services/goalFidelityCalibration.js
@@ -40,13 +40,16 @@
* a report does not currently carry.
*/
+import { updateTask } from './cos.js';
import { getSettings } from './settings.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
import { SUPERVISED_INVESTIGATION_DELIVERY, investigationOutcome } from '../lib/investigationTasks.js';
import {
+ GOAL_FIDELITY_CONTEXT_GAPS,
buildGoalFidelityCalibrationTask,
formatGoalFidelityCalibrationSummary,
goalFidelityCalibrationFingerprint,
+ goalFidelityReportIsSubstantive,
normalizeGoalFidelityContextGap,
} from '../lib/goalFidelityCalibration.js';
@@ -66,17 +69,19 @@ const gateEnabled = (codeReview) => codeReview?.goalFidelity?.enabled !== false;
*
* @param {Object} args
* @param {string} args.gap - which context the reviewer was missing
- * (`GOAL_FIDELITY_CONTEXT_GAPS`); anything unknown normalizes to `other`
+ * (`GOAL_FIDELITY_CONTEXT_GAPS`); an unrecognized value normalizes to `other`
* rather than being refused, because a report with a bad enum still carries a
- * real diagnosis in its prose.
+ * real diagnosis in its prose. The one refusal is a report with no recognized
+ * gap AND no filled-in prose — the unrun template.
* @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.
+ * the calibration as an affected task. A repeat report for the same gap folds
+ * into the open calibration and unions its run id in (`unionAffectedRun`), so
+ * the task names every run the gap cost rather than only the first.
* @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,
@@ -85,6 +90,19 @@ const gateEnabled = (codeReview) => codeReview?.goalFidelity?.enabled !== false;
export async function reportGoalFidelityFalsePositive({ gap, detail, evidence, fingerprint, taskId, verdict } = {}) {
const resolvedGap = normalizeGoalFidelityContextGap(gap);
const calibrationFingerprint = goalFidelityCalibrationFingerprint(resolvedGap);
+ // The report block hands the agent a ready-to-run `curl` full of `<…>`
+ // placeholders. One run verbatim would queue an `other` calibration whose
+ // diagnosis is the template — a task that reads like a report and says
+ // nothing, which an agent then spends a run on. Refused with an actionable
+ // reason rather than 400'd, since the caller is an agent reading the body.
+ if (!goalFidelityReportIsSubstantive({ gap, detail, evidence })) {
+ return report({
+ queued: false,
+ gap: resolvedGap,
+ fingerprint: calibrationFingerprint,
+ reason: `the report was still the unfilled template — send a gap from ${GOAL_FIDELITY_CONTEXT_GAPS.join('/')}, and say in 'detail' what the reviewer could not see`,
+ });
+ }
const settings = await getSettings().catch(() => null);
if (!gateEnabled(settings?.codeReview)) {
return report({
@@ -118,7 +136,34 @@ export async function reportGoalFidelityFalsePositive({ gap, detail, evidence, f
// 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' }) });
+ const outcome = investigationOutcome(filed, { subject: 'the calibration task' });
+ if (outcome.duplicate) await unionAffectedRun(filed.task, taskId);
+ return report({ gap: resolvedGap, fingerprint: calibrationFingerprint, ...outcome });
+}
+
+/**
+ * Fold a repeat report's run into the calibration that already tracks this gap.
+ *
+ * `addTask`'s dedup returns the surviving task untouched — only the
+ * agent-failure producer carries a union of its own — so without this the
+ * calibration names the FIRST misjudged run and no other, however many times
+ * the gap fired. That count is exactly the evidence the task body tells the
+ * agent to size the fix by ("every run the gap cost"), so losing it makes a
+ * recurring blind spot look like a one-off.
+ *
+ * Same shape as the agent-failure producer's union: metadata AND a line in the
+ * body, because the body is what the agent reads. Best-effort — a calibration
+ * that is queued but missing one run id is worth more than a failed report.
+ */
+async function unionAffectedRun(task, taskId) {
+ const affected = Array.isArray(task?.metadata?.affectedTasks) ? task.metadata.affectedTasks : [];
+ if (!taskId || !task?.id || affected.includes(taskId)) return;
+ await updateTask(task.id, {
+ description: `${task.description}\n- Also misjudged task \`${taskId}\` (same context gap).`,
+ metadata: { affectedTasks: [...affected, taskId] },
+ }, 'internal').catch((err) => {
+ console.error(`❌ goal-fidelity calibration: could not union ${taskId} into ${task.id}: ${err.message}`);
+ });
}
/**
diff --git a/server/services/goalFidelityCalibration.test.js b/server/services/goalFidelityCalibration.test.js
index b6a963224f..5629555301 100644
--- a/server/services/goalFidelityCalibration.test.js
+++ b/server/services/goalFidelityCalibration.test.js
@@ -21,7 +21,9 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
const getSettings = vi.fn();
const fileInvestigationTask = vi.fn();
+const updateTask = vi.fn();
+vi.mock('./cos.js', () => ({ updateTask }));
vi.mock('./settings.js', () => ({ getSettings }));
vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask }));
@@ -44,6 +46,7 @@ const filed = () => ({ args: fileInvestigationTask.mock.calls[0][0], opts: fileI
beforeEach(() => {
vi.clearAllMocks();
getSettings.mockResolvedValue({ codeReview: { goalFidelity: { enabled: true } } });
+ updateTask.mockResolvedValue({});
fileInvestigationTask.mockResolvedValue({ task: { id: 'calib-1' }, approvalRequired: false, loopReason: null });
});
@@ -123,6 +126,64 @@ describe('reportGoalFidelityFalsePositive', () => {
expect(result).toMatchObject({ queued: true, duplicate: true, taskId: 'calib-1' });
});
+ // `addTask`'s dedup returns the surviving task untouched, so without an explicit
+ // union the calibration names only the FIRST misjudged run however many times
+ // the gap fires — and the task body tells the agent to size the fix by exactly
+ // that count.
+ it('unions a repeat report\'s run into the calibration that already tracks the gap', async () => {
+ fileInvestigationTask.mockResolvedValue({
+ task: { id: 'calib-1', duplicate: true, description: '[Auto] Goal-fidelity calibration', metadata: { affectedTasks: ['task-1'] } },
+ });
+ await reportGoalFidelityFalsePositive({ ...REPORT, taskId: 'task-9' });
+ expect(updateTask).toHaveBeenCalledWith('calib-1', expect.objectContaining({
+ metadata: { affectedTasks: ['task-1', 'task-9'] },
+ }), 'internal');
+ // The body is what the agent actually reads, so the run has to land there too.
+ expect(updateTask.mock.calls[0][1].description).toContain('task-9');
+ });
+
+ it('does not re-add a run the calibration already names', async () => {
+ fileInvestigationTask.mockResolvedValue({
+ task: { id: 'calib-1', duplicate: true, description: 'x', metadata: { affectedTasks: ['task-7'] } },
+ });
+ await reportGoalFidelityFalsePositive(REPORT);
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('leaves a freshly-created calibration alone — there is nothing to union into', async () => {
+ await reportGoalFidelityFalsePositive(REPORT);
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('still reports the queued calibration when the union write fails', async () => {
+ fileInvestigationTask.mockResolvedValue({
+ task: { id: 'calib-1', duplicate: true, description: 'x', metadata: {} },
+ });
+ updateTask.mockRejectedValue(new Error('state locked'));
+ const result = await reportGoalFidelityFalsePositive({ ...REPORT, taskId: 'task-9' });
+ expect(result).toMatchObject({ queued: true, duplicate: true });
+ });
+
+ // The report block emits a curl whose fields are all `<…>` placeholders; an
+ // agent running it verbatim must not queue a task whose diagnosis is the template.
+ it('refuses the unfilled template with a reason naming what to send instead', async () => {
+ const result = await reportGoalFidelityFalsePositive({
+ gap: '<one of: truncated-diff | other>',
+ detail: '<what the reviewer could not see, in one or two sentences>',
+ evidence: '<file:line, commit, or PR that shows the objective WAS delivered>',
+ });
+ expect(result.queued).toBe(false);
+ expect(result.reason).toMatch(/unfilled template/);
+ expect(result.reason).toContain('rubric-gap');
+ expect(fileInvestigationTask).not.toHaveBeenCalled();
+ });
+
+ it('refuses the template before reading settings, so a disabled gate is not the reported cause', async () => {
+ getSettings.mockResolvedValue({ codeReview: { goalFidelity: { enabled: false } } });
+ const result = await reportGoalFidelityFalsePositive({ gap: '<one of: …>' });
+ expect(result.reason).toMatch(/unfilled template/);
+ });
+
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);