Skip to content

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

refactor: dedupe goal-fidelity issues by label listing instead of full-text search

[._.]/ Adam Eivycf1d0c6de788
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index b6d1c3f708..5a050e3e4c 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -254,13 +254,15 @@ function GoalFidelityFollowUp({ followUp }) {
{issue.duplicate ? 'Already tracked as' : 'Filed as'} {issue.number ? `#${issue.number}` : 'an issue'}
</a>
)}
- {issueError && <span className="text-port-warning">No issue filed: {issueError}</span>}
+ {/* `status`, not `alert`: these report a background follow-up the user
+ did not trigger, so they are passive news, not a response to an action. */}
+ {issueError && <span role="status" className="text-port-warning">No issue filed: {issueError}</span>}
{taskId && (
<Link className="text-port-accent hover:underline w-fit" to={`/cos/tasks?task=${encodeURIComponent(taskId)}&source=internal`}>
View the queued follow-up task
</Link>
)}
- {taskError && <span className="text-port-warning">No follow-up queued: {taskError}</span>}
+ {taskError && <span role="status" className="text-port-warning">No follow-up queued: {taskError}</span>}
</div>
);
}
diff --git a/client/src/components/settings/CodeReviewersTab.jsx b/client/src/components/settings/CodeReviewersTab.jsx
index 32ffe4be51..54b48dc0f8 100644
--- a/client/src/components/settings/CodeReviewersTab.jsx
+++ b/client/src/components/settings/CodeReviewersTab.jsx
@@ -113,10 +113,13 @@ export default function CodeReviewersTab() {
...(goalFidelity.effort ? { effort: goalFidelity.effort } : {}),
// Booleans always ride: unlike the scalars above, `false` here is the
// user turning an action OFF, not "inherit", so dropping it would make
- // the switch un-clearable once it had been on.
+ // the switch un-clearable once it had been on. The trigger is the other
+ // way round — it only means something once an action is armed, so an
+ // install that never armed one is left inheriting the shipped default
+ // rather than pinned to today's value forever.
fileIssue: goalFidelity.fileIssue === true,
queueTask: goalFidelity.queueTask === true,
- followUpOn: goalFidelity.followUpOn || DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ ...(goalFidelity.fileIssue || goalFidelity.queueTask ? { followUpOn: goalFidelity.followUpOn } : {}),
},
};
const ok = await api.updateSettings({ codeReview: payload }, { silent: true })
diff --git a/client/src/components/settings/CodeReviewersTab.test.jsx b/client/src/components/settings/CodeReviewersTab.test.jsx
index 8f7d1b8054..5212558c0b 100644
--- a/client/src/components/settings/CodeReviewersTab.test.jsx
+++ b/client/src/components/settings/CodeReviewersTab.test.jsx
@@ -166,11 +166,13 @@ describe('CodeReviewersTab', () => {
await waitFor(() => expect(api.updateSettings).toHaveBeenCalled());
const [payload] = api.updateSettings.mock.calls[0];
- // The scalars are dropped when unset (absent = inherit), but the follow-up
- // booleans always ride: false there is the user's OFF, not 'inherit', and
- // dropping it would make either switch un-clearable once it had been on.
+ // The scalars are dropped when unset (absent = inherit), and so is the
+ // trigger while neither action is armed — pinning it would freeze an
+ // install on today's default forever. The follow-up BOOLEANS always ride:
+ // false there is the user's OFF, not 'inherit', and dropping one would make
+ // that switch un-clearable once it had been on.
expect(payload.codeReview.goalFidelity).toEqual({
- enabled: true, backend: 'lmstudio', fileIssue: false, queueTask: false, followUpOn: 'rethink',
+ enabled: true, backend: 'lmstudio', fileIssue: false, queueTask: false,
});
});
@@ -192,7 +194,7 @@ describe('CodeReviewersTab', () => {
await waitFor(() => expect(api.updateSettings).toHaveBeenCalled());
expect(api.updateSettings.mock.calls[0][0].codeReview.goalFidelity).toEqual({
- enabled: false, fileIssue: false, queueTask: false, followUpOn: 'rethink',
+ enabled: false, fileIssue: false, queueTask: false,
});
});
diff --git a/client/src/components/settings/GoalFidelityControls.jsx b/client/src/components/settings/GoalFidelityControls.jsx
index f14b24c3c4..fd54bbd3c2 100644
--- a/client/src/components/settings/GoalFidelityControls.jsx
+++ b/client/src/components/settings/GoalFidelityControls.jsx
@@ -1,17 +1,20 @@
import { LOCAL_LLM_EFFORT_LEVELS, LOCAL_LLM_REVIEWERS, reviewerLabel } from '../cos/constants';
import {
DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ GOAL_FIDELITY_FOLLOW_UP_TRIGGERS,
sanitizeReviewerModelInput,
} from '../../lib/reviewerPins';
-// What each trigger means in the user's terms. The values mirror the server's
-// `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` enum; the prose is why one would pick the
-// wider one — `fix-first` never downgrades a run, so an issue is the only thing
-// that carries those findings past the run record.
-const FOLLOW_UP_TRIGGER_OPTIONS = [
- { value: 'rethink', label: 'Only “rethink” — the run built the wrong thing' },
- { value: 'any-finding', label: 'Any finding — also the advisory “fix-first”' },
-];
+// Prose for each trigger, keyed by the mirrored enum rather than re-listing its
+// values: the settings schema is a `z.enum` over the server's list, so an option
+// the picker offered but the enum omitted would 400 the whole save — and the
+// parity test guarding that mirror only covers the picker if the picker renders
+// from it. `fix-first` is the reason to widen: it never downgrades a run, so an
+// issue is the only thing that carries those findings past the run record.
+const FOLLOW_UP_TRIGGER_LABELS = {
+ rethink: 'Only “rethink” — the run built the wrong thing',
+ 'any-finding': 'Any finding — also the advisory “fix-first”',
+};
// The goal-fidelity gate's controls (#5994) — the SECOND review, which asks
// whether a finished run's diff delivers the objective the task stated, rather
@@ -178,8 +181,8 @@ export default function GoalFidelityControls({ value, modelOptions, disabled = f
onChange={(e) => patch({ followUpOn: e.target.value })}
className="w-full sm:w-2/3 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"
>
- {FOLLOW_UP_TRIGGER_OPTIONS.map(({ value: option, label }) => (
- <option key={option} value={option}>{label}</option>
+ {GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.map((option) => (
+ <option key={option} value={option}>{FOLLOW_UP_TRIGGER_LABELS[option]}</option>
))}
</select>
</div>
diff --git a/server/lib/README.md b/server/lib/README.md
index a381f3a82f..a97e2821c1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -525,11 +525,11 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |
| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. |
-| `goalFidelityFollowUp.js` | Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. `resolveGoalFidelityFollowUp(codeReview)` (`null` when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked) and `goalFidelityFollowUpApplies(review, trigger)` over `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` (`rethink` = only the verdict that holds a run, the default; `any-finding` also fires on the advisory `fix-first`). `goalFidelityFingerprint(task)` is the one dedup identity three parties share — the tracker search, the issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`, a colon-free token because every forge parses `:` as a search qualifier), and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. `buildGoalFidelityIssue` / `buildGoalFidelityFollowUpTask` compose the bodies. Pure; I/O lives in `services/goalFidelityFollowUp.js`. |
+| `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`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
-| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels), and `truncateOnBoundary(slug, max)` is its bounder — back off to the last `-` at or before `max` so a slug a human reads (a PLAN.md id, the app segment of a CoS worktree directory) is never cut mid-word, which `trimTo` would reintroduce; `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
+| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels), and `truncateOnBoundary(slug, max)` is its bounder — back off to the last `-` at or before `max` so a slug a human reads (a PLAN.md id, the app segment of a CoS worktree directory) is never cut mid-word, which `trimTo` would reintroduce; `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). `firstLine(text)` is the first non-blank line, trimmed — the CoS task headline `addTask` dedupes on, declared here rather than in the task store so a closure-sensitive caller can reach it (`cosTaskStore.js` re-exports it). |
| `pipelineIssueOrder.js` | Volume-based renumbering and `compareIssuesInSeries` for globally ordered manuscripts and production. |
| `pipelineStages.js` | Canonical pipeline data-stage groups, visible tab order, UI/voice labels, spoken aliases, and derived voice-intent regex. |
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
diff --git a/server/lib/goalFidelityFollowUp.js b/server/lib/goalFidelityFollowUp.js
index 49bf0cf245..1bb6e5a57c 100644
--- a/server/lib/goalFidelityFollowUp.js
+++ b/server/lib/goalFidelityFollowUp.js
@@ -12,8 +12,8 @@
* other; turning both on files the issue first so the queued task can name it.
*
* The dedup identity lives here rather than in the filer because THREE parties
- * have to agree on it — the forge search that decides "already filed", the
- * issue body that carries the marker that search reads back, and the CoS task
+ * have to agree on it — the issue body that carries the marker, the tracker
+ * listing that reads it back to decide "already filed", and the CoS task
* fingerprint that stops a second follow-up run for the same finding. A
* scheduled task regenerates with a fresh id every cadence, so keying on the
* task id alone would re-file the same finding forever; the key is instead
@@ -23,16 +23,19 @@
* Pure and I/O-free: the settings resolver, the filer, the queue producer, and
* the tests share one definition of what a follow-up IS.
*
- * DEPENDENCY-FREE by design. `cosValidation.js` imports this for the settings
- * enum, and it is reached by most of the server suite — so the obvious edge
- * here (`investigationTasks.js`, for its `investigationFingerprint` formatter)
- * put five modules on ~80 suites' closures and blew the import budget for one
- * three-segment template string. The format is inlined instead, and
- * `goalFidelityFollowUp.test.js` pins it against the real
- * `investigationFingerprint` so the two cannot drift: the test pays the import,
- * production does not. See server/AGENTS.md "Import scoping".
+ * CLOSURE-FREE by design. `cosValidation.js` imports this for the settings enum
+ * and is reached by most of the server suite, so every edge here is multiplied
+ * by ~80 suites. `textUtils.js` is free — a zero-import leaf already in all four
+ * consumers' closures — but `investigationTasks.js`, which declares the
+ * `investigationFingerprint` formatter, would have added five modules for one
+ * three-segment template string. So that ONE format is inlined, and
+ * `goalFidelityFollowUp.test.js` pins it against the real function so the two
+ * cannot drift: the test pays the import, production does not. See
+ * server/AGENTS.md "Import scoping".
*/
+import { firstLine, kebabCase, truncateOnBoundary } from './textUtils.js';
+
/**
* Which verdicts trigger a follow-up.
*
@@ -51,6 +54,17 @@ export const GOAL_FIDELITY_FOLLOW_UP_TRIGGERS = Object.freeze(['rethink', 'any-f
/** The trigger an install gets when it has configured none. */
export const DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER = 'rethink';
+/**
+ * One stored trigger, validated. Shared by `resolveGoalFidelityFollowUp` and by
+ * the settings projection the Code Reviewers tab reads back
+ * (`pickCodeReviewDefaults`) — they have to agree, and a silent divergence
+ * between "what the form shows" and "what runs" is invisible until a finding
+ * fires on the wrong verdict.
+ */
+export const normalizeGoalFidelityFollowUpTrigger = (value) => (
+ GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.includes(value) ? value : DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER
+);
+
/** The verdicts each trigger fires on. */
const TRIGGER_VERDICTS = Object.freeze({
rethink: Object.freeze(['rethink']),
@@ -106,10 +120,7 @@ export function resolveGoalFidelityFollowUp(codeReview) {
const fileIssue = raw.fileIssue === true;
const queueTask = raw.queueTask === true;
if (!fileIssue && !queueTask) return null;
- const trigger = GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.includes(raw.followUpOn)
- ? raw.followUpOn
- : DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER;
- return { fileIssue, queueTask, trigger };
+ return { fileIssue, queueTask, trigger: normalizeGoalFidelityFollowUpTrigger(raw.followUpOn) };
}
/** Does this verdict fire the configured trigger? */
@@ -118,20 +129,8 @@ export function goalFidelityFollowUpApplies(review, trigger) {
return verdicts.includes(review?.verdict);
}
-/** Lowercase `a-z0-9-` slug of free text, bounded. */
-function subjectSlug(text) {
- return String(text ?? '')
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .slice(0, SUBJECT_SLUG_MAX)
- .replace(/-+$/, '');
-}
-
-/** First non-blank line of a task description, trimmed. */
-function firstLine(text) {
- return String(text ?? '').split('\n').map(line => line.trim()).find(Boolean) || '';
-}
+/** Lowercase `a-z0-9-` slug of free text, bounded on a word boundary. */
+const subjectSlug = (text) => truncateOnBoundary(kebabCase(String(text ?? '')), SUBJECT_SLUG_MAX);
/**
* The durable dedup key for one goal-fidelity finding.
@@ -156,37 +155,36 @@ export function goalFidelityFingerprint(task) {
}
/**
- * The exact string a duplicate search looks for in an existing issue.
+ * The exact string the dedup looks for in an existing issue's body.
*
- * A single hyphenated token with no colons, spaces, or quotes: every forge's
- * full-text search treats `:` as a qualifier separator, so the raw
- * `goal-fidelity:user:…` fingerprint would be parsed as a query rather than
- * matched as text — and on GitHub an unknown qualifier fails the whole search.
- * The `portosgf-` prefix keeps it from colliding with ordinary prose.
+ * The CANDIDATES come from a label filter, not a text search — every issue this
+ * feature files carries `GOAL_FIDELITY_ISSUE_LABEL`, so the filer lists that
+ * label across every state and reads the marker back from the rows. A
+ * full-text search would have been index-backed (minutes of lag on GitHub and
+ * JIRA), which is exactly the window in which a scheduled task re-runs; a label
+ * is a direct field filter with no such lag.
*
- * The search is only a NARROWING step. Every forge tokenizes on hyphens too, so
- * a search hit is a candidate; `issueMatchesGoalFidelityMarker` decides, by
- * substring, on the text the forge actually returned.
+ * Still a single hyphenated token with no colons, spaces, or quotes: it rides
+ * inside a JIRA JQL string literal, and the raw `goal-fidelity:user:…`
+ * fingerprint would need escaping there for no gain. The `portosgf-` prefix
+ * keeps it from colliding with ordinary prose.
*/
export function goalFidelityIssueMarker(fingerprint) {
- const token = String(fingerprint ?? '')
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '');
- return `portosgf-${token}`;
+ return `portosgf-${kebabCase(String(fingerprint ?? ''))}`;
}
/**
* Does this issue carry our marker for `fingerprint`?
*
- * Reads `body` or `description` because the three trackers spell the same field
- * two ways (`gh`/`glab` normalize to `body`; JIRA returns `description`), and a
- * dedup that silently looked at the wrong one would read every existing issue
- * as a non-match and re-file on every run.
+ * Takes the ONE normalized `{ title, body }` shape every candidate source in
+ * `services/goalFidelityFollowUp.js` maps to — the trackers disagree about the
+ * field names (`description` on glab and JIRA, `summary` for a JIRA title), and
+ * accepting every spelling here would let a mapper quietly stop normalizing
+ * without anything failing.
*/
export function issueMatchesGoalFidelityMarker(issue, fingerprint) {
const marker = goalFidelityIssueMarker(fingerprint);
- return `${issue?.title || ''}\n${issue?.summary || ''}\n${issue?.body || ''}\n${issue?.description || ''}`.includes(marker);
+ return `${issue?.title || ''}\n${issue?.body || ''}`.includes(marker);
}
/** Bounded markdown bullet list, or a fallback sentence when the list is empty. */
@@ -198,6 +196,9 @@ function bulletList(items, empty) {
}
const truncate = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
+const truncateTitle = (text, max) => (text.length > max
+ ? `${text.slice(0, text.lastIndexOf(' ', max - 1) > max / 2 ? text.lastIndexOf(' ', max - 1) : max - 1)}…`
+ : text);
/**
* Compose the issue this finding files.
@@ -214,7 +215,7 @@ const truncate = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}
*/
export function buildGoalFidelityIssue({ task, review, fingerprint }) {
const subject = firstLine(task?.description) || 'a CoS agent task';
- const title = truncate(`Goal-fidelity ${review?.verdict || 'finding'}: ${subject}`, GOAL_FIDELITY_ISSUE_LIMITS.titleChars);
+ const title = truncateTitle(`Goal-fidelity ${review?.verdict || 'finding'}: ${subject}`, GOAL_FIDELITY_ISSUE_LIMITS.titleChars);
// The marker sits in the SECOND paragraph, not the last: a reader of this
// issue gets it from a truncated body just as reliably as from a whole one,
// and the open-issue fallback scan reads bodies the forge lister has already
@@ -264,7 +265,11 @@ export function formatGoalFidelityFollowUpSummary(result) {
result?.issue && !result.issue.duplicate ? `filed ${result.issue.number ? `#${result.issue.number}` : 'an issue'}` : null,
result?.issueError ? `issue not filed (${result.issueError})` : null,
result?.task?.duplicate ? 'follow-up task already queued' : null,
- result?.task && !result.task.duplicate ? `queued follow-up task ${result.task.id}` : null,
+ // A HELD task is not a queued one — the loop policy stops it for a human,
+ // and saying "queued" about it is the one wrong thing to report.
+ result?.task && !result.task.duplicate
+ ? `${result.task.approvalRequired ? 'follow-up task awaiting approval' : 'queued follow-up task'} ${result.task.id}`
+ : null,
result?.taskError ? `follow-up task not queued (${result.taskError})` : null,
].filter(Boolean);
return parts.length ? `Goal-fidelity follow-up: ${parts.join('; ')}` : 'Goal-fidelity follow-up: nothing to do';
diff --git a/server/lib/goalFidelityFollowUp.test.js b/server/lib/goalFidelityFollowUp.test.js
index 16598eafeb..2e2fd23470 100644
--- a/server/lib/goalFidelityFollowUp.test.js
+++ b/server/lib/goalFidelityFollowUp.test.js
@@ -153,11 +153,14 @@ describe('issueMatchesGoalFidelityMarker', () => {
const fingerprint = 'goal-fidelity:user:comics/add-retry-caps';
const marker = goalFidelityIssueMarker(fingerprint);
- // `gh`/`glab` normalize to `body`; JIRA returns `description`. Reading only one
- // would silently treat every existing ticket as a non-match on the other forge.
- it('reads the body OR the description, because the trackers disagree on the field', () => {
+ // The filer normalizes every tracker's rows to `{ title, body }` before the
+ // matcher sees them, so this reads exactly that shape. Accepting JIRA's raw
+ // `description` here too would let a mapper quietly stop normalizing without
+ // anything failing.
+ it('reads the normalized title and body, and only those', () => {
expect(issueMatchesGoalFidelityMarker({ body: `text ${marker}` }, fingerprint)).toBe(true);
- expect(issueMatchesGoalFidelityMarker({ description: `text ${marker}` }, fingerprint)).toBe(true);
+ expect(issueMatchesGoalFidelityMarker({ title: `text ${marker}`, body: '' }, fingerprint)).toBe(true);
+ expect(issueMatchesGoalFidelityMarker({ description: `text ${marker}` }, fingerprint)).toBe(false);
});
it('does not match a different fingerprint or an unmarked issue', () => {
diff --git a/server/lib/textUtils.js b/server/lib/textUtils.js
index 9d20529f49..d156edc426 100644
--- a/server/lib/textUtils.js
+++ b/server/lib/textUtils.js
@@ -191,6 +191,18 @@ export function escapeRegExp(value) {
* empty string rather than being coerced, so a caller distinguishes "nothing to
* slug" from a real slug without a separate guard.
*/
+/**
+ * First non-empty line of a string, trimmed.
+ *
+ * The CoS task-description headline: `generateTasksMarkdown` flattens a stored
+ * description to one line, so every comparison against a multi-line input has to
+ * normalize on the first line. Lives in this dependency-free leaf because the
+ * goal-fidelity follow-up needs the same headline for its dedup key and cannot
+ * import the task store (see server/AGENTS.md "Import scoping");
+ * `services/cosTaskStore.js` re-exports it at the address its callers already use.
+ */
+export const firstLine = (text) => String(text ?? '').split('\n').map(line => line.trim()).find(Boolean) || '';
+
export function kebabCase(text) {
if (typeof text !== 'string') return '';
return text
diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.js
index c0f8b6e8b1..806ea77f3b 100644
--- a/server/services/agentFinalization.goalFidelity.test.js
+++ b/server/services/agentFinalization.goalFidelity.test.js
@@ -412,12 +412,21 @@ describe('finalizeAgent — goal-fidelity gate', () => {
expect(completion().goalFidelity.followUp).toBeUndefined();
});
- // A ship verdict is still a verdict: the gate ran and cleared the run, so
- // the follow-up is asked and declines on the trigger, not skipped here.
- it('is consulted on a clean verdict too, and stays silent', async () => {
+ // No trigger fires on `ship`, so the overwhelmingly common verdict must not
+ // even resolve the follow-up's module graph (the apps roster, both forge
+ // CLIs, the JIRA client) to be told there is nothing to act on.
+ it('is never consulted on a clean verdict', async () => {
runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'ship' }));
await finalize();
+ expect(runGoalFidelityFollowUpMock).not.toHaveBeenCalled();
+ expect(completion().success).toBe(true);
+ });
+
+ it('is consulted on the advisory fix-first verdict, which a wider trigger acts on', async () => {
+ runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'fix-first' }));
+ await finalize();
expect(runGoalFidelityFollowUpMock).toHaveBeenCalled();
+ // fix-first is advisory — it records a finding without holding the run.
expect(completion().success).toBe(true);
});
});
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index d342dad2f2..abc3fa364b 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -49,7 +49,7 @@ import {
goalFidelityHoldsRun,
taskObjective,
} from '../lib/goalFidelity.js';
-import { formatGoalFidelityFollowUpSummary } from '../lib/goalFidelityFollowUp.js';
+import { formatGoalFidelityFollowUpSummary, goalFidelityFollowUpApplies } from '../lib/goalFidelityFollowUp.js';
import { getGoalFidelityConfig, runLocalGoalFidelityReview } from './codeReview.js';
import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';
import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
@@ -1197,8 +1197,10 @@ export async function finalizeAgent({
// finding on the project's own tracker and/or queues the run that fixes it.
// Lazily imported: the filer reaches the apps roster, both forge CLIs, and
// (for a JIRA-tracked app) the JIRA client, and a static edge would put all
- // of it on the closure of every suite that reaches finalization.
- if (fidelity.review) {
+ // of it on the closure of every suite that reaches finalization. Gated on the
+ // WIDEST trigger so a clean `ship` — the overwhelmingly common verdict — does
+ // not evaluate that graph just to be told there is nothing to act on.
+ if (goalFidelityFollowUpApplies(fidelity.review, 'any-finding')) {
const followUp = await import('./goalFidelityFollowUp.js')
.then(({ runGoalFidelityFollowUp }) => runGoalFidelityFollowUp({ agentId, task, review: fidelity.review }))
.catch(err => {
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 600b96044c..dd9ed30137 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -50,10 +50,7 @@ import {
normalizeGoalFidelityVerdict,
resolveGoalFidelityConfig,
} from '../lib/goalFidelity.js'
-import {
- DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
- GOAL_FIDELITY_FOLLOW_UP_TRIGGERS,
-} from '../lib/goalFidelityFollowUp.js'
+import { normalizeGoalFidelityFollowUpTrigger } from '../lib/goalFidelityFollowUp.js'
import { getSettings, settingsEvents } from './settings.js'
// LM Studio (`:1234`), Ollama (`:11434`) and MTPLX (`:8000/v1`) all ship
@@ -140,9 +137,7 @@ export function pickCodeReviewDefaults(settings) {
// asymmetry is deliberate and matches what the resolver does at runtime.
fileIssue: raw?.goalFidelity?.fileIssue === true,
queueTask: raw?.goalFidelity?.queueTask === true,
- followUpOn: GOAL_FIDELITY_FOLLOW_UP_TRIGGERS.includes(raw?.goalFidelity?.followUpOn)
- ? raw.goalFidelity.followUpOn
- : DEFAULT_GOAL_FIDELITY_FOLLOW_UP_TRIGGER,
+ followUpOn: normalizeGoalFidelityFollowUpTrigger(raw?.goalFidelity?.followUpOn),
},
// Faithful mirror of the stored scalars, deliberately NOT shape-checked here:
// `/api/code-review/local` passes these as a JSON request-body field where a
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 818b1e99a3..018ec0adce 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -36,10 +36,12 @@ import { buildQueuedTask } from './cosTaskIntake.js';
import { canChallenge, getChallengeCount, buildChallengePatch, buildChallengeResolutionPatch, classifyRecheckOutcome, MAX_CHALLENGES_PER_TASK } from './cosChallenge.js';
import { runLocalCodeReview, getCodeReviewDefaults } from './codeReview.js';
-// First non-empty line of a string. Used by addTask dedup: stored descriptions
-// are flattened to a single line by generateTasksMarkdown, so the comparison
-// must normalize on the first line to match multi-line inputs.
-export const firstLine = (s) => (s || '').split('\n').map(l => l.trim()).find(l => l) || '';
+// First non-empty line of a string — used by addTask's dedup, since stored
+// descriptions are flattened to a single line by generateTasksMarkdown. Declared
+// in the dependency-free text leaf and re-exported here at the address this
+// module's callers already import it from.
+import { firstLine } from '../lib/textUtils.js';
+export { firstLine };
const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);
diff --git a/server/services/goalFidelityFollowUp.js b/server/services/goalFidelityFollowUp.js
index ce4f658763..7f906acdb8 100644
--- a/server/services/goalFidelityFollowUp.js
+++ b/server/services/goalFidelityFollowUp.js
@@ -44,12 +44,10 @@
import { execGh, ensureForgeReachable } from './github.js';
import { execGlab, execGlabJson } from './gitlab.js';
import { resolveForgeExecOptions } from './forgeExecOptions.js';
-import { listAppIssues } from './appIssues.js';
-import { getAppById } from './apps.js';
-import { ROOT_DIR } from './cosState.js';
+import { PORTOS_APP_ID, getAppById } from './apps.js';
import { getSettings } from './settings.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
-import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { forgeCliForTracker, resolveAppForgeTarget } from '../lib/workTracker.js';
import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { boundedErrorMessage } from '../lib/errorHandler.js';
@@ -67,9 +65,7 @@ import {
resolveGoalFidelityFollowUp,
} from '../lib/goalFidelityFollowUp.js';
-/** Candidates a marker search may return before we substring-confirm them. */
-const SEARCH_LIMIT = 30;
-/** Page size for the open-issue rescan on GitLab and the JIRA marker search. */
+/** Page size for the label-filtered duplicate listing on every tracker. */
const PAGE_LIMIT = 100;
/**
@@ -89,84 +85,102 @@ const PAGE_LIMIT = 100;
const scrubForgeText = (value) => scrubSecretTokens(scrubHomePath(value));
/**
- * The repository this task's work lives in, as an app-record shape the forge
- * resolvers accept.
+ * The managed-app record whose tracker this finding belongs on.
*
- * A task with no `metadata.app` is PortOS's own work, which runs against the
- * install root — the same fallback `agentWorkspacePrep` uses to pick a
- * workspace, so the tracker this files to is the tracker the run touched.
+ * A task with no `metadata.app` is PortOS's own work — and that resolves to the
+ * REAL `PORTOS_APP_ID` record (always seeded by `loadApps`), not to a
+ * `{ repoPath: ROOT_DIR }` literal. The three fields a literal would drop are
+ * the three that decide where the issue lands: `workTracker` (an install that
+ * pinned PortOS to JIRA would otherwise get a GitHub issue nothing will ever
+ * claim), `forgeAccount` (the wrong credentials on a multi-account install),
+ * and `jira` (without it the JIRA arm is structurally unreachable for PortOS's
+ * own tasks).
*/
async function resolveFollowUpRepo(task) {
- const appId = task?.metadata?.app;
- if (!appId) return { id: null, name: 'PortOS', repoPath: ROOT_DIR, workTracker: 'auto' };
- const app = await getAppById(appId).catch(() => null);
- if (!app?.repoPath) return null;
- return app;
+ const app = await getAppById(task?.metadata?.app || PORTOS_APP_ID).catch(() => null);
+ return app?.repoPath ? app : null;
}
/**
- * GitHub: candidates carrying the marker, across OPEN and CLOSED.
+ * Everything a forge call for this app needs, resolved ONCE.
*
- * `--search` is a narrowing step whose ranking we do not trust — the caller
- * substring-confirms every row. Returns `null` for "could not read", which the
- * caller treats as a refusal to file rather than an absence of duplicates.
+ * `resolveForgeExecOptions` is neither cached nor cheap — it shells out for the
+ * origin remote, then `gh auth status` / `gh auth token`, plus `gh api user`
+ * when the app pins a forge account. Resolving it per call made the list and
+ * the create each pay for it; worse, the create ran with no options at all, so
+ * an app pinned to a non-ambient account filed (or 404'd) under the wrong
+ * login — the exact failure `resolveForgeExecOptions` exists to prevent.
+ *
+ * `glab` resolves its project from the working directory rather than a token
+ * overlay, so only GitHub passes a repo path here.
*/
-async function searchGithubMarker({ target, repoPath, forgeAccount, marker }) {
- const { cwd, env, customEnv } = await resolveForgeExecOptions(repoPath, { forgeAccount });
- const forge = await ensureForgeReachable('goal-fidelity-followup', {
- hostname: target.apiHost,
- ...(customEnv ? { env: customEnv } : {}),
- });
- if (!forge.ok) return null;
- const raw = await execGh([
- 'issue', 'list', '--repo', target.repoSpec, '--state', 'all',
- '--search', marker, '--limit', String(SEARCH_LIMIT),
- '--json', 'number,title,body,url,state',
- ], undefined, { cwd, env }).catch((err) => {
- console.error(`❌ goal-fidelity follow-up: gh marker search failed for ${target.repoSpec}: ${err.message}`);
- return null;
- });
- const rows = safeJSONParse(raw, null);
- return Array.isArray(rows) ? rows : null;
-}
+const resolveForgeContext = (app, tracker) => resolveForgeExecOptions(
+ tracker === 'github' ? app.repoPath : null,
+ { forgeAccount: app.forgeAccount },
+);
/**
- * GitLab: `glab issue list --all` is every STATE, not every page — the page cap
- * rides separately. glab has no reliable cross-version full-text issue search
- * flag, so this reads a bounded page and the caller substring-confirms; the
- * marker sits in the second paragraph of the body precisely so a capped read
- * still finds it.
- */
-async function searchGitlabMarker({ repoPath }) {
- const { rows } = await execGlabJson(['issue', 'list', '--all', '--per-page', String(PAGE_LIMIT)], repoPath);
- if (!Array.isArray(rows)) return null;
- return rows.map((row) => ({
- number: row?.iid ?? null,
- title: row?.title || '',
- body: row?.description || '',
- url: row?.web_url || '',
- state: row?.state || '',
- }));
-}
-
-/**
- * JIRA: a `text ~` marker match inside the app's own project. The project is
- * scoped explicitly — a marker search across every project the token can see
- * would dedupe one app's finding against another's.
+ * Every issue this feature has ever filed on this tracker, in one normalized
+ * `{ number, title, body, url }` shape — or `null` when the tracker could not
+ * be read.
+ *
+ * Filtered by LABEL across every STATE, which is what makes the dedup sound:
+ *
+ * - a label is a direct field filter, so unlike a full-text search it has no
+ * index lag — and the lag window (minutes, on both GitHub and JIRA) is
+ * exactly when a scheduled task re-runs and would re-file;
+ * - every state, so an issue a human already CLOSED is still found and not
+ * re-filed;
+ * - and it bounds the page by the thing we care about rather than by the
+ * tracker's whole backlog, so a busy repo cannot push our own issues off the
+ * end of the page and silently read as "nothing filed".
*
- * `jira.js` is imported lazily here and in the filer below: only a JIRA-tracked
- * app ever reaches it, and a static edge would put the whole JIRA client (and
- * its axios/client graph) on the closure of every suite that transitively
- * reaches agent finalization. See server/AGENTS.md "Import scoping".
+ * The three trackers disagree about field names (`iid` / `key`, `description`
+ * for the body, `summary` for a JIRA title). They are reconciled here, so the
+ * matcher and the result have one shape to read.
*/
-async function searchJiraMarker({ jira, marker }) {
+async function listFiledIssues({ app, target, tracker, exec }) {
+ if (tracker === 'github') {
+ const raw = await execGh([
+ 'issue', 'list', '--repo', target.repoSpec,
+ '--label', GOAL_FIDELITY_ISSUE_LABEL, '--state', 'all',
+ '--limit', String(PAGE_LIMIT), '--json', 'number,title,body,url',
+ ], undefined, { cwd: exec.cwd, env: exec.env }).catch((err) => {
+ console.error(`❌ goal-fidelity follow-up: gh issue list failed for ${target.repoSpec}: ${err.message}`);
+ return null;
+ });
+ const rows = safeJSONParse(raw, null);
+ return Array.isArray(rows) ? rows : null;
+ }
+
+ if (tracker === 'gitlab') {
+ // `--all` is every STATE, not every page — the page cap rides separately.
+ const { rows } = await execGlabJson(
+ ['issue', 'list', '--label', GOAL_FIDELITY_ISSUE_LABEL, '--all', '--per-page', String(PAGE_LIMIT)],
+ app.repoPath,
+ );
+ if (!Array.isArray(rows)) return null;
+ return rows.map((row) => ({
+ number: row?.iid ?? null,
+ title: row?.title || '',
+ body: row?.description || '',
+ url: row?.web_url || '',
+ }));
+ }
+
+ // JIRA. The project is scoped explicitly — a label match across every project
+ // the token can see would dedupe one app's finding against another's.
+ // `jira.js` is imported lazily here and in the creator: only a JIRA-tracked
+ // app reaches it, and a static edge would put the whole JIRA client graph on
+ // the closure of every suite reaching agent finalization (server/AGENTS.md
+ // "Import scoping").
const { searchIssues, escapeJql } = await import('./jira.js');
- const jql = `project = "${escapeJql(jira.projectKey)}" AND text ~ "${escapeJql(marker)}"`;
- const rows = await searchIssues(jira.instanceId, jql, {
+ const jql = `project = "${escapeJql(app.jira.projectKey)}" AND labels = "${escapeJql(GOAL_FIDELITY_ISSUE_LABEL)}"`;
+ const rows = await searchIssues(app.jira.instanceId, jql, {
fields: 'summary,description,status',
- maxResults: SEARCH_LIMIT,
+ maxResults: PAGE_LIMIT,
}).catch((err) => {
- console.error(`❌ goal-fidelity follow-up: JIRA marker search failed for ${jira.projectKey}: ${err.message}`);
+ console.error(`❌ goal-fidelity follow-up: JIRA issue search failed for ${app.jira.projectKey}: ${err.message}`);
return null;
});
if (!Array.isArray(rows)) return null;
@@ -175,69 +189,83 @@ async function searchJiraMarker({ jira, marker }) {
title: row?.summary || '',
body: row?.description || '',
url: row?.url || '',
- state: row?.status || '',
}));
}
/**
- * Every place a duplicate could already be, for one forge tracker: the marker
- * search (all states) and the open-issue list (index-lag backstop).
+ * Create the marker label, then the issue.
*
- * Returns `{ issue }` on a confirmed duplicate, `{ issue: null }` when both
- * reads answered and neither matched, and `{ error }` when a read we needed
- * could not be made. The three are distinct on purpose — collapsing the last
- * into the middle is how a blip files a duplicate.
- */
-async function findExistingForgeIssue({ app, target, tracker, fingerprint }) {
- const marker = goalFidelityIssueMarker(fingerprint);
- const candidates = tracker === 'github'
- ? await searchGithubMarker({
- target, repoPath: app.repoPath, forgeAccount: app.forgeAccount, marker,
- })
- : await searchGitlabMarker({ repoPath: app.repoPath });
- if (!candidates) return { error: `could not read the ${tracker} issue list` };
- const searchHit = candidates.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
- if (searchHit) return { issue: searchHit };
-
- // Index-lag backstop. GitHub's search index trails a creation by minutes, and
- // two runs of one schedule inside that window is ordinary traffic — without
- // this the second run files a duplicate the search genuinely could not see.
- // GitLab's page read above is already a direct listing, so it needs no rescan.
- if (tracker !== 'github') return { issue: null };
- const open = await listAppIssues(app);
- if (open.transient) return { error: `could not read the open ${tracker} issues (${open.reason})` };
- const openHit = open.issues.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
- return { issue: openHit || null };
-}
-
-/**
- * Create the marker label, then the issue. The label create is idempotent and
- * its failure is swallowed — both CLIs fail the whole `issue create` with a 422
- * on an undefined label, so a label we could not create resurfaces as the
- * create's own error if it actually mattered.
+ * The label create is idempotent and its failure is swallowed — both CLIs fail
+ * the whole `issue create` with a 422 on an undefined label, so a label we
+ * could not create resurfaces as the create's own error if it mattered.
*/
-async function createForgeIssue({ app, target, tracker, title, body }) {
- const cli = tracker === 'gitlab' ? 'glab' : 'gh';
+async function createForgeIssue({ app, target, tracker, exec, title, body }) {
+ const cli = forgeCliForTracker(tracker);
const spec = { name: GOAL_FIDELITY_ISSUE_LABEL, ...GOAL_FIDELITY_ISSUE_LABEL_SPEC };
await (cli === 'glab'
? execGlab(forgeLabelCreateArgs(cli, spec), app.repoPath)
- : execGh(forgeLabelCreateArgs(cli, spec, { repo: target.repoSpec }))).catch(() => null);
+ : execGh(forgeLabelCreateArgs(cli, spec, { repo: target.repoSpec }), undefined, { cwd: exec.cwd, env: exec.env })
+ ).catch(() => null);
const args = forgeIssueCreateArgs(cli, {
title, body, labels: [GOAL_FIDELITY_ISSUE_LABEL], repo: cli === 'glab' ? null : target.repoSpec,
});
return (cli === 'glab'
? execGlab(args, app.repoPath, undefined, { rejectOnError: true })
- : execGh(args)
+ : execGh(args, undefined, { cwd: exec.cwd, env: exec.env })
).then(
(stdout) => ({ ok: true, ...parseCreatedForgeIssue(stdout) }),
(error) => ({ ok: false, error: boundedErrorMessage(error, 'Issue creation failed') }),
);
}
+/**
+ * Create the JIRA ticket for one finding, in the same `{ ok, number, url }`
+ * shape. It carries the same marker label as its forge siblings — that label is
+ * what the next run's duplicate check filters on, so a ticket filed without it
+ * would be invisible to the dedup and re-filed every cadence.
+ */
+async function createJiraIssue({ app, title, body }) {
+ const { createTicket } = await import('./jira.js');
+ const created = await createTicket(app.jira.instanceId, {
+ projectKey: app.jira.projectKey,
+ summary: title,
+ description: body,
+ issueType: app.jira.defaultIssueType || 'Task',
+ labels: [GOAL_FIDELITY_ISSUE_LABEL],
+ }).catch((err) => ({ success: false, error: boundedErrorMessage(err, 'JIRA ticket creation failed') }));
+ return created?.success
+ ? { ok: true, number: created.ticketId, url: created.url }
+ : { ok: false, error: created?.error || 'JIRA ticket creation failed' };
+}
+
+/**
+ * Is this app's tracker one we can file to, and does it have what it needs?
+ * Returns the refusal sentence, or `null` when the file may proceed.
+ */
+function trackerRefusal({ app, target, tracker }) {
+ if (tracker === 'jira') {
+ const jira = app?.jira;
+ return jira?.enabled && jira.instanceId && jira.projectKey
+ ? null
+ : 'this project tracks work in JIRA, but its JIRA instance and project are not configured';
+ }
+ if (tracker !== 'github' && tracker !== 'gitlab') {
+ return `this project's work tracker is ${tracker || 'unresolved'}, which has no issue to file`;
+ }
+ if (!target || target.forge !== tracker) {
+ return `the ${tracker} tracker does not match this repository's remote`;
+ }
+ return null;
+}
+
/**
* File one goal-fidelity finding on the app's tracker.
*
+ * One flow for all three trackers, because the sequence is the same everywhere
+ * and the fail-closed rule is this feature's load-bearing invariant — stating
+ * it once means a later guard cannot land on two of the three.
+ *
* @returns {Promise<{issue: object|null, error: string|null}>} `issue` carries
* `duplicate: true` when an existing item already tracks this fingerprint —
* the queued task still wants that item's URL, so a duplicate is a usable
@@ -248,54 +276,42 @@ async function fileFollowUpIssue({ task, review, fingerprint }) {
if (!app) return { issue: null, error: `app '${task?.metadata?.app}' has no configured repository` };
const { tracker, target } = await resolveAppForgeTarget(app).catch(() => ({ tracker: null, target: null }));
- const { title, body } = buildGoalFidelityIssue({ task, review, fingerprint });
- // Scrubbed BEFORE the duplicate check, not just before the create: the text
- // that dedupes has to be the text that gets filed.
- const safeTitle = scrubForgeText(title);
- const safeBody = scrubForgeText(body);
+ const refusal = trackerRefusal({ app, target, tracker });
+ if (refusal) return { issue: null, error: refusal };
- if (tracker === 'jira') return fileJiraFollowUpIssue({ app, fingerprint, title: safeTitle, body: safeBody });
- if (tracker !== 'github' && tracker !== 'gitlab') {
- return { issue: null, error: `this project's work tracker is ${tracker || 'unresolved'}, which has no issue to file` };
- }
- if (!target || target.forge !== tracker) {
- return { issue: null, error: `the ${tracker} tracker does not match this repository's remote` };
+ const exec = tracker === 'jira' ? null : await resolveForgeContext(app, tracker);
+ // The reachability probe runs before anything is read or created: on an
+ // unreachable forge this is one failing call instead of a list and a label
+ // create that each have to time out first.
+ if (tracker === 'github') {
+ const forge = await ensureForgeReachable('goal-fidelity-followup', {
+ hostname: target.apiHost,
+ ...(exec.customEnv ? { env: exec.customEnv } : {}),
+ });
+ if (!forge.ok) return { issue: null, error: `GitHub is not reachable (${forge.status}); nothing was filed` };
}
- const existing = await findExistingForgeIssue({ app, target, tracker, fingerprint });
- if (existing.error) return { issue: null, error: `${existing.error}; nothing was filed` };
- if (existing.issue) {
- return { issue: { ...existing.issue, duplicate: true }, error: null };
- }
+ // Read before writing. A failed read must NOT read as "nothing is tracked" —
+ // that is exactly how a transient CLI blip files the same issue twice — so an
+ // unreadable tracker refuses the file rather than proceeding blind.
+ const existing = await listFiledIssues({ app, target, tracker, exec });
+ if (!existing) return { issue: null, error: `could not read the ${tracker} issue list to check for duplicates; nothing was filed` };
+ const duplicate = existing.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
+ if (duplicate) return { issue: { ...duplicate, duplicate: true }, error: null };
- const created = await createForgeIssue({ app, target, tracker, title: safeTitle, body: safeBody });
+ const { title, body } = buildGoalFidelityIssue({ task, review, fingerprint });
+ // Scrubbed on the way to the tracker: a filed issue is world-readable the
+ // moment it lands, and this text is model-authored prose derived from an
+ // untrusted diff. The marker itself is a slug of the task's first line and
+ // carries no path or credential shape, so the scrub leaves it intact — which
+ // it must, or the issue it files could never dedupe against itself.
+ const created = tracker === 'jira'
+ ? await createJiraIssue({ app, title: scrubForgeText(title), body: scrubForgeText(body) })
+ : await createForgeIssue({ app, target, tracker, exec, title: scrubForgeText(title), body: scrubForgeText(body) });
if (!created.ok) return { issue: null, error: created.error };
return { issue: { number: created.number, url: created.url, duplicate: false }, error: null };
}
-/** The JIRA arm of the same contract: same marker dedup, a ticket instead of an issue. */
-async function fileJiraFollowUpIssue({ app, fingerprint, title, body }) {
- const jira = app?.jira;
- if (!jira?.enabled || !jira.instanceId || !jira.projectKey) {
- return { issue: null, error: 'this project tracks work in JIRA, but its JIRA instance and project are not configured' };
- }
- const marker = goalFidelityIssueMarker(fingerprint);
- const candidates = await searchJiraMarker({ jira, marker });
- if (!candidates) return { issue: null, error: 'could not read the JIRA project to check for duplicates; nothing was filed' };
- const hit = candidates.find((issue) => issueMatchesGoalFidelityMarker(issue, fingerprint));
- if (hit) return { issue: { ...hit, duplicate: true }, error: null };
-
- const { createTicket } = await import('./jira.js');
- const created = await createTicket(jira.instanceId, {
- projectKey: jira.projectKey,
- summary: title,
- description: body,
- issueType: jira.defaultIssueType || 'Task',
- }).catch((err) => ({ success: false, error: boundedErrorMessage(err, 'JIRA ticket creation failed') }));
- if (!created?.success) return { issue: null, error: created?.error || 'JIRA ticket creation failed' };
- return { issue: { number: created.ticketId, url: created.url, duplicate: false }, error: null };
-}
-
/**
* Queue the CoS follow-up run.
*
@@ -306,6 +322,11 @@ async function fileJiraFollowUpIssue({ app, fingerprint, title, body }) {
* storm cannot mint one agent per failure), the loop policy (a cause we already
* queued a fix for and that came back is held for the human), and the
* worktree + PR delivery posture.
+ *
+ * The producer's approval verdict rides back out with the task: the loop policy
+ * can HOLD a follow-up for a human (`repeat-fingerprint`, `failure-storm`), and
+ * that is the case the user most needs named — reporting "queued" for a task
+ * 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 });
@@ -317,7 +338,7 @@ async function queueFollowUpTask({ task, review, fingerprint, issue }) {
context: `Auto-generated from a goal-fidelity ${review?.verdict} verdict`,
...(task?.metadata?.app ? { app: task.metadata.app } : {}),
});
- return filed?.task || null;
+ return filed?.task ? { ...filed.task, approvalRequired: filed.approvalRequired === true } : null;
}
/**
@@ -364,4 +385,3 @@ export async function runGoalFidelityFollowUp({ agentId, task, review }) {
return result;
}
-export const __testing = { resolveFollowUpRepo, findExistingForgeIssue };
diff --git a/server/services/goalFidelityFollowUp.test.js b/server/services/goalFidelityFollowUp.test.js
index cbf6c2b5e7..80917ed82a 100644
--- a/server/services/goalFidelityFollowUp.test.js
+++ b/server/services/goalFidelityFollowUp.test.js
@@ -5,9 +5,10 @@
*
* The failure this suite exists to catch is a DUPLICATE. The producer is an
* unattended loop, so an issue filed twice is filed forever — which is why
- * every tracker arm gets the same three cases: no existing issue (file), an
- * existing one carrying the marker (reuse, including a CLOSED one), and a
- * tracker we could not read (refuse, never file blind).
+ * every tracker arm gets the same three cases: nothing filed yet (file), an
+ * existing item carrying the marker (reuse, including a CLOSED one), and a
+ * tracker we could not read (refuse, never file blind). The listing is
+ * label-filtered across every state precisely so none of those can be missed.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
@@ -16,7 +17,6 @@ const execGh = vi.fn();
const execGlab = vi.fn();
const execGlabJson = vi.fn();
const ensureForgeReachable = vi.fn();
-const listAppIssues = vi.fn();
const getAppById = vi.fn();
const getSettings = vi.fn();
const fileInvestigationTask = vi.fn();
@@ -27,15 +27,16 @@ const createTicket = vi.fn();
vi.mock('./github.js', () => ({ execGh, ensureForgeReachable }));
vi.mock('./gitlab.js', () => ({ execGlab, execGlabJson }));
vi.mock('./forgeExecOptions.js', () => ({
- resolveForgeExecOptions: async () => ({ cwd: '/repo', env: {}, customEnv: null }),
+ resolveForgeExecOptions: async (repoPath) => ({ cwd: repoPath || undefined, env: { GH_TOKEN: 'synthetic' }, customEnv: null }),
}));
-vi.mock('./appIssues.js', () => ({ listAppIssues }));
-vi.mock('./apps.js', () => ({ getAppById }));
-vi.mock('./cosState.js', () => ({ ROOT_DIR: '/portos' }));
+vi.mock('./apps.js', () => ({ getAppById, PORTOS_APP_ID: 'portos' }));
vi.mock('./settings.js', () => ({ getSettings }));
vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask }));
vi.mock('./jira.js', () => ({ searchIssues, createTicket, escapeJql: (s) => String(s) }));
-vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget }));
+vi.mock('../lib/workTracker.js', () => ({
+ resolveAppForgeTarget,
+ forgeCliForTracker: (tracker) => (tracker === 'gitlab' ? 'glab' : 'gh'),
+}));
const { runGoalFidelityFollowUp } = await import('./goalFidelityFollowUp.js');
const { goalFidelityFingerprint, goalFidelityIssueMarker } = await import('../lib/goalFidelityFollowUp.js');
@@ -60,13 +61,17 @@ const run = () => runGoalFidelityFollowUp({ agentId: 'agent-1', task: TASK, revi
/** A `gh issue list --json` reply. */
const ghRows = (rows) => JSON.stringify(rows);
+/** The flag value `gh` was given for `name` on call `n`. */
+const ghFlag = (n, name) => {
+ const args = execGh.mock.calls[n][0];
+ return args[args.indexOf(name) + 1];
+};
beforeEach(() => {
vi.clearAllMocks();
ensureForgeReachable.mockResolvedValue({ ok: true });
getAppById.mockResolvedValue(GITHUB_APP);
resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target: GITHUB_TARGET });
- listAppIssues.mockResolvedValue({ transient: false, issues: [], reason: 'no-open-issues' });
execGh.mockResolvedValue(ghRows([]));
fileInvestigationTask.mockResolvedValue({ task: { id: 'cos-9' }, approvalRequired: false });
});
@@ -113,7 +118,7 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
it('files the issue with the marker label and reports its number', async () => {
settings({ fileIssue: true });
execGh
- .mockResolvedValueOnce(ghRows([])) // marker search
+ .mockResolvedValueOnce(ghRows([])) // duplicate listing
.mockResolvedValueOnce('') // label create
.mockResolvedValueOnce('https://github.com/acme/comics/issues/42');
const result = await run();
@@ -122,43 +127,32 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
expect(createArgs.slice(0, 2)).toEqual(['issue', 'create']);
expect(createArgs).toContain('--label');
expect(createArgs).toContain('goal-fidelity');
- // The body carries the key the next run's search reads back.
+ // The body carries the key the next run's listing reads back.
expect(createArgs[createArgs.indexOf('--body') + 1]).toContain(MARKER);
});
- // The whole feature's point of failure. A closed issue is still a filed
- // issue — re-filing it is exactly the "same issue over and over" loop.
- it('reuses an existing issue carrying the marker, even when it is CLOSED', async () => {
- settings({ fileIssue: true });
- execGh.mockResolvedValueOnce(ghRows([
- { number: 5, title: 'Goal-fidelity rethink: Add retry caps', body: `stuff ${MARKER}`, url: 'u5', state: 'CLOSED' },
- ]));
- const result = await run();
- expect(result.issue).toMatchObject({ number: 5, duplicate: true });
- expect(execGh).toHaveBeenCalledTimes(1); // searched, never created
- });
-
- it('searches every state, not just the open ones', async () => {
+ // The dedup lists by LABEL across every STATE rather than by full-text
+ // search: a label is a direct field filter with no index lag, and the lag
+ // window is exactly when a scheduled task re-runs.
+ it('lists by the marker label across every state', async () => {
settings({ fileIssue: true });
await run();
- const searchArgs = execGh.mock.calls[0][0];
- expect(searchArgs[searchArgs.indexOf('--state') + 1]).toBe('all');
- expect(searchArgs[searchArgs.indexOf('--search') + 1]).toBe(MARKER);
+ expect(execGh.mock.calls[0][0].slice(0, 2)).toEqual(['issue', 'list']);
+ expect(ghFlag(0, '--label')).toBe('goal-fidelity');
+ expect(ghFlag(0, '--state')).toBe('all');
+ expect(ghFlag(0, '--repo')).toBe('github.com/acme/comics');
});
- // The forge search index trails a creation by minutes; two runs of one
- // schedule inside that window are ordinary, and without the rescan the
- // second files a duplicate the search genuinely could not see.
- it('catches a just-filed issue the search index has not indexed yet', async () => {
+ // A closed issue is still a filed issue — re-filing it is exactly the "same
+ // issue over and over" loop this feature has to avoid.
+ it('reuses an existing issue carrying the marker, even when it is CLOSED', async () => {
settings({ fileIssue: true });
- execGh.mockResolvedValueOnce(ghRows([])); // search: index lag, no hit
- listAppIssues.mockResolvedValue({
- transient: false,
- issues: [{ number: 6, title: 't', body: `fresh ${MARKER}`, url: 'u6' }],
- });
+ execGh.mockResolvedValueOnce(ghRows([
+ { number: 5, title: 'Goal-fidelity rethink: Add retry caps', body: `stuff ${MARKER}`, url: 'u5' },
+ ]));
const result = await run();
- expect(result.issue).toMatchObject({ number: 6, duplicate: true });
- expect(execGh).toHaveBeenCalledTimes(1);
+ expect(result.issue).toMatchObject({ number: 5, duplicate: true });
+ expect(execGh).toHaveBeenCalledTimes(1); // listed, never created
});
it("does not match another finding's marker", async () => {
@@ -173,7 +167,7 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
// Fail-CLOSED, against the usual sentinel convention: a tracker we could not
// read is not "nothing is filed". Filing blind is how a `gh` blip duplicates.
- it('refuses to file when the marker search could not be read', async () => {
+ it('refuses to file when the listing could not be read', async () => {
settings({ fileIssue: true });
execGh.mockResolvedValueOnce('not json');
const result = await run();
@@ -182,22 +176,13 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
expect(execGh).toHaveBeenCalledTimes(1);
});
- it('refuses to file when the open-issue rescan is transient', async () => {
- settings({ fileIssue: true });
- execGh.mockResolvedValueOnce(ghRows([]));
- listAppIssues.mockResolvedValue({ transient: true, issues: [], reason: 'gh-offline' });
- const result = await run();
- expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/gh-offline/);
- expect(execGh).toHaveBeenCalledTimes(1);
- });
-
- it('refuses to file when the forge is unreachable', async () => {
+ it('refuses to file when the forge is unreachable, before reading or creating anything', async () => {
settings({ fileIssue: true });
ensureForgeReachable.mockResolvedValue({ ok: false, status: 'offline' });
const result = await run();
expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/could not read/);
+ expect(result.issueError).toMatch(/not reachable/);
+ expect(execGh).not.toHaveBeenCalled();
});
it('reports a failed create rather than claiming an issue exists', async () => {
@@ -210,6 +195,17 @@ describe('runGoalFidelityFollowUp — GitHub', () => {
expect(result.issue).toBeNull();
expect(result.issueError).toContain('422');
});
+
+ // An app pinned to a non-ambient forge account files under the wrong login
+ // without this — the 404 pattern `resolveForgeExecOptions` exists to prevent.
+ it('runs the create under the same resolved forge credentials as the listing', async () => {
+ settings({ fileIssue: true });
+ execGh.mockResolvedValueOnce(ghRows([])).mockResolvedValueOnce('').mockResolvedValueOnce('u/1');
+ await run();
+ for (const call of execGh.mock.calls) {
+ expect(call[2]).toMatchObject({ cwd: '/repo', env: { GH_TOKEN: 'synthetic' } });
+ }
+ });
});
describe('runGoalFidelityFollowUp — GitLab', () => {
@@ -218,27 +214,36 @@ describe('runGoalFidelityFollowUp — GitLab', () => {
tracker: 'gitlab',
target: { forge: 'gitlab', repoSpec: null, fullName: 'acme/comics' },
});
+ execGlabJson.mockResolvedValue({ rows: [], reason: 'ok' });
});
it('files through glab when no existing issue carries the marker', async () => {
settings({ fileIssue: true });
- execGlabJson.mockResolvedValue({ rows: [], reason: 'ok' });
execGlab.mockResolvedValueOnce('').mockResolvedValueOnce('https://gitlab.com/acme/comics/-/issues/8');
const result = await run();
expect(result.issue).toMatchObject({ number: 8, duplicate: false });
});
- // `--all` on `glab issue list` is every STATE, which is what makes a closed
- // duplicate visible at all.
- it('reads every state, so a closed issue still dedupes', async () => {
+ // An unfiltered page is the silent-duplicate bug: on a repo with more issues
+ // than the page holds, our own issue falls off the end and the dedup reports
+ // "nothing filed" every cadence. `--all` is every STATE, so a closed one
+ // still counts.
+ it('lists by the marker label across every state', async () => {
+ settings({ fileIssue: true });
+ await run();
+ const args = execGlabJson.mock.calls[0][0];
+ expect(args[args.indexOf('--label') + 1]).toBe('goal-fidelity');
+ expect(args).toContain('--all');
+ });
+
+ it('reuses an existing labelled issue rather than filing a second', async () => {
settings({ fileIssue: true });
execGlabJson.mockResolvedValue({
- rows: [{ iid: 3, title: 't', description: `x ${MARKER}`, web_url: 'u3', state: 'closed' }],
+ rows: [{ iid: 3, title: 't', description: `x ${MARKER}`, web_url: 'u3' }],
reason: 'ok',
});
const result = await run();
expect(result.issue).toMatchObject({ number: 3, duplicate: true });
- expect(execGlabJson.mock.calls[0][0]).toContain('--all');
expect(execGlab).not.toHaveBeenCalled();
});
@@ -261,21 +266,31 @@ describe('runGoalFidelityFollowUp — JIRA', () => {
beforeEach(() => {
getAppById.mockResolvedValue(JIRA_APP);
resolveAppForgeTarget.mockResolvedValue({ tracker: 'jira', target: null });
+ searchIssues.mockResolvedValue([]);
+ createTicket.mockResolvedValue({ success: true, ticketId: 'COM-12', url: 'https://jira/browse/COM-12' });
});
- it("creates a ticket in the app's project", async () => {
+ // The ticket must carry the marker LABEL as well as the body marker: the
+ // label is what the next run's duplicate listing filters on, so a ticket
+ // filed without it would be invisible to the dedup and re-filed every cadence.
+ it("creates a labelled ticket in the app's project", async () => {
settings({ fileIssue: true });
- searchIssues.mockResolvedValue([]);
- createTicket.mockResolvedValue({ success: true, ticketId: 'COM-12', url: 'https://jira/browse/COM-12' });
const result = await run();
expect(result.issue).toMatchObject({ number: 'COM-12', duplicate: false });
- expect(createTicket.mock.calls[0][1].projectKey).toBe('COM');
+ expect(createTicket.mock.calls[0][1]).toMatchObject({ projectKey: 'COM', labels: ['goal-fidelity'] });
expect(createTicket.mock.calls[0][1].description).toContain(MARKER);
});
- // JIRA returns the body as `description`, not `body` — a dedup that read only
- // `body` would treat every existing ticket as a non-match and re-file forever.
- it('dedupes on the description field JIRA actually returns', async () => {
+ it("scopes the label listing to the app's own project", async () => {
+ settings({ fileIssue: true });
+ await run();
+ expect(searchIssues.mock.calls[0][1]).toContain('project = "COM"');
+ expect(searchIssues.mock.calls[0][1]).toContain('labels = "goal-fidelity"');
+ });
+
+ // JIRA returns the body as `description`; the mapper normalizes it so the
+ // matcher has one shape to read.
+ it('dedupes on an existing ticket', async () => {
settings({ fileIssue: true });
searchIssues.mockResolvedValue([{ key: 'COM-4', summary: 't', description: `x ${MARKER}`, url: 'u' }]);
const result = await run();
@@ -283,21 +298,12 @@ describe('runGoalFidelityFollowUp — JIRA', () => {
expect(createTicket).not.toHaveBeenCalled();
});
- it("scopes the marker search to the app's own project", async () => {
- settings({ fileIssue: true });
- searchIssues.mockResolvedValue([]);
- createTicket.mockResolvedValue({ success: true, ticketId: 'COM-13', url: 'u' });
- await run();
- expect(searchIssues.mock.calls[0][1]).toContain('project = "COM"');
- expect(searchIssues.mock.calls[0][1]).toContain(MARKER);
- });
-
- it('refuses to file when the JIRA search failed', async () => {
+ it('refuses to file when the JIRA listing failed', async () => {
settings({ fileIssue: true });
searchIssues.mockRejectedValue(new Error('401'));
const result = await run();
expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/could not read the JIRA project/);
+ expect(result.issueError).toMatch(/could not read/);
expect(createTicket).not.toHaveBeenCalled();
});
@@ -332,16 +338,16 @@ describe('runGoalFidelityFollowUp — unfilable trackers', () => {
expect(result.issueError).toMatch(/no configured repository/);
});
- // A task with no `metadata.app` is PortOS's own work, which runs against the
- // install root — the same fallback that picks its workspace.
- it('falls back to the install root for a task with no app', async () => {
+ // PortOS's own tasks resolve to the REAL PortOS app record, not a fabricated
+ // one — the literal would drop `workTracker`, `forgeAccount` and `jira`, the
+ // three fields that decide which tracker the issue even lands on.
+ it("reads the real PortOS app record for a task with no app", async () => {
settings({ fileIssue: true });
execGh.mockResolvedValueOnce(ghRows([])).mockResolvedValueOnce('').mockResolvedValueOnce('u/1');
await runGoalFidelityFollowUp({
agentId: 'agent-1', task: { id: 't', taskType: 'user', description: 'Fix it' }, review: REVIEW,
});
- expect(getAppById).not.toHaveBeenCalled();
- expect(resolveAppForgeTarget.mock.calls[0][0].repoPath).toBe('/portos');
+ expect(getAppById).toHaveBeenCalledWith('portos');
});
});
@@ -349,7 +355,7 @@ describe('runGoalFidelityFollowUp — the queued task', () => {
it('queues through the shared investigation producer with the shared fingerprint', async () => {
settings({ queueTask: true });
const result = await run();
- expect(result.task).toEqual({ id: 'cos-9' });
+ expect(result.task).toMatchObject({ id: 'cos-9', approvalRequired: false });
const [args] = fileInvestigationTask.mock.calls[0];
expect(args.fingerprint).toBe(FINGERPRINT);
expect(args.affectedTasks).toEqual(['task-7']);
@@ -357,6 +363,15 @@ describe('runGoalFidelityFollowUp — the queued task', () => {
expect(execGh).not.toHaveBeenCalled(); // no issue filing was asked for
});
+ // 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 () => {
+ settings({ queueTask: true });
+ fileInvestigationTask.mockResolvedValue({ task: { id: 'cos-9' }, approvalRequired: true, loopReason: 'failure-storm' });
+ const result = await run();
+ expect(result.task.approvalRequired).toBe(true);
+ });
+
it('hands the filed issue to the queued task so it can claim it', async () => {
settings({ fileIssue: true, queueTask: true });
execGh
@@ -374,7 +389,7 @@ describe('runGoalFidelityFollowUp — the queued task', () => {
execGh.mockResolvedValueOnce('not json');
const result = await run();
expect(result.issueError).toBeTruthy();
- expect(result.task).toEqual({ id: 'cos-9' });
+ expect(result.task).toMatchObject({ id: 'cos-9' });
});
it('reports a suppressed queue rather than silently returning nothing', async () => {