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

persist the unattended-spawn hold in TASKS.md and version the PR content fingerprint (#7367)

[._.]/ Adam Eivya906962bc874
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 947b7cc46f..d74f441d08 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -153,7 +153,11 @@ export default function TaskItem({ task, agent = null, liveOutput, isSystem, spa
// registration ordering for why the two disagree.
const displayStatus = spawning ? 'in_progress' : task.status;
const idScope = isSystem ? 'sys' : 'user';
- const requiresApproval = isSystem && task.approvalRequired;
+ // Either queue. A USER row can hold too: a row the parser had to RECOVER is
+ // withheld from the unattended spawn and persists that hold in TASKS.md
+ // (#7300, #7367). Gating the button on `isSystem` would leave it pending with
+ // no way for the human it is waiting on to release it.
+ const requiresApproval = Boolean(task.approvalRequired);
// Name the hold's reason on the APPROVE button so "why is this one waiting on
// me?" is answerable without opening the body (#3714). Undefined for producers
// that stamp no reason, which leaves the button's plain label untouched.
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 0d5db21c56..43e0c83fbb 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -689,6 +689,25 @@ describe('TaskItem investigation approval hint (#3714)', () => {
expect(approve).toHaveAttribute('title', expect.stringContaining('last 24 hours'));
});
+ it('offers the approval action on a held USER task too, not just a system one', async () => {
+ // A user row the parser had to RECOVER is withheld from the unattended spawn
+ // and persists that hold in TASKS.md (#7300, #7367). Gating the button on
+ // `isSystem` left it pending with nothing able to release it.
+ const heldUser = { ...task, id: 'task-recovered', approvalRequired: true, metadata: {} };
+ api.approveCosTask.mockResolvedValue({ ...heldUser, approvalRequired: false });
+ const onRefresh = vi.fn();
+ render(<TaskItem task={heldUser} onRefresh={onRefresh} providers={providers} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Approve task task-recovered' }));
+ await waitFor(() => expect(api.approveCosTask).toHaveBeenCalledWith('task-recovered', { silent: true }));
+ expect(onRefresh).toHaveBeenCalled();
+ });
+
+ it('shows no approval action on an ordinary user task', () => {
+ render(<TaskItem task={{ ...task, id: 'task-plain', metadata: {} }} onRefresh={vi.fn()} providers={providers} />);
+ expect(screen.queryByRole('button', { name: /^Approve task/ })).not.toBeInTheDocument();
+ });
+
it('leaves the plain approve label on an approval-required task that is not a failure loop', () => {
const plain = { ...held, id: 'sys-approve-plain', metadata: {} };
render(<TaskItem task={plain} isSystem onRefresh={vi.fn()} providers={providers} />);
diff --git a/server/lib/README.md b/server/lib/README.md
index 35324a439c..0640335eed 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -155,6 +155,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `catalogTypes.js` | Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record `payloadSchemaVersion` + upgraders, per-type `defaultTags`. Also exports the relation-kind registry and the tag-taxonomy helpers (`canonicalTagKey`, `tagIdForKey`, `defaultTagsForType`). The client projects its UI registry from this one (`client/src/lib/catalogTypes.js`) rather than copying it. |
| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. |
| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
+| `aspectRatio.js` | Describe a pixel canvas as the ratio phrase a prompt can use — `aspectRatioTerms(w, h)` (bounded best rational approximation, so 1096x1536 reads as 5:7 rather than 137:192) and `aspectRatioPhrase(w, h)` → `"5:7 portrait"` / `"16:9 landscape"` / `"1:1 square"`. Use it wherever a prompt has to state a framing the canvas already fixes, so the sentence and the canvas cannot drift. Pure. |
| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
| `scriptVideoCompiler.js` | Compiles a scene script + bible into beat-level continuous-video clip specs (duration/frame-grid snapping, byte-stable descriptor injection, chain-length fresh-cut rule). |
| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
diff --git a/server/lib/aspectRatio.js b/server/lib/aspectRatio.js
new file mode 100644
index 0000000000..c867fcaaff
--- /dev/null
+++ b/server/lib/aspectRatio.js
@@ -0,0 +1,93 @@
+/**
+ * Describe a pixel canvas as the aspect ratio a human (or an image model) reads
+ * it as — "2:3 portrait", "5:7 portrait", "16:9 landscape", "1:1 square".
+ *
+ * Exists so a prompt that tells a model what shape to draw can be DERIVED from
+ * the canvas it will be rendered onto, rather than restated beside it. A
+ * hand-written ratio phrase is a second copy of the canvas size, and the two
+ * drift the moment one of them is tuned: the deck layout prompts said "2:3
+ * portrait" for months after the per-kind canvases moved to the true card trims
+ * (1096x1536 and 888x1536), so every card was asked for one framing and
+ * rendered at another.
+ *
+ * The reduction is a best rational approximation (continued fractions) bounded
+ * to small whole numbers, not a plain GCD: 1096:1536 reduces exactly to
+ * 137:192, which is arithmetically right and useless as a phrase. Bounded, it
+ * lands on 5:7 — the poker-card trim the canvas was chosen to approximate.
+ * A canvas that already reduces small (1024:1536) still reports its exact
+ * ratio, because the exact convergent is reached before the bound.
+ *
+ * Pure.
+ */
+
+// Largest value either side of the ratio may take. 24 is above every ratio a
+// real print/screen format uses (2:3, 5:7, 11:19, 16:9, 4:3, 21:9) and below
+// the point where a ratio stops reading as a shape.
+const DEFAULT_MAX_TERM = 24;
+
+const isPositiveSize = (value) => Number.isFinite(value) && value > 0;
+
+/**
+ * The smallest whole-number ratio within `maxTerm` that describes `width:height`.
+ * Returns `null` for a non-positive or non-finite edge.
+ *
+ * @returns {{ width: number, height: number }|null}
+ */
+export function aspectRatioTerms(width, height, { maxTerm = DEFAULT_MAX_TERM } = {}) {
+ if (!isPositiveSize(width) || !isPositiveSize(height)) return null;
+
+ // Continued-fraction expansion of width/height, keeping the last convergent
+ // whose terms both fit the bound. `previous` is the convergent before it, as
+ // the recurrence needs both. The seeds are the standard 1/0 and 0/1.
+ let value = width / height;
+ let previous = { width: 0, height: 1 };
+ let best = { width: 1, height: 0 };
+
+ // 40 terms is far past the point where a double's precision is meaningful;
+ // the bound below almost always ends the walk within a handful.
+ for (let step = 0; step < 40; step += 1) {
+ const whole = Math.floor(value);
+ const next = {
+ width: whole * best.width + previous.width,
+ height: whole * best.height + previous.height,
+ };
+ if (next.width > maxTerm || next.height > maxTerm) break;
+ previous = best;
+ best = next;
+ const remainder = value - whole;
+ // An exact convergent — no remainder left to expand.
+ if (remainder <= Number.EPSILON) break;
+ value = 1 / remainder;
+ }
+
+ // Only reachable when the first convergent already exceeds the bound (an
+ // extreme banner like 4096x64); fall back to the exact reduced ratio rather
+ // than reporting nothing.
+ if (best.width < 1 || best.height < 1) {
+ const divisor = greatestCommonDivisor(Math.round(width), Math.round(height));
+ return { width: Math.round(width) / divisor, height: Math.round(height) / divisor };
+ }
+ return best;
+}
+
+function greatestCommonDivisor(a, b) {
+ let x = Math.abs(a);
+ let y = Math.abs(b);
+ while (y) [x, y] = [y, x % y];
+ return x || 1;
+}
+
+/**
+ * The ratio phrase for a canvas — `"5:7 portrait"`, `"16:9 landscape"`,
+ * `"1:1 square"`. Empty string for a canvas that cannot be described, so a
+ * caller interpolating it into a prompt degrades to saying nothing about
+ * framing rather than to saying something false.
+ */
+export function aspectRatioPhrase(width, height, options) {
+ const terms = aspectRatioTerms(width, height, options);
+ if (!terms) return '';
+ const orientation = terms.width === terms.height ? 'square'
+ : terms.width < terms.height ? 'portrait'
+ : 'landscape';
+ return `${terms.width}:${terms.height} ${orientation}`;
+}
diff --git a/server/lib/aspectRatio.test.js b/server/lib/aspectRatio.test.js
new file mode 100644
index 0000000000..f6dd2861a3
--- /dev/null
+++ b/server/lib/aspectRatio.test.js
@@ -0,0 +1,52 @@
+import { describe, it, expect } from 'vitest';
+import { aspectRatioPhrase, aspectRatioTerms } from './aspectRatio.js';
+
+describe('aspectRatioTerms', () => {
+ it('reads a canvas as the small ratio it approximates, not its exact reduction', () => {
+ // The reason this is a continued-fraction approximation rather than a GCD:
+ // both deck canvases reduce exactly to numbers nobody can read as a shape
+ // (137:192 and 37:64), while the trims they were chosen for are 5:7 and
+ // 11:19. A phrase built from the exact reduction would be arithmetically
+ // right and useless in a prompt.
+ expect(aspectRatioTerms(1096, 1536)).toEqual({ width: 5, height: 7 });
+ expect(aspectRatioTerms(888, 1536)).toEqual({ width: 11, height: 19 });
+ });
+
+ it('reports an exactly-reducible canvas exactly', () => {
+ // The bound only ever stops the walk EARLY, so a ratio that is already
+ // small must survive it untouched — otherwise approximating would be a
+ // silent rounding of sizes that never needed it.
+ expect(aspectRatioTerms(1024, 1536)).toEqual({ width: 2, height: 3 });
+ expect(aspectRatioTerms(1920, 1080)).toEqual({ width: 16, height: 9 });
+ expect(aspectRatioTerms(1024, 1024)).toEqual({ width: 1, height: 1 });
+ });
+
+ it('falls back to the exact reduction when the first convergent already exceeds the bound', () => {
+ // An extreme banner has no small approximation at all. Reporting its true
+ // ratio beats reporting nothing, since the caller interpolates the result
+ // into a prompt.
+ expect(aspectRatioTerms(4096, 64)).toEqual({ width: 64, height: 1 });
+ });
+
+ it('returns null for a canvas that cannot be described', () => {
+ expect(aspectRatioTerms(0, 1536)).toBeNull();
+ expect(aspectRatioTerms(1024, 0)).toBeNull();
+ expect(aspectRatioTerms(Number.NaN, 1536)).toBeNull();
+ expect(aspectRatioTerms(undefined, undefined)).toBeNull();
+ });
+});
+
+describe('aspectRatioPhrase', () => {
+ it('names the orientation the ratio implies', () => {
+ expect(aspectRatioPhrase(1096, 1536)).toBe('5:7 portrait');
+ expect(aspectRatioPhrase(1920, 1080)).toBe('16:9 landscape');
+ expect(aspectRatioPhrase(1024, 1024)).toBe('1:1 square');
+ });
+
+ it('says nothing rather than something false about an undescribable canvas', () => {
+ // A caller interpolating this into a prompt drops the framing clause; it
+ // must never emit a ratio built from a missing or zero edge.
+ expect(aspectRatioPhrase(0, 1536)).toBe('');
+ expect(aspectRatioPhrase(null, null)).toBe('');
+ });
+});
diff --git a/server/lib/deckTemplates.js b/server/lib/deckTemplates.js
index 2cba46633f..9beff67abc 100644
--- a/server/lib/deckTemplates.js
+++ b/server/lib/deckTemplates.js
@@ -12,6 +12,7 @@
* `services/decks.js`.
*/
+import { aspectRatioPhrase } from './aspectRatio.js';
import { composeStyledPrompt } from './composeStyledPrompt.js';
import { buildVisualStyleClause, universeVisualStyleTokens } from './universeVisualStyle.js';
@@ -63,10 +64,23 @@ export const CARD_STATUS = Object.freeze({
// Per-kind layout clause. Every card of a deck shares it (editable on the deck)
// so the whole set reads as ONE physical object — same border, same index
// treatment — while the card prompt carries only the subject.
-export const DEFAULT_LAYOUT_PROMPT = Object.freeze({
- [DECK_KIND.PLAYING]: 'Complete playing-card face, 2:3 portrait, ornate decorative border, the rank and suit index drawn in the top-left and bottom-right corners, symmetrical composition',
- [DECK_KIND.TAROT]: 'Complete tarot card, 2:3 portrait, decorative framed border, the card title lettered in a banner along the bottom edge, symbolic centered composition',
-});
+//
+// The framing phrase is DERIVED from the kind's canvas, never written beside
+// it: these clauses kept telling the model "2:3 portrait" after the per-kind
+// sizes moved to each card's true trim (5:7 and 11:19), so the prompt and the
+// canvas disagreed about the shape being drawn. Deriving means changing a
+// canvas changes the sentence, and the two cannot drift apart again.
+const layoutClauseFor = {
+ [DECK_KIND.PLAYING]: (framing) => `Complete playing-card face, ${framing}, ornate decorative border, the rank and suit index drawn in the top-left and bottom-right corners, symmetrical composition`,
+ [DECK_KIND.TAROT]: (framing) => `Complete tarot card, ${framing}, decorative framed border, the card title lettered in a banner along the bottom edge, symbolic centered composition`,
+};
+
+export const DEFAULT_LAYOUT_PROMPT = Object.freeze(Object.fromEntries(
+ DECK_KINDS.map((kind) => {
+ const size = DECK_CARD_SIZE_BY_KIND[kind] || DECK_CARD_SIZE;
+ return [kind, layoutClauseFor[kind](aspectRatioPhrase(size.width, size.height))];
+ }),
+));
const PLAYING_SUITS = Object.freeze([
{ key: 'spades', name: 'Spades', symbol: '♠' },
diff --git a/server/lib/deckTemplates.test.js b/server/lib/deckTemplates.test.js
index 16bdc9321e..795086e7e1 100644
--- a/server/lib/deckTemplates.test.js
+++ b/server/lib/deckTemplates.test.js
@@ -1,7 +1,9 @@
import { describe, it, expect } from 'vitest';
import {
- CARD_STATUS, DECK_BACK_KEY, DECK_KIND, cardStatus, composeCardRenderPrompt, deckCardRoster, deckCompletion,
+ CARD_STATUS, DECK_BACK_KEY, DECK_CARD_SIZE_BY_KIND, DECK_KIND, DECK_KINDS, DEFAULT_LAYOUT_PROMPT,
+ cardStatus, composeCardRenderPrompt, deckCardRoster, deckCompletion,
} from './deckTemplates.js';
+import { aspectRatioPhrase } from './aspectRatio.js';
describe('deckCardRoster', () => {
it('mints a full playing deck (52 faces + 2 jokers + back) with unique keys', () => {
@@ -78,3 +80,24 @@ describe('cardStatus + deckCompletion', () => {
expect(deckCompletion([]).percent).toBe(0);
});
});
+
+describe('DEFAULT_LAYOUT_PROMPT', () => {
+ it('states the framing its own canvas actually renders at', () => {
+ // The defect this pins: both clauses said "2:3 portrait" while the per-kind
+ // canvases had moved to each card's true trim, so every deck asked the model
+ // for one shape and gave it another. Derived from DECK_CARD_SIZE_BY_KIND, a
+ // canvas change rewrites the sentence with it.
+ for (const kind of DECK_KINDS) {
+ const { width, height } = DECK_CARD_SIZE_BY_KIND[kind];
+ expect(DEFAULT_LAYOUT_PROMPT[kind]).toContain(aspectRatioPhrase(width, height));
+ }
+ expect(DEFAULT_LAYOUT_PROMPT[DECK_KIND.PLAYING]).toContain('5:7 portrait');
+ expect(DEFAULT_LAYOUT_PROMPT[DECK_KIND.TAROT]).toContain('11:19 portrait');
+ });
+
+ it('keeps a clause for every deck kind, with its kind-specific layout intact', () => {
+ expect(Object.keys(DEFAULT_LAYOUT_PROMPT).sort()).toEqual([...DECK_KINDS].sort());
+ expect(DEFAULT_LAYOUT_PROMPT[DECK_KIND.PLAYING]).toContain('rank and suit index');
+ expect(DEFAULT_LAYOUT_PROMPT[DECK_KIND.TAROT]).toContain('card title lettered in a banner');
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 3e589bb273..15846dac3e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -91,6 +91,7 @@ export * from './catalogTypes.js';
export * as catalogUniverseTags from './catalogUniverseTags.js';
export * from './canonPrompt.js';
export * from './comicScriptParser.js';
+export * from './aspectRatio.js';
export * from './composeStyledPrompt.js';
export * from './scriptVideoCompiler.js';
export * from './creativeDirectorPresets.js';
diff --git a/server/lib/prReviewContent.js b/server/lib/prReviewContent.js
index da809f3477..c9d6ec8f08 100644
--- a/server/lib/prReviewContent.js
+++ b/server/lib/prReviewContent.js
@@ -70,17 +70,107 @@ export function screenedPullRequestContent(pr, diff, commits = pr?.commits) {
}
/**
- * Stable identity for the exact PR content screened at a given head commit.
+ * The recipe version a fresh fingerprint is stamped with.
*
- * Null when the commit log is missing, rather than a fingerprint standing for a
- * smaller surface than the one that was stamped: a caller comparing against a
- * stamped value must fail closed, never match by omission.
+ * A fingerprint is only meaningful against the recipe that produced it, and
+ * PortOS is DISTRIBUTED software that persists these across upgrades: an
+ * approved PR waiting in the merge queue holds a stamp from whatever the
+ * install was running when the security scan ran. Adding the commit log (#7323)
+ * silently invalidated every one of them — the coordinator re-derived with the
+ * new recipe, got a mismatch, and dropped the approval with a console warning
+ * and no hand-back. It self-healed on the next scan, so the window was one
+ * cycle, but the drop was silent for it.
+ *
+ * So the version rides INSIDE the stamp (`"2:<sha256>"`) rather than beside it
+ * in a second field. The same lesson as the projection drift above: a field
+ * that travels separately gets dropped at a hop, and this value passes through
+ * a security report, a task's `metadata.issueWatcher`, and the install's
+ * `approvedPullRequests` state before it is compared.
+ *
+ * Changing `screenedPullRequestContent` means bumping this AND adding the
+ * outgoing recipe to `FINGERPRINT_RECIPES`, in the same commit.
*/
-export function screenedPullRequestFingerprint(pr, diff, commits = pr?.commits) {
- if (!Array.isArray(commits)) return null;
+export const SCREENED_PR_FINGERPRINT_VERSION = 2;
+
+/**
+ * Every recipe PortOS has ever stamped with, by version. A stamp names its own
+ * recipe, so an approval screened before an upgrade re-verifies against the
+ * guarantee that was actually made when it was screened — content unchanged
+ * since the scan — instead of mismatching on a definition it predates.
+ *
+ * This is not a weakening. The caller has already required `headRefOid` to
+ * equal the approved head, which pins the diff and the commit log; what a
+ * fingerprint adds is detection of the parts that CAN change at a fixed head
+ * (title, description). Every version checks those.
+ *
+ * A recipe returns null when the input it needs is missing, so a caller can
+ * never match by omission against a stamp that covered more.
+ */
+const FINGERPRINT_RECIPES = Object.freeze({
+ // v1 (pre-#7323): title + description + diff. Commit messages went unscreened.
+ 1: (pr, diff) => screenedPullRequestContent(pr, diff, []),
+ // v2 (#7323): + the commit log, so an instruction hidden in a commit body is
+ // both screened and watched for change.
+ 2: (pr, diff, commits) => (Array.isArray(commits) ? screenedPullRequestContent(pr, diff, commits) : null),
+});
+
+// A version with no recipe could only stamp fingerprints nothing can ever
+// verify, so the bump and the outgoing recipe have to land together. Checked at
+// module load, which every boot and every test run performs.
+const currentRecipe = FINGERPRINT_RECIPES[SCREENED_PR_FINGERPRINT_VERSION];
+if (!currentRecipe) throw new Error(`No screened-PR fingerprint recipe for version ${SCREENED_PR_FINGERPRINT_VERSION}`);
+
+// `<version>:<sha256>` for anything stamped since versioning; a bare sha256 is
+// a v1 stamp an install persisted before it.
+const VERSIONED_FINGERPRINT_RE = /^(\d{1,4}):([0-9a-f]{64})$/;
+const BARE_SHA256_RE = /^[0-9a-f]{64}$/;
+
+/** Is this a value `screenedPullRequestFingerprint` could have produced? */
+export function isScreenedPullRequestFingerprint(value) {
+ return parseFingerprint(value) !== null;
+}
+
+function parseFingerprint(value) {
+ if (typeof value !== 'string') return null;
+ const versioned = value.match(VERSIONED_FINGERPRINT_RE);
+ if (versioned) return { version: Number(versioned[1]), hash: versioned[2] };
+ return BARE_SHA256_RE.test(value) ? { version: 1, hash: value } : null;
+}
+
+function fingerprintHash(pr, content) {
+ if (typeof content !== 'string') return null;
return modelAbuseContentFingerprint(
'pull-request',
{ number: pr?.number, headSha: pr?.headRefOid },
- screenedPullRequestContent(pr, diff, commits),
+ content,
);
}
+
+/**
+ * Stable identity for the exact PR content screened at a given head commit,
+ * stamped with the recipe that produced it.
+ *
+ * Null when the commit log is missing, rather than a fingerprint standing for a
+ * smaller surface than the one that was stamped: a caller comparing against a
+ * stamped value must fail closed, never match by omission.
+ */
+export function screenedPullRequestFingerprint(pr, diff, commits = pr?.commits) {
+ const hash = fingerprintHash(pr, currentRecipe(pr, diff, commits));
+ return hash === null ? null : `${SCREENED_PR_FINGERPRINT_VERSION}:${hash}`;
+}
+
+/**
+ * Does `stamped` still describe this PR's screened content?
+ *
+ * The one comparison every consumer makes — never `screenedPullRequestFingerprint(...) === stamped`,
+ * which is exactly the check that fails closed on an approval stamped by the
+ * previous recipe. Fails closed on a missing, malformed, or unknown-recipe
+ * stamp (a state file written by a NEWER install than this one).
+ */
+export function screenedPullRequestFingerprintMatches(stamped, pr, diff, commits = pr?.commits) {
+ const parsed = parseFingerprint(stamped);
+ if (!parsed) return false;
+ const recipe = FINGERPRINT_RECIPES[parsed.version];
+ if (!recipe) return false;
+ return fingerprintHash(pr, recipe(pr, diff, commits)) === parsed.hash;
+}
diff --git a/server/lib/prReviewContent.test.js b/server/lib/prReviewContent.test.js
new file mode 100644
index 0000000000..c2dec3616e
--- /dev/null
+++ b/server/lib/prReviewContent.test.js
@@ -0,0 +1,99 @@
+import { describe, it, expect } from 'vitest';
+import {
+ SCREENED_PR_FINGERPRINT_VERSION,
+ isScreenedPullRequestFingerprint,
+ screenedPullRequestContent,
+ screenedPullRequestFingerprint,
+ screenedPullRequestFingerprintMatches,
+} from './prReviewContent.js';
+
+const PR = {
+ number: 7,
+ headRefOid: 'a'.repeat(40),
+ title: 'Fix the thing',
+ body: 'Closes #101.',
+};
+const DIFF = 'diff --git a/src/example.js b/src/example.js\n+const x = 1;\n';
+const COMMITS = [{ messageHeadline: 'fix the thing', messageBody: 'It was broken.' }];
+
+// A stamp an install persisted before the commit log joined the screened
+// content (#7323): the same hash, over the commit-less content, stored bare.
+// Built through the current builder so it cannot drift from the v1 recipe the
+// matcher keeps.
+const legacyStamp = (pr, diff) => screenedPullRequestFingerprint(pr, diff, []).split(':')[1];
+
+describe('screenedPullRequestFingerprint', () => {
+ it('stamps the recipe version into the fingerprint itself', () => {
+ // Beside it in a second field, the version is a projection that gets
+ // dropped at a hop — which is how the recipe and its consumers drifted in
+ // the first place. Inside the value, it travels wherever the value does.
+ const stamp = screenedPullRequestFingerprint(PR, DIFF, COMMITS);
+ expect(stamp).toMatch(new RegExp(`^${SCREENED_PR_FINGERPRINT_VERSION}:[0-9a-f]{64}$`));
+ });
+
+ it('fails closed when the commit log is missing', () => {
+ // Never a fingerprint standing for a smaller surface than the stamped one.
+ expect(screenedPullRequestFingerprint(PR, DIFF, undefined)).toBeNull();
+ expect(screenedPullRequestFingerprint(PR, DIFF, null)).toBeNull();
+ });
+});
+
+describe('screenedPullRequestFingerprintMatches', () => {
+ it('matches its own stamp, and rejects content that changed at the same head', () => {
+ const stamp = screenedPullRequestFingerprint(PR, DIFF, COMMITS);
+ expect(screenedPullRequestFingerprintMatches(stamp, PR, DIFF, COMMITS)).toBe(true);
+ // The parts a maintainer or contributor can change WITHOUT moving the head
+ // SHA — which is the whole reason a fingerprint exists on top of the SHA.
+ expect(screenedPullRequestFingerprintMatches(stamp, { ...PR, title: 'Something else' }, DIFF, COMMITS)).toBe(false);
+ expect(screenedPullRequestFingerprintMatches(stamp, { ...PR, body: 'Now says something else' }, DIFF, COMMITS)).toBe(false);
+ expect(screenedPullRequestFingerprintMatches(stamp, PR, `${DIFF}+const y = 2;\n`, COMMITS)).toBe(false);
+ expect(screenedPullRequestFingerprintMatches(stamp, PR, DIFF, [{ messageHeadline: 'rewritten' }])).toBe(false);
+ });
+
+ it('re-derives a stamp from an older recipe instead of mismatching it', () => {
+ // The reported defect: adding the commit log to the screened content made
+ // every persisted fingerprint unreachable, so an approved PR sitting in the
+ // merge queue when the install updated was dropped with a console warning
+ // and no hand-back. Verified against the recipe the stamp NAMES, the
+ // approval survives the upgrade.
+ const legacy = legacyStamp(PR, DIFF);
+ expect(isScreenedPullRequestFingerprint(legacy)).toBe(true);
+ expect(screenedPullRequestFingerprintMatches(legacy, PR, DIFF, COMMITS)).toBe(true);
+ // Still the guarantee that recipe actually made: content unchanged since
+ // the scan. A title edit at the same head still fails it.
+ expect(screenedPullRequestFingerprintMatches(legacy, { ...PR, title: 'Edited' }, DIFF, COMMITS)).toBe(false);
+ });
+
+ it('fails closed on a missing, malformed, or unknown-recipe stamp', () => {
+ expect(screenedPullRequestFingerprintMatches(null, PR, DIFF, COMMITS)).toBe(false);
+ expect(screenedPullRequestFingerprintMatches('', PR, DIFF, COMMITS)).toBe(false);
+ expect(screenedPullRequestFingerprintMatches('not-a-fingerprint', PR, DIFF, COMMITS)).toBe(false);
+ // A state file written by a NEWER install: this one has no recipe for it and
+ // must not fall back to one it does have.
+ expect(screenedPullRequestFingerprintMatches(`9999:${'b'.repeat(64)}`, PR, DIFF, COMMITS)).toBe(false);
+ });
+
+ it('will not match the current recipe by omitting the commit log', () => {
+ const stamp = screenedPullRequestFingerprint(PR, DIFF, COMMITS);
+ expect(screenedPullRequestFingerprintMatches(stamp, PR, DIFF, undefined)).toBe(false);
+ });
+});
+
+describe('isScreenedPullRequestFingerprint', () => {
+ it('accepts both stamp shapes and nothing else', () => {
+ expect(isScreenedPullRequestFingerprint(`2:${'a'.repeat(64)}`)).toBe(true);
+ expect(isScreenedPullRequestFingerprint('a'.repeat(64))).toBe(true);
+ expect(isScreenedPullRequestFingerprint('a'.repeat(63))).toBe(false);
+ expect(isScreenedPullRequestFingerprint(`2:${'A'.repeat(64)}`)).toBe(false);
+ expect(isScreenedPullRequestFingerprint(undefined)).toBe(false);
+ });
+});
+
+describe('screenedPullRequestContent', () => {
+ it('omits the commit block entirely when there are no commit messages', () => {
+ // What makes the v1 recipe expressible as "the same content with an empty
+ // commit list" rather than a second hand-written projection.
+ expect(screenedPullRequestContent(PR, DIFF, [])).not.toContain('Commit messages:');
+ expect(screenedPullRequestContent(PR, DIFF, COMMITS)).toContain('Commit messages:');
+ });
+});
diff --git a/server/lib/taskParser.js b/server/lib/taskParser.js
index 4d3647d79b..e5c120b093 100644
--- a/server/lib/taskParser.js
+++ b/server/lib/taskParser.js
@@ -189,19 +189,21 @@ function matchTaskLine(line) {
// withheld from `getAutoApprovedTasks` regardless of its id. This is the same
// hold the unknown-checkbox path takes, from the other side of the row.
//
- // An INTERNAL recovered row additionally lands in the approval queue, because
- // its split is ambiguous in a second way — the priority field could itself have
+ // A recovered row of EITHER kind lands in the approval queue, because its
+ // split is ambiguous in a second way — the priority field could itself have
// held a pipe ('UR|GENT', 'UR|AUTO' were both reachable), so which segment was
// the approval flag is a guess, and that flag gates an agent spawn.
//
- // A user-prefixed row claims no approval: the user file writes no flags, so the
- // claim would be erased by the next write and only strand the row in the
- // meantime (`approveTask` reads the internal file, and TaskItem hides Approve
- // for a user task). Its `autoApproved: false` is what the internal file's
- // write turns into an APPROVAL flag, so the hold survives there and evaporates
- // in the user file — which is exactly where it is not needed, since user tasks
- // are never dequeued autonomously. A strict match on either kind is untouched.
- approvalRequired: (recovery && isInternalTaskId(taskId)) || approvalFlag === 'APPROVAL',
+ // `approvalRequired` — not `autoApproved: false` alone — is what carries the
+ // hold, because it is the one signal BOTH files can write (`APPROVAL`). The
+ // hold used to be inferred on the user side and evaporate on the next write:
+ // the row healed into a strict row with no flag, and the read after that
+ // parsed it as auto-approved and spawned an agent from what #7300 established
+ // was prose. `autoApproved: false` cannot stand in for it there — every user
+ // task `buildQueuedTask` mints carries that value, so writing a flag for it
+ // would hold the entire user queue. A strict match on either kind is
+ // untouched.
+ approvalRequired: recovery || approvalFlag === 'APPROVAL',
autoApproved: !recovery && (withFlag ? approvalFlag === 'AUTO' : true),
description: description.trim(),
metadata: {}
@@ -417,9 +419,40 @@ function flattenDescription(task) {
return description.replace(/\r?\n/g, ' ');
}
+/**
+ * The `| AUTO |` / `| APPROVAL |` segment a task row carries, or `''`.
+ *
+ * The internal file uses the whole vocabulary: every task that carries an
+ * `autoApproved` at all states it, and a held one says APPROVAL.
+ *
+ * The user file carries ONLY the hold. `APPROVAL` when the row is withheld from
+ * the unattended spawn (#7300, #7367), nothing otherwise — so an ordinary user
+ * row keeps the flagless shape it has always had, and the hold stops being
+ * inferred from a recovery match that the very next write erases.
+ *
+ * Which is why the user side keys on `approvalRequired` and NOT on the
+ * internal side's wider `heldBack`: `buildQueuedTask` mints every user task
+ * with `autoApproved: false` (only an internal task is ever auto-approved in
+ * memory), so writing a flag for that value would hold the entire user queue on
+ * its first rewrite.
+ */
+function approvalFlagSegment(task, includeApprovalFlags) {
+ if (!includeApprovalFlags) return task.approvalRequired === true ? ' | APPROVAL' : '';
+ // `autoApproved === false` writes APPROVAL, not AUTO (#7300). A task that says
+ // it is not auto-approved must not be healed into a row the next read dequeues:
+ // APPROVAL is the only flag this format has that survives the round trip as a
+ // hold. An `undefined` autoApproved is NOT that claim — it stays on the old
+ // path so a task that never carried the field keeps its flagless row.
+ const heldBack = task.approvalRequired || task.autoApproved === false;
+ if (heldBack) return ' | APPROVAL';
+ return task.autoApproved !== undefined ? ' | AUTO' : '';
+}
+
/**
* Generate TASKS.md content from tasks array
- * @param {boolean} includeApprovalFlags - Whether to include AUTO/APPROVAL flags (for internal CoS tasks)
+ * @param {boolean} includeApprovalFlags - Whether to include the full AUTO/APPROVAL
+ * vocabulary (for internal CoS tasks). The user file writes only the APPROVAL
+ * hold — see `approvalFlagSegment`.
*/
export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {
// Repair BEFORE grouping: groupTasksByStatus buckets only the five known
@@ -452,15 +485,7 @@ export function generateTasksMarkdown(tasks, includeApprovalFlags = false) {
for (const task of sortByPriority(sectionTasks)) {
const checkbox = statusToCheckbox[task.status];
- // `autoApproved === false` writes APPROVAL, not AUTO (#7300). A task that says
- // it is not auto-approved must not be healed into a row the next read dequeues:
- // APPROVAL is the only flag this format has that survives the round trip as a
- // hold. An `undefined` autoApproved is NOT that claim — it stays on the old
- // path so a task that never carried the field keeps its flagless row.
- const heldBack = task.approvalRequired || task.autoApproved === false;
- const approvalFlag = includeApprovalFlags && (heldBack || task.autoApproved !== undefined)
- ? ` | ${heldBack ? 'APPROVAL' : 'AUTO'}`
- : '';
+ const approvalFlag = approvalFlagSegment(task, includeApprovalFlags);
lines.push(`- ${checkbox} #${task.id} | ${task.priority}${approvalFlag} | ${flattenDescription(task)}`);
// Add metadata (escape newlines in values for single-line storage).
diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.js
index d2abd1e0d9..7e4fcd4712 100644
--- a/server/lib/taskParser.test.js
+++ b/server/lib/taskParser.test.js
@@ -942,26 +942,46 @@ describe('unrepresentable status/priority never drops a task (#7239)', () => {
expect(getAutoApprovedTasks(reread)).toEqual([]);
});
- it('withholds a recovered USER row from the dequeue without claiming approval', () => {
+ it("carries a recovered USER row hold through the write that heals the file", () => {
// The payload survives, but the row is not handed to the spawn engine: the
// recovery patterns cannot tell a genuine legacy row from a sentence inside a
- // legacy description body (#7300). It claims no APPROVAL, because the user file
- // writes no flags — that claim would only strand the row until the next write.
+ // legacy description body (#7300).
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const [recovered] = parseTasksMarkdown('# Tasks\n\n## Pending\n- [ ] #task-C | URGENT | plain user row\n - prompt: payload\n');
warn.mockRestore();
expect(recovered.autoApproved).toBe(false);
- expect(recovered.approvalRequired).toBe(false);
+ expect(recovered.approvalRequired).toBe(true);
expect(getAutoApprovedTasks([recovered])).toEqual([]);
expect(recovered.metadata.prompt).toBe('payload');
- // The user file writes no approval flags, so the healed row is an ordinary
- // strict row again — exactly what it was before the corruption.
- const reread = parseTasksMarkdown(generateTasksMarkdown([recovered], false));
- expect(reread[0].autoApproved).toBe(true);
- expect(reread[0].approvalRequired).toBe(false);
+ // The reported defect (#7367): the healing write used to drop the row's
+ // priority to MEDIUM and emit no flag, so the row became an ordinary strict
+ // row and the NEXT read spawned an agent from it. The user file now writes
+ // the hold, so it survives the round trip.
+ const healed = generateTasksMarkdown([recovered], false);
+ expect(healed).toContain('- [ ] #task-C | MEDIUM | APPROVAL | plain user row');
+ const reread = parseTasksMarkdown(healed);
+ expect(reread[0].autoApproved).toBe(false);
+ expect(reread[0].approvalRequired).toBe(true);
expect(reread[0].priority).toBe('MEDIUM');
+ // And it is STABLE — a second write does not re-derive a different answer.
+ expect(generateTasksMarkdown(reread, false)).toBe(healed);
+ });
+
+ it('leaves an ordinary user row flagless, so the hold cannot swallow the queue', () => {
+ // `buildQueuedTask` mints EVERY user task with `autoApproved: false` (only an
+ // internal task is ever auto-approved in memory), so the user file keys its
+ // flag on `approvalRequired` alone. Keying it on `autoApproved === false`
+ // instead would stamp APPROVAL on every user row on its first rewrite and
+ // stall the whole user queue.
+ const markdown = generateTasksMarkdown([{
+ id: 'task-1', status: 'pending', priority: 'HIGH', priorityValue: 3,
+ description: 'ordinary user row', metadata: {}, approvalRequired: false, autoApproved: false,
+ }], false);
+ expect(markdown).toContain('- [ ] #task-1 | HIGH | ordinary user row');
+ expect(markdown).not.toContain('APPROVAL');
+ expect(parseTasksMarkdown(markdown)[0].autoApproved).toBe(true);
});
it('does not mint a runnable task from a task-shaped line inside a description body', () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 27ee8ecc2e..74a47a6cb8 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1519,7 +1519,8 @@ export async function init() {
// - 'added': fill open slots via dequeueNextTask, and (for user tasks) also
// fire tryImmediateSpawn so the just-added task starts instantly, bypassing
// the evaluation interval that's meant for system task generation.
- // - 'approved': a newly approved internal task can now spawn — re-run dequeue.
+ // - 'approved': a newly approved task can now spawn — re-run dequeue. Either
+ // queue: a user row withheld by the #7300 hold is released the same way.
// - 'unblocked': a blocked task flipped back to pending (revive/retry, #2614)
// is newly spawnable exactly like an approval — re-run dequeue.
// - 'requeued': an in_progress task flipped back to pending — a failed run's
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 8eb432a147..7df00fdb31 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -37,6 +37,7 @@ import { dirname, join } from 'path';
import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';
import { canQueueImprovementTasks, DEFAULT_STATE } from './cosState.js';
import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible, isUserTaskRunnableUnattended } from './cosDequeue.js';
+import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';
import {
createLocalEndpointSlotContext,
cloudSwarmThreadCapacity,
@@ -1291,7 +1292,17 @@ describe('cos.js source — priority + capacity invariants', () => {
expect(fnBody).toMatch(/if\s*\(\s*availableSlots\s*<=\s*0\s*\)/);
});
- it('user tier withholds a recovered row, in BOTH spawn engines (#7300)', () => {
+ // Parse a legacy row, write it back the way the USER queue writes it, and read
+ // the result — the approval flags a real row carries after one heal cycle.
+ const healedUserRow = (line) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const parsed = parseTasksMarkdown(`# Tasks\n\n## Pending\n${line}\n`);
+ const [healed] = parseTasksMarkdown(generateTasksMarkdown(parsed, false));
+ warn.mockRestore();
+ return { approvalRequired: healed.approvalRequired, autoApproved: healed.autoApproved };
+ };
+
+ it('user tier withholds a recovered row, in BOTH spawn engines (#7300, #7367)', () => {
// A user row parses auto-approved unless the parser took its RECOVERY path,
// which cannot tell a genuine legacy row from a task-shaped sentence inside a
// legacy multi-line description body. This tier otherwise spawns every pending
@@ -1303,6 +1314,12 @@ describe('cos.js source — priority + capacity invariants', () => {
onDemand: [],
user: [
{ ...task('task-note'), autoApproved: false },
+ // The same hold as it comes back OFF DISK. Round-tripped through the real
+ // writer and parser rather than hand-stamped, because the defect (#7367)
+ // was exactly there: the user file used to emit no flag, the recovered row
+ // healed into an ordinary strict row, and the next read spawned an agent
+ // from it. A hand-built fixture would have kept passing through all of it.
+ { ...task('task-healed'), ...healedUserRow('- [ ] #task-healed | URGENT | legacy user row') },
{ ...task('task-real'), autoApproved: true },
task('task-fieldless'),
],
diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.js
index e5893326a2..be7c912b38 100644
--- a/server/services/cosDequeue.js
+++ b/server/services/cosDequeue.js
@@ -187,10 +187,15 @@ export async function closeStolenIdleReviewCard(cardId, admittedTask) {
* `undefined` is NOT that claim — a task built without the field (most user rows)
* stays runnable, so this narrows nothing that was already running.
*
+ * `approvalRequired` is the same hold said the way the FILE can hold it: the user
+ * `TASKS.md` writes `| APPROVAL |` on a withheld row (#7367), which reads back as
+ * `approvalRequired: true` + `autoApproved: false`. Both are checked so the hold
+ * survives whichever half a producer or a peer merge happens to carry.
+ *
* Lives beside `isIdleTierEligible` for the same reason: both spawn engines run
* their own copy of the user tier, and anything the two must agree on belongs in
* ONE body rather than in a pair of blocks a grep test has to police.
*/
export function isUserTaskRunnableUnattended(task) {
- return task?.autoApproved !== false;
+ return task?.autoApproved !== false && task?.approvalRequired !== true;
}
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 16398e3ab6..818b1e99a3 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -1057,19 +1057,37 @@ export async function reorderTasks(taskIds) {
export async function approveTask(taskId, { now = Date.now() } = {}) {
return withStateLock(async () => {
const state = await loadState();
- const filePath = join(ROOT_DIR, state.config.cosTasksFile);
- if (!existsSync(filePath)) {
+ // Both queues, internal first. A USER row can hold too: a row the parser had
+ // to RECOVER is withheld from the unattended spawn and now persists that hold
+ // as `| APPROVAL |` (#7300, #7367). Without a release path here that row is a
+ // zombie — pending forever, with nothing in the product able to clear it —
+ // which is a worse outcome than the evaporating hold it replaced.
+ const queues = [
+ { taskType: 'internal', filePath: join(ROOT_DIR, state.config.cosTasksFile) },
+ { taskType: 'user', filePath: join(ROOT_DIR, state.config.userTasksFile) },
+ ].filter(({ filePath }) => existsSync(filePath));
+
+ if (queues.length === 0) {
return { error: 'CoS task file not found' };
}
- let tasks = await readTaskFile(filePath);
+ let found = null;
+ for (const queue of queues) {
+ const tasks = await readTaskFile(queue.filePath);
+ const taskIndex = tasks.findIndex(t => t.id === taskId);
+ if (taskIndex !== -1) {
+ found = { ...queue, tasks, taskIndex };
+ break;
+ }
+ }
- const taskIndex = tasks.findIndex(t => t.id === taskId);
- if (taskIndex === -1) {
+ if (!found) {
return { error: 'Task not found' };
}
+ const { taskType, filePath, tasks, taskIndex } = found;
+
if (!tasks[taskIndex].approvalRequired) {
return { error: 'Task does not require approval' };
}
@@ -1086,10 +1104,10 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {
};
// Write back to file
- const markdown = generateTasksMarkdown(tasks, true);
+ const markdown = generateTasksMarkdown(tasks, taskType === 'internal');
await writeTaskFile(filePath, markdown);
- cosEvents.emit('tasks:changed', { type: 'internal', action: 'approved', task: tasks[taskIndex] });
+ cosEvents.emit('tasks:changed', { type: taskType, action: 'approved', task: tasks[taskIndex] });
return tasks[taskIndex];
});
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 29e322c7d4..5f1653cd58 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -1749,6 +1749,30 @@ describe('cosTaskStore.approveTask', () => {
it('returns an error when the cos task file is missing', async () => {
expect((await approveTask('sys-x')).error).toBe('CoS task file not found');
});
+
+ it('releases a USER row the parser withheld, so the hold is not a zombie', async () => {
+ // A row the parser had to RECOVER is withheld from the unattended spawn and
+ // now persists that hold in TASKS.md (#7300, #7367). Nothing else in the
+ // product can clear it: `updateTask` carries the flags through untouched, so
+ // without this the row stays pending forever.
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ mock.files.set(USER_FILE, '# Tasks\n\n## Pending\n- [ ] #task-held | URGENT | legacy user row\n - prompt: payload\n');
+ mock.mtimes.set(USER_FILE, 1);
+
+ const held = (await getUserTasks()).tasks[0];
+ expect(held.approvalRequired).toBe(true);
+
+ const approved = await approveTask('task-held');
+ warn.mockRestore();
+
+ expect(approved.approvalRequired).toBe(false);
+ expect(approved.autoApproved).toBe(true);
+ expect(approved.metadata.prompt).toBe('payload');
+ expect(mock.events.some(e => e.name === 'tasks:changed' && e.payload.action === 'approved' && e.payload.type === 'user')).toBe(true);
+ // And the release is persisted: the rewritten row carries no hold.
+ __resetTaskCache();
+ expect((await getUserTasks()).tasks[0].approvalRequired).toBe(false);
+ });
});
// ─── Source-level regression guards (moved from cos.test.js) ───────────────
diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.js
index f940d4803b..c4e14acd45 100644
--- a/server/services/issueWatcher.js
+++ b/server/services/issueWatcher.js
@@ -31,7 +31,7 @@ import { mergePR, resolveForgeForRepo } from './git.js';
import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
import { normalizeEligibilityFacts } from './modelAbuseGuard.js';
import { issuePrerequisiteWaived, linkedIssueIntentFingerprint } from '../lib/modelAbuseGuard.js';
-import { screenedPullRequestFingerprint } from '../lib/prReviewContent.js';
+import { screenedPullRequestFingerprintMatches } from '../lib/prReviewContent.js';
import { trimTo } from '../lib/textUtils.js';
const IN_PROGRESS_LABEL_SPEC = dispatchLabelSpec(IN_PROGRESS_LABEL);
@@ -574,9 +574,10 @@ async function readPullRequest(ctx, number) {
// a fork's head branch actually lives, which is what lets the remediation
// agent's worktree attach to it at all (#6064). `assignees` keeps that
// assignment idempotent across scheduled sweeps. `commits` is part of the
- // screened content, so `screenedPullRequestFingerprint` cannot verify a PR
- // read without it — safe to ask for on a single PR, unlike the bulk listing
- // the preflight has to keep it out of (GraphQL node budget).
+ // screened content, so `screenedPullRequestFingerprintMatches` cannot verify
+ // a current-recipe stamp on a PR read without it — safe to ask for on a
+ // single PR, unlike the bulk listing the preflight has to keep it out of
+ // (GraphQL node budget).
'--json', 'id,number,title,body,url,state,isDraft,author,assignees,labels,commits,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,mergeable,mergeStateStatus,statusCheckRollup',
], ctx);
}
@@ -886,8 +887,7 @@ async function processPendingApprovals(app, ctx) {
if (
typeof approvedDiff !== 'string'
|| approvedDiff.length > MAX_DIFF_CHARS
- || !approval.contentFingerprint
- || screenedPullRequestFingerprint(pr, approvedDiff) !== approval.contentFingerprint
+ || !screenedPullRequestFingerprintMatches(approval.contentFingerprint, pr, approvedDiff)
) {
// A maintainer can edit the title/body or a contributor can replace the
// head after the review. An old approval is never enough to merge the
@@ -1271,7 +1271,7 @@ async function verifyScreenedPullRequest(ctx, raw, expectedPullRequests) {
// A PR description can change without changing its head SHA. Require the
// exact content screened before cognition, not merely the same revision,
// before any review, rebase, or merge action.
- if (!target.contentFingerprint || screenedPullRequestFingerprint(pr, diff) !== target.contentFingerprint) {
+ if (!screenedPullRequestFingerprintMatches(target.contentFingerprint, pr, diff)) {
// `pr` rides along so the notification can still link to it.
return { number, pr, reason: 'its content no longer matches what the security scan screened', notify: true };
}
diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.js
index 21d2d00ac3..aca39f2fdb 100644
--- a/server/services/issueWatcher.test.js
+++ b/server/services/issueWatcher.test.js
@@ -1046,6 +1046,42 @@ describe('processTaskOutput', () => {
}));
});
+ // An approval persisted before the screened content gained the commit log
+ // (#7323) carries a fingerprint the current recipe cannot reproduce. Compared
+ // against the current recipe alone, every one of them mismatched on the first
+ // tick after the update and the approval was dropped with a console warning
+ // and no hand-back — silent for the cycle it took the next scan to re-approve.
+ it('merges an approval stamped by an older fingerprint recipe instead of dropping it', async () => {
+ // The stamp a pre-#7323 install wrote: the same hash over the commit-less
+ // content, stored without a recipe version.
+ const legacyFingerprint = screenedPullRequestFingerprint(pullRequest(), DIFF, []).split(':')[1];
+ apps.set(APP.id, {
+ ...APP,
+ issueWatcherState: {
+ approvedPullRequests: [{
+ number: 7,
+ headSha: 'a'.repeat(40),
+ contentFingerprint: legacyFingerprint,
+ url: 'https://github.com/o/r/pull/7',
+ ciPolicy: 'skippable',
+ noChecksObserved: true,
+ rebaseRequired: false,
+ ticks: 0,
+ }],
+ },
+ });
+ mergePrMock.mockResolvedValue({ success: true });
+ installDefaultGhMock({
+ pr: pullRequest({ statusCheckRollup: [] }),
+ reviews: [[{ user: { login: 'owner' }, commit_id: 'a'.repeat(40), state: 'APPROVED' }]],
+ });
+
+ await buildTaskInput({ app: apps.get(APP.id) });
+
+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7);
+ expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([]);
+ });
+
it('bounds polling for an approved PR whose CI never settles', async () => {
const approval = {
number: 7,
diff --git a/server/services/prReviewerPipeline.js b/server/services/prReviewerPipeline.js
index bf99d15180..75fb53c846 100644
--- a/server/services/prReviewerPipeline.js
+++ b/server/services/prReviewerPipeline.js
@@ -19,7 +19,8 @@
* the spawn ladder and the gates around this one, never the scan itself.
*/
-import { MODEL_ABUSE_GUARD_ID, isSha256Hex, issuePrerequisiteWaived, normalizeEligibilityFacts } from '../lib/modelAbuseGuard.js';
+import { MODEL_ABUSE_GUARD_ID, issuePrerequisiteWaived, normalizeEligibilityFacts } from '../lib/modelAbuseGuard.js';
+import { isScreenedPullRequestFingerprint } from '../lib/prReviewContent.js';
import { PUBLIC_REVIEW_GATE_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';
import { PIPELINE_STAGE_BEHAVIOR_FLAGS } from '../lib/cosValidation.js';
import { createPrReviewerDefaultStages } from './taskScheduleRegistry.js';
@@ -447,7 +448,7 @@ function normalizedExpectedPullRequests(task) {
const pullRequests = [];
for (const item of expected.pullRequests) {
if (!Number.isInteger(item?.number) || item.number < 1 || seen.has(item.number)) return null;
- if (!HEAD_SHA_RE.test(item.headSha) || !isSha256Hex(item.contentFingerprint)) return null;
+ if (!HEAD_SHA_RE.test(item.headSha) || !isScreenedPullRequestFingerprint(item.contentFingerprint)) return null;
if (typeof item.authorLogin !== 'string' || !item.authorLogin.trim()) return null;
seen.add(item.number);
pullRequests.push({