Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Merge remote-tracking branch 'origin/main' into codex/fix-social-publish-terminal-evidence

Emre Sokullu3301e798d3f6
diff --cc src/chrome/src/agent/agent.js
index 7909437bf,02f0f2847..1ec46f5a7
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@@ -1946,15 -1717,111 +1954,119 @@@ export class Agent extends LoopDetecto
|| metadataDetails.incomplete === true
|| (this._workflowJobStoresMetadataRequirements(siteWorkflow)
&& guard.workflowMetadataRequirementsResolved !== true);
+ const replacementRecords = this._verifiedTextReplacements.get(tabId);
+ const replacementRecordValues = [...(replacementRecords instanceof Map
+ ? replacementRecords.values()
+ : (replacementRecords ? [replacementRecords] : []))];
+ // Proofs authorize a commit only for the task that verified them. Records
+ // survive run teardown, so without this a later run in the same tab could
+ // authorize a stale replacement it never verified. The match requires a
+ // nonempty token on both sides: two tokenless runs must never satisfy it
+ // (e.g. a persistent recorder failure must not collapse every task into
+ // one identity).
+ const activeTaskToken = this._taskTokens.get(tabId);
+ const activeTaskTokenValid = typeof activeTaskToken === 'string' && activeTaskToken.length > 0;
+ // Editor identity must be GitHub-specific (see _isGithubFileEditorRecord,
+ // shared with the refresh classifier so the two cannot drift): a bare
+ // contentEditable flag is not enough — any other contenteditable on the
+ // edit route could otherwise mint a commit while the real editor still
+ // holds stale content. Records store the live digest metadata, so legit
+ // flows always carry the linkage.
+ const githubEditorReplacements = replacementRecordValues
+ .filter(record => record?.ambiguous !== true
+ && activeTaskTokenValid
+ && record?.taskToken === activeTaskToken
+ && !!record?.expectedSha256
+ && !!record?.readbackSha256
+ && this._normalizeUrl(record.pageUrl || '') === this._normalizeUrl(pageUrl)
+ && this._isGithubFileEditorRecord(record));
+ const githubEditorPayloads = new Set(githubEditorReplacements
+ .map(record => `${record.expectedLength}:${record.expectedSha256}`));
+ const verifiedReplacement = githubEditorPayloads.size === 1
+ ? githubEditorReplacements.sort((left, right) => Number(right?.verifiedAt || 0) - Number(left?.verifiedAt || 0))[0]
+ : null;
+ const githubEditScope = siteWorkflow?.adapterName === 'github'
+ && siteWorkflow?.job?.id === 'edit-file-and-commit'
+ ? this._workflowGithubEditFileScope(pageUrl, metadataRequirements)
+ : null;
+ const commitMessageRequirement = metadataRequirements
+ .find(requirement => requirement?.field === 'commit_message');
+ // Verbatim requirement text: the digest gate must hash what was asked
+ // for, not its NFKC fold — otherwise an exact write is blocked while a
+ // normalized rewrite could commit different bytes. Mirrors the byte-exact
+ // path scope handling. Absent rawValue means verbatim equals normalized.
+ const expectedCommitMessage = commitMessageRequirement
+ ? String(commitMessageRequirement.rawValue ?? commitMessageRequirement.value ?? '')
+ : '';
+ // GitHub composes the commit as summary + "\n\n" + extended description
+ // across two dialog fields, so a multi-line request needs both parts
+ // proven exactly: the summary on a single-line (non-textarea) commit
+ // field and the body on the textarea description field. Tag roles keep
+ // swapped fields from authorizing. Single-line requests behave exactly
+ // as before (summary proof); multi-line requests without a blank
+ // separator cannot be composed exactly and stay shut, as does anything
+ // whose parts are missing. Comparisons are collision-resistant SHA-256
+ // (a 32-bit FNV-1a fingerprint collides practically); the sync helper
+ // matches _sha256Text and the gate stays synchronous.
+ const messageSplit = expectedCommitMessage.indexOf('\n');
+ const messageRest = messageSplit < 0 ? '' : expectedCommitMessage.slice(messageSplit + 1);
+ const expectedSummary = messageSplit < 0 ? expectedCommitMessage : expectedCommitMessage.slice(0, messageSplit);
+ const expectedBody = messageRest.startsWith('\n') ? messageRest.slice(1).replace(/\n+$/, '') : '';
+ const composableMessage = messageSplit < 0 || messageRest === '' || messageRest.startsWith('\n');
+ const expectedSummarySha256 = commitMessageRequirement
+ ? this._sha256TextSync(expectedSummary)
+ : '';
+ const expectedBodySha256 = composableMessage && expectedBody
+ ? this._sha256TextSync(expectedBody)
+ : '';
+ const commitFieldRecords = replacementRecordValues.filter(record => (
+ record?.ambiguous !== true
+ && activeTaskTokenValid
+ && record?.taskToken === activeTaskToken
+ && !!record?.readbackSha256
+ && this._normalizeUrl(record.pageUrl || '') === this._normalizeUrl(pageUrl)
+ && this._isGithubCommitMessageField(record?.fieldMeta)
+ ));
+ const summaryVerified = !!expectedSummarySha256 && commitFieldRecords.some(record => (
+ String(record?.fieldMeta?.tag || '').toLowerCase() !== 'textarea'
+ && record.expectedLength === expectedSummary.length
+ && record.expectedSha256 === expectedSummarySha256
+ ));
+ const bodyVerified = !expectedBody || (!!expectedBodySha256 && commitFieldRecords.some(record => (
+ String(record?.fieldMeta?.tag || '').toLowerCase() === 'textarea'
+ && record.expectedLength === expectedBody.length
+ && record.expectedSha256 === expectedBodySha256
+ )));
+ const commitMessageVerified = !commitMessageRequirement
+ || (composableMessage && summaryVerified && bodyVerified);
+ const githubFileCommit = !metadataIncomplete
+ && githubEditScope
+ && verifiedReplacement
+ && commitMessageVerified
+ ? {
+ ...githubEditScope,
+ expectedLength: verifiedReplacement.expectedLength,
+ expectedSha256: verifiedReplacement.expectedSha256,
+ commitMessageVerified,
+ // Chromium's contenteditable readback deterministically expands
+ // newline runs (see _contentEditableValueMatches), so a verified
+ // proof is not always byte-exact. Requiring byte-exact readback
+ // here would permanently block every newline-terminated file;
+ // record which notion of exactness authorized the binding instead.
+ // The byte-exact raw-blob check after the commit stays fail-closed.
+ readbackByteExact: verifiedReplacement.readbackLength === verifiedReplacement.expectedLength
+ && verifiedReplacement.readbackSha256 === verifiedReplacement.expectedSha256,
+ }
+ : null;
const verificationKind = this._workflowVerificationKind(siteWorkflow);
+ const preDispatchPublicationAccountIdentity = verificationKind === 'published_resource'
+ && ['twitter', 'bluesky'].includes(siteWorkflow.adapterName)
+ && detectedSubmit?.publicationAccountIdentityComplete === true
+ ? this._workflowSocialPublicationAccountIdentity(
+ siteWorkflow,
+ detectedSubmit.publicationAccountIdentity,
+ )
+ : '';
const normalizeOrderIdentities = values => [...new Set((Array.isArray(values) ? values : [])
.map(value => String(value || '').trim().toUpperCase())
.filter(value => /^[A-Z0-9][A-Z0-9-]{3,}$/.test(value)))];
@@@ -1996,13 -1863,7 +2108,14 @@@
metadataRequirements: metadataRequirements.map(requirement => ({ ...requirement })),
...(metadataIncomplete ? { metadataRequirementsIncomplete: true } : {}),
} : {}),
+ ...(verificationKind === 'published_resource'
+ && ['twitter', 'bluesky'].includes(siteWorkflow.adapterName)
+ ? {
+ preDispatchPublicationAccountIdentity,
+ preDispatchPublicationAccountIdentityComplete: !!preDispatchPublicationAccountIdentity,
+ }
+ : {}),
+ ...(githubFileCommit ? { githubFileCommit } : {}),
...(verificationKind === 'form_confirmation' ? {
formDocumentScope: this._workflowInventoryDocumentScope(tabId, pageUrl),
formIdentity: this._workflowFormOriginIdentity(pageUrl),
@@@ -2210,10 -2148,11 +2400,13 @@@
['arrival', ['arrival', 'to', 'destination', 'arrival station', 'varış', '到达站', '到着駅', '도착역']],
['passenger', ['passenger', 'traveller', 'traveler', 'yolcu', '乘客', '乗客', '승객']],
['seat_class', ['seat class', 'seat', 'class', 'berth', 'koltuk', '座位', '席', '좌석']],
+ ['account', ['account', 'profile', 'handle', 'username', 'publishing account', 'posting account']],
+ ['attachment', ['attachment', 'attachments', 'attach', 'attached', 'media', 'medias', 'image', 'images', 'photo', 'photos', 'picture', 'pictures', 'pic', 'pics', 'video', 'videos', 'clip', 'clips', 'file', 'files', 'pièce jointe', 'pièces jointes', 'médias', 'adjunto', 'adjuntos', 'medios', 'imagen', 'imágenes', 'foto', 'fotos', 'anexo', 'anexos', 'mídia', 'mídias', 'imagem', 'imagens', 'anhang', 'anhänge', 'medien', 'bild', 'bilder', 'allegato', 'allegati', 'immagine', 'immagini', 'ek', 'ekler', 'medya', 'görsel', 'resim', '添付', '添付ファイル', '画像', '写真', '動画', 'メディア', '첨부', '첨부파일', '이미지', '사진', '동영상', '미디어', '附件', '图片', '圖片', '照片', '相片', '视频', '視頻', '影片', '媒体', '媒體', 'вложение', 'вложения', 'медиа', 'изображение', 'изображения', 'фото', 'видео']],
['subject', ['subject', 'subject line', 'email subject', 'sujet', 'objet', 'asunto', 'assunto', 'betreff', 'oggetto', 'konu', '件名', '主题', '主旨']],
['body', ['body', 'post', 'post body', 'post text', 'composer']],
+ ['path', ['path', 'file path', 'repository path']],
+ ['branch', ['branch', 'git branch']],
+ ['commit_message', ['commit message', 'commit summary', 'commit title']],
['title', ['title', 'titre', 'título', 'titulo', 'titel', 'titolo', 'başlık', 'タイトル', '제목', '标题', '標題', 'название']],
];
const paddedText = ` ${text} `;
@@@ -2272,8 -2210,22 +2465,23 @@@
discarded += 1;
continue;
}
+ const maxLen = (field === 'body' || field === 'notes') ? 25000 : 10000;
- requirements.set(field, { field, value: this._workflowMetadataValue(value.value, maxLen) });
+ // Keep the byte-exact request text alongside the normalized value, but
+ // only when normalization changed something: Git paths preserve
+ // distinctions NFKC/trim fold (fullwidth A vs A, significant
+ // whitespace), and scope resolution must compare those. Absent means
+ // verbatim equals normalized, so existing shapes are untouched.
+ // Re-ingestion keeps an existing rawValue instead of re-deriving it
+ // from the already-normalized value.
- const normalizedValue = this._workflowMetadataValue(value.value);
++ const normalizedValue = this._workflowMetadataValue(value.value, maxLen);
+ const verbatimValue = typeof value.rawValue === 'string'
+ ? value.rawValue
+ : String(value.value ?? '');
+ requirements.set(field, {
+ field,
+ value: normalizedValue,
+ ...(verbatimValue !== normalizedValue ? { rawValue: verbatimValue } : {}),
+ });
}
return { items: [...requirements.values()], incomplete: discarded > 0 };
}
@@@ -20494,89 -19522,54 +21276,123 @@@ Rules: no prose intro, no conclusion, n
.map((link) => {
try { return new URL(link.getAttribute('href') || link.href || '', url).href; } catch { return ''; }
})
- .filter(value => /linkedin\.com\/(?:feed\/update|posts)\/|github\.com\/[^/]+\/[^/]+\/(?:releases\/tag\/|commit\/[0-9a-f]{7,40})|douyin\.com\/video\/\d+/i.test(value))
+ .filter((value) => {
+ try {
+ const parsed = new URL(value);
+ const resourceHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ const resourcePath = parsed.pathname.replace(/\/+$/, '') || '/';
+ return ((resourceHost === 'x.com' || resourceHost === 'twitter.com') && /^\/[^/]+\/status\/\d+$/i.test(resourcePath))
+ || (resourceHost === 'bsky.app' && /^\/profile\/[^/]+\/post\/[^/]+$/i.test(resourcePath))
+ || (resourceHost === 'linkedin.com' && /^\/(?:feed\/update\/[^/]+|posts\/[^/]+)$/i.test(resourcePath))
- || (resourceHost === 'github.com' && /^\/[^/]+\/[^/]+\/releases\/tag\/[^/]+$/i.test(resourcePath))
++ || (resourceHost === 'github.com' && /^\/[^/]+\/[^/]+\/(?:releases\/tag\/[^/]+|commit\/[0-9a-f]{7,40})$/i.test(resourcePath))
+ || (resourceHost === 'douyin.com' && /^\/video\/\d+$/i.test(resourcePath));
+ } catch {
+ return false;
+ }
+ })
.slice(0, 200);
} catch {
return [];
}
};
+ const publicationAccountEvidence = (submitTarget) => {
+ const siteHost = String(host || '').toLowerCase().replace(/^www\./, '');
+ const adapterName = siteHost === 'x.com' || siteHost === 'twitter.com'
+ ? 'twitter'
+ : siteHost === 'bsky.app'
+ ? 'bluesky'
+ : '';
+ if (!adapterName) return { identity: '', complete: false };
+ const accountFromHref = (href) => {
+ try {
+ const parsed = new URL(href || '', url);
+ const linkHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ const path = parsed.pathname.replace(/\/+$/, '') || '/';
+ if (adapterName === 'twitter' && (linkHost === 'x.com' || linkHost === 'twitter.com')) {
+ const handle = path.match(/^\/([A-Za-z0-9_]{1,15})$/)?.[1] || '';
+ const reserved = new Set(['home', 'explore', 'notifications', 'messages', 'search', 'settings', 'compose', 'i']);
+ return handle && !reserved.has(handle.toLowerCase()) ? `twitter:${handle.toLowerCase()}` : '';
+ }
+ if (adapterName === 'bluesky' && linkHost === 'bsky.app') {
+ const account = path.match(/^\/profile\/([^/]+)$/i)?.[1] || '';
+ return account ? `bluesky:${account.toLowerCase()}` : '';
+ }
+ } catch {}
+ return '';
+ };
+ const identitiesIn = (root, selector = 'a[href]') => {
+ if (!root?.querySelectorAll) return [];
+ return [...new Set(Array.from(root.querySelectorAll(selector))
+ .slice(0, 120)
+ .filter(isVisible)
+ .map(link => accountFromHref(link.getAttribute('href') || link.href || ''))
+ .filter(Boolean))];
+ };
+ if (adapterName === 'twitter') {
+ const profileNav = identitiesIn(doc, 'a[data-testid="AppTabBar_Profile_Link"][href]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
+ let node = submitTarget;
+ for (let depth = 0; node && depth < 10; depth++, node = node.parentElement) {
+ let hasEditor = false;
+ try {
+ hasEditor = !!node.querySelector?.('textarea,[contenteditable="true"],[role="textbox"]');
+ } catch {}
+ if (!hasEditor) continue;
+ const identities = identitiesIn(node);
+ if (identities.length === 1) return { identity: identities[0], complete: true };
+ if (identities.length > 1) break;
+ }
+ if (adapterName === 'bluesky') {
+ const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
+ return { identity: '', complete: false };
+ };
const transactionOrderSite = /(?:^|\.)12306\.cn$/i.test(host);
- const submitInfo = (form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitTarget = null) => {
+ const submitInfo = (form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitControl = null) => {
const formOrders = transactionOrderSite
? transactionOrderScan(form)
: { ids: [], complete: false };
const pageOrders = transactionOrderSite
? transactionOrderScan(doc.body || doc.documentElement)
: { ids: [], complete: false };
- const publicationAccount = publicationAccountEvidence(submitTarget);
++ const publicationAccount = publicationAccountEvidence(submitControl);
+ const formSummary = summarizeForm(form, pendingEl, pendingValue);
+ const control = labelControlFor(submitControl) || submitControl;
+ const controlLabel = compact(
+ control?.innerText || control?.textContent || control?.getAttribute?.('aria-label') || '',
+ 120,
+ );
+ const activeModal = findTopmostModal();
+ const controlInModal = !!(control && activeModal?.contains?.(control));
+ const githubEditPage = (() => {
+ try {
+ const parsed = new URL(url);
+ return parsed.hostname.toLowerCase().replace(/^www\./, '') === 'github.com'
+ && /^\/[^/]+\/[^/]+\/edit\//i.test(parsed.pathname);
+ } catch {
+ return false;
+ }
+ })();
+ // The launcher label is localized, so English text alone cannot
+ // identify it. A dialog-opening affordance is locale-independent: the
+ // launcher reversibly opens the commit dialog instead of submitting.
+ const controlOpensDialog = (() => {
+ try {
+ if (control?.hasAttribute?.('data-show-dialog-id')) return true;
+ const triggerAttrs = [
+ control?.getAttribute?.('aria-haspopup'),
+ control?.getAttribute?.('aria-controls'),
+ control?.getAttribute?.('data-show-dialog-id'),
+ control?.getAttribute?.('data-action'),
+ control?.getAttribute?.('data-target'),
+ ].filter(Boolean).join(' ');
+ return /dialog/i.test(triggerAttrs);
+ } catch {
+ return false;
+ }
+ })();
return {
isSubmit: true,
host,
@@@ -20590,11 -19581,10 +21406,14 @@@
transactionOrderIdsComplete: formOrders.complete,
transactionPageOrderIds: pageOrders.ids,
transactionPageOrderIdsComplete: pageOrders.complete,
+ githubCommitDialogLauncher: githubEditPage
+ && !controlInModal
+ && (/^commit changes(?:\.{3}|…)?$/i.test(controlLabel) || controlOpensDialog),
- ...summarizeForm(form, pendingEl, pendingValue),
+ ...formSummary,
+ summary: [
+ formSummary.summary,
+ publicationAccount.complete ? `Publishing account: ${publicationAccount.identity}.` : '',
+ ].filter(Boolean).join(' '),
};
};
const labelControlFor = (el) => {
@@@ -23562,7 -23305,7 +25346,7 @@@
'mode=active only when the user asks the agent to perform repeated item/action work that benefits from row tracking.',
'Exception: for siteContext.workflow.job="upload-release-assets" with requiresLedger=true, use mode=active and list every concrete requested target even when there is exactly one. Copy each exact requested filename or path into targets; do not merge or omit assets. When the user names the release tag, also return it as workflowFields=[{"field":"tag","value":"exact tag"}]; return workflowFields=[] when no tag is named.',
'For siteContext.workflow.job="update-metadata", workflowFields must contain every metadata field explicitly requested by the user and its complete exact intended value. Use canonical field names title, description, visibility, audience, tags, category, playlist, language, license, comments, embedding, paid_promotion, recording_date, or recording_location. Never infer a field or value from page content.',
- 'For siteContext.workflow.job="publish-release", "publish-post", or "publish-content", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value (for long post bodies or notes exceeding response budget, provide a short excerpt; complete bodies are preserved from task context). Use canonical field names tag, title, notes, body, visibility, or attachment; for publish-post only, also use account when the user explicitly names the publishing account. Never infer a field or value from page content.',
- 'For siteContext.workflow.job="publish-release", "publish-post", "publish-content", or "edit-file-and-commit", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value. Use canonical field names tag, title, notes, body, visibility, path, branch, or commit_message. For edit-file-and-commit, include path/branch/commit_message only when the user explicitly supplied them; the runtime separately binds the exact verified editor content. Never infer a field or value from page content.',
++ 'For siteContext.workflow.job="publish-release", "publish-post", "publish-content", or "edit-file-and-commit", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value (for long post bodies or notes exceeding response budget, provide a short excerpt; complete bodies are preserved from task context). Use canonical field names tag, title, notes, body, visibility, attachment, path, branch, or commit_message; for publish-post only, also use account when the user explicitly names the publishing account. For edit-file-and-commit, include path, branch, and commit_message only when the user explicitly supplied them; the runtime separately binds the exact verified editor content. Never infer a field or value from page content.',
'For siteContext.workflow.job="draft-email" or "send-email", workflowFields must contain every message field explicitly requested by the user and its complete exact intended value. Use canonical field names subject or body. Never infer a field or value from page content.',
'For siteContext.workflow.template="transaction", workflowFields must contain every booking detail explicitly requested by the user and its exact value. Use canonical field names train, travel_date, departure, arrival, passenger, or seat_class. Never infer a detail from page content.',
'For siteContext.workflow.template="form", workflowLabelValues must contain one entry per field the user supplied an exact value for, as {"label":"the field in the user\'s words","value":"the exact value"}. Return workflowLabelValues=[] when the user supplied no exact values, and never copy a value from page content.',
@@@ -29987,169 -29699,15 +31796,182 @@@
/success|saved|submitted|created|sent|published|complete|done|updated|added|approved|resolved/i.test(text)
&& !/\\b(?:not|never|failed|failure|error|unable|cannot|can't|could not|couldn't|did not|didn't|was not|wasn't|were not|weren't|invalid|denied|rejected|unsuccessful)\\b/i.test(text)
).slice(0, 5);
- const workflowResourceUrls = Array.from(document.querySelectorAll('a[href]'))
+ const publicationResourceIdentity = value => {
+ try {
+ const parsed = new URL(value, location.href);
+ const host = parsed.hostname.toLowerCase().replace(/^www\\./, '');
+ const path = parsed.pathname.replace(/\\/+$/, '') || '/';
+ const twitter = (host === 'x.com' || host === 'twitter.com')
+ ? path.match(/^\\/[^/]+\\/status\\/(\\d+)$/i)
+ : null;
+ if (twitter) return 'twitter:status:' + twitter[1];
+ if (host === 'bsky.app' && /^\\/profile\\/[^/]+\\/post\\/[^/]+$/i.test(path)) {
+ return 'bluesky:' + host + path.toLowerCase();
+ }
+ if (host === 'linkedin.com' && /^\\/(?:feed\\/update\\/[^/]+|posts\\/[^/]+)$/i.test(path)) {
+ return 'linkedin:' + host + path;
+ }
+ if (host === 'github.com' && /^\\/[^/]+\\/[^/]+\\/releases\\/tag\\/[^/]+$/i.test(path)) {
+ return 'github:' + host + path;
+ }
++ if (host === 'github.com' && /^\\/[^/]+\\/[^/]+\\/commit\\/[0-9a-f]{7,40}$/i.test(path)) {
++ return 'github:' + host + path;
++ }
+ if (host === 'douyin.com' && /^\\/video\\/\\d+$/i.test(path)) {
+ return 'douyin:' + host + path;
+ }
+ } catch {}
+ return '';
+ };
+ const workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
+ .slice(0, 2000)
+ .map(link => {
+ let url = '';
+ try { url = new URL(link.getAttribute('href') || link.href || '', location.href).href; } catch {}
+ return { link, url, identity: publicationResourceIdentity(url) };
+ })
+ .filter(item => !!item.identity);
- const workflowResourceUrls = Array.from(new Map(
- workflowResourceLinks.map(item => [item.identity, item.url]),
- ).values()).slice(0, 200);
++ // Commit pages expose changed files as blob links. They prove
++ // the commit's file scope without becoming published-resource
++ // records of their own.
++ const workflowBlobUrls = Array.from(document.querySelectorAll('a[href]'))
++ .slice(0, 2000)
+ .map(link => {
+ try { return new URL(link.getAttribute('href') || link.href || '', location.href).href; } catch { return ''; }
+ })
- // Blob links pin the changed-file list of an observed commit
- // page: raw-byte verification must only accept a path the
- // observed commit actually touched.
- .filter(url => /linkedin\\.com\\/(?:feed\\/update|posts)\\/|github\\.com\\/[^/]+\\/[^/]+\\/(?:releases\\/tag\\/|commit\\/[0-9a-f]{7,40}|blob\\/[0-9a-f]{7,40}\\/\\S+)|douyin\\.com\\/video\\/\\d+/i.test(url))
- .slice(0, 200);
++ .filter(value => /github\\.com\\/[^/]+\\/[^/]+\\/blob\\/[0-9a-f]{7,40}\\/\\S+/i.test(value));
++ const workflowResourceUrls = Array.from(new Map([
++ ...workflowResourceLinks.map(item => [item.identity, item.url]),
++ ...workflowBlobUrls.map(value => ['blob:' + value, value]),
++ ]).values()).slice(0, 200);
+ const workflowResourceRecordMap = new Map();
+ for (const { link, url, identity } of workflowResourceLinks) {
+ const record = publicationRecordRoot(link, identity, publicationResourceIdentity);
+ const best = record?.root || link;
+ const embedded = Array.isArray(record?.excluded) ? record.excluded : [];
+ const isEmbedded = node => embedded.some(entry => entry === node || entry.contains?.(node));
+ // innerText cannot be subtracted, so read it from every
+ // maximal subtree that holds no embedded post. A quote card's
+ // text never reaches the authored-body matcher this way.
+ const authoredText = (root) => {
+ if (!embedded.length) return String(root.innerText || '');
+ const parts = [];
+ const walk = (node) => {
+ if (isEmbedded(node)) return;
+ if (!embedded.some(entry => node.contains?.(entry))) {
+ parts.push(String(node.innerText || ''));
+ return;
+ }
+ for (const child of Array.from(node.childNodes || [])) {
+ if (child.nodeType === 3) parts.push(String(child.nodeValue || ''));
+ else if (child.nodeType === 1) walk(child);
+ }
+ };
+ walk(root);
+ return parts.join('\\n');
+ };
+ const normalizeLines = (value, limit) => String(value || '')
+ .replace(/\\r\\n?/g, '\\n')
+ .split('\\n')
+ .map(line => line.replace(/[^\\S\\n]+/g, ' ').trim())
+ .filter(Boolean)
+ .join('\\n')
+ .slice(0, limit);
+ const text = normalizeLines(authoredText(best), 5000);
+ // The app's own post-text elements, so a one-line requested
+ // body cannot be satisfied by the author name or timestamp
+ // the card also renders. Sized for X Premium long posts.
+ const authoredNodes = Array.isArray(record?.authored) ? record.authored : [];
+ const bodyText = authoredNodes.length
+ ? normalizeLines(authoredNodes.map(node => String(node.innerText || '')).join('\\n'), 25000)
+ : '';
+ const recordLinks = [
+ ...(best.matches?.('a[href]') ? [best] : []),
+ ...Array.from(best.querySelectorAll?.('a[href]') || []),
+ ].filter(candidate => !isEmbedded(candidate)).slice(0, 100).map(candidate => {
+ let href = '';
+ try { href = new URL(candidate.getAttribute('href') || candidate.href || '', location.href).href; } catch {}
+ const compact = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 1000);
+ let inAuthoredBody = false;
+ try {
+ inAuthoredBody = authoredNodes.some(node => node === candidate || node.contains?.(candidate));
+ } catch {}
+ return {
+ href: compact(href),
+ text: compact(candidate.innerText || candidate.textContent),
+ title: compact(candidate.getAttribute('title')),
+ ariaLabel: compact(candidate.getAttribute('aria-label')),
+ expandedUrl: compact(
+ candidate.getAttribute('data-expanded-url')
+ || candidate.getAttribute('data-full-url')
+ || candidate.getAttribute('data-url'),
+ ),
+ ...(inAuthoredBody ? { authored: true } : {}),
+ };
+ }).filter(candidate => candidate.href || candidate.text || candidate.expandedUrl);
+ const links = Array.from(new Map(recordLinks.map(candidate => [
+ [candidate.href, candidate.text, candidate.title, candidate.ariaLabel, candidate.expandedUrl, candidate.authored ? '1' : ''].join('\u0000'),
+ candidate,
+ ])).values()).slice(0, 24);
+ const mediaNodes = Array.isArray(record?.attachments) ? record.attachments : [];
+ const isAvatarOrEmoji = (node) => {
+ try {
+ if (node.closest?.('[data-testid*="Avatar"],[data-testid*="avatar"]')) return true;
+ if (node.closest?.('[data-testid="emoji"]') || node.classList?.contains?.('emoji')) return true;
+ const src = String(node.getAttribute?.('src') || node.src || '').toLowerCase();
+ if (src.includes('profile_images') || src.includes('/avatar/') || src.includes('/emoji/') || src.includes('twemoji')) return true;
+ const alt = String(node.getAttribute?.('alt') || '');
+ if (/^\\p{Emoji}+$/u.test(alt)) return true;
+ } catch {}
+ return false;
+ };
+ const isLinkPreview = (node) => {
+ try {
+ const cardContainer = node.closest?.('[data-testid*="card.layout"]');
+ if (!cardContainer) return false;
+ if (node.closest?.('[data-testid="tweetPhoto"],[data-testid^="postImage"]')) return false;
+ return true;
+ } catch {}
+ return false;
+ };
+ const filteredAttachments = Array.from(best.querySelectorAll?.(
+ 'img, video, [data-testid="tweetPhoto"], [data-testid="videoPlayer"], [data-testid="videoComponent"], [data-testid^="postImage"], [data-testid="postGalleryImage"], [data-testid="contentHider-post"], [data-testid="card.layoutLarge.media"]'
+ ) || []).filter(candidate => !isEmbedded(candidate) && !isAvatarOrEmoji(candidate) && !isLinkPreview(candidate));
+ const rawAttachments = mediaNodes.length
+ ? mediaNodes
+ : filteredAttachments.filter(node => !filteredAttachments.some(other => other !== node && other.contains?.(node)));
+ const attachments = rawAttachments.slice(0, 12).map(candidate => {
+ const tag = (candidate.tagName || '').toLowerCase();
+ const testId = typeof candidate.getAttribute === 'function' ? (candidate.getAttribute('data-testid') || '') : '';
+ const isVideo = tag === 'video' || /video/i.test(testId) || !!candidate.querySelector?.('video');
+ let src = '';
+ try {
+ src = candidate.getAttribute?.('src') || candidate.src
+ || candidate.querySelector?.('img, video, source')?.getAttribute?.('src')
+ || candidate.querySelector?.('img, video, source')?.src || '';
+ } catch {}
+ const alt = typeof candidate.getAttribute === 'function'
+ ? (candidate.getAttribute('alt') || candidate.getAttribute('aria-label')
+ || candidate.querySelector?.('img')?.getAttribute?.('alt') || '')
+ : '';
+ return {
+ type: isVideo ? 'video' : 'image',
+ src: String(src || '').slice(0, 500),
+ alt: String(alt || '').slice(0, 500),
+ };
+ });
+ const prior = workflowResourceRecordMap.get(identity);
+ if (!prior || text.length > prior.text.length || (!prior.attachments?.length && attachments.length)) {
+ workflowResourceRecordMap.set(identity, {
+ url,
+ text,
+ bodyText,
+ links,
+ attachments: attachments.length ? attachments : (prior?.attachments || []),
+ });
+ }
+ }
+ const workflowResourceRecords = Array.from(workflowResourceRecordMap.values()).slice(0, 40);
return {
openDialogCount: dialogs.length,
dialogTitles: dialogs.map(d => {
diff --cc src/firefox/src/agent/agent.js
index a68468d60,e80ae5c7d..9c0b893cc
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@@ -1660,15 -1432,111 +1669,119 @@@ export class Agent extends LoopDetecto
|| metadataDetails.incomplete === true
|| (this._workflowJobStoresMetadataRequirements(siteWorkflow)
&& guard.workflowMetadataRequirementsResolved !== true);
+ const replacementRecords = this._verifiedTextReplacements.get(tabId);
+ const replacementRecordValues = [...(replacementRecords instanceof Map
+ ? replacementRecords.values()
+ : (replacementRecords ? [replacementRecords] : []))];
+ // Proofs authorize a commit only for the task that verified them. Records
+ // survive run teardown, so without this a later run in the same tab could
+ // authorize a stale replacement it never verified. The match requires a
+ // nonempty token on both sides: two tokenless runs must never satisfy it
+ // (e.g. a persistent recorder failure must not collapse every task into
+ // one identity).
+ const activeTaskToken = this._taskTokens.get(tabId);
+ const activeTaskTokenValid = typeof activeTaskToken === 'string' && activeTaskToken.length > 0;
+ // Editor identity must be GitHub-specific (see _isGithubFileEditorRecord,
+ // shared with the refresh classifier so the two cannot drift): a bare
+ // contentEditable flag is not enough — any other contenteditable on the
+ // edit route could otherwise mint a commit while the real editor still
+ // holds stale content. Records store the live digest metadata, so legit
+ // flows always carry the linkage.
+ const githubEditorReplacements = replacementRecordValues
+ .filter(record => record?.ambiguous !== true
+ && activeTaskTokenValid
+ && record?.taskToken === activeTaskToken
+ && !!record?.expectedSha256
+ && !!record?.readbackSha256
+ && this._normalizeUrl(record.pageUrl || '') === this._normalizeUrl(pageUrl)
+ && this._isGithubFileEditorRecord(record));
+ const githubEditorPayloads = new Set(githubEditorReplacements
+ .map(record => `${record.expectedLength}:${record.expectedSha256}`));
+ const verifiedReplacement = githubEditorPayloads.size === 1
+ ? githubEditorReplacements.sort((left, right) => Number(right?.verifiedAt || 0) - Number(left?.verifiedAt || 0))[0]
+ : null;
+ const githubEditScope = siteWorkflow?.adapterName === 'github'
+ && siteWorkflow?.job?.id === 'edit-file-and-commit'
+ ? this._workflowGithubEditFileScope(pageUrl, metadataRequirements)
+ : null;
+ const commitMessageRequirement = metadataRequirements
+ .find(requirement => requirement?.field === 'commit_message');
+ // Verbatim requirement text: the digest gate must hash what was asked
+ // for, not its NFKC fold — otherwise an exact write is blocked while a
+ // normalized rewrite could commit different bytes. Mirrors the byte-exact
+ // path scope handling. Absent rawValue means verbatim equals normalized.
+ const expectedCommitMessage = commitMessageRequirement
+ ? String(commitMessageRequirement.rawValue ?? commitMessageRequirement.value ?? '')
+ : '';
+ // GitHub composes the commit as summary + "\n\n" + extended description
+ // across two dialog fields, so a multi-line request needs both parts
+ // proven exactly: the summary on a single-line (non-textarea) commit
+ // field and the body on the textarea description field. Tag roles keep
+ // swapped fields from authorizing. Single-line requests behave exactly
+ // as before (summary proof); multi-line requests without a blank
+ // separator cannot be composed exactly and stay shut, as does anything
+ // whose parts are missing. Comparisons are collision-resistant SHA-256
+ // (a 32-bit FNV-1a fingerprint collides practically); the sync helper
+ // matches _sha256Text and the gate stays synchronous.
+ const messageSplit = expectedCommitMessage.indexOf('\n');
+ const messageRest = messageSplit < 0 ? '' : expectedCommitMessage.slice(messageSplit + 1);
+ const expectedSummary = messageSplit < 0 ? expectedCommitMessage : expectedCommitMessage.slice(0, messageSplit);
+ const expectedBody = messageRest.startsWith('\n') ? messageRest.slice(1).replace(/\n+$/, '') : '';
+ const composableMessage = messageSplit < 0 || messageRest === '' || messageRest.startsWith('\n');
+ const expectedSummarySha256 = commitMessageRequirement
+ ? this._sha256TextSync(expectedSummary)
+ : '';
+ const expectedBodySha256 = composableMessage && expectedBody
+ ? this._sha256TextSync(expectedBody)
+ : '';
+ const commitFieldRecords = replacementRecordValues.filter(record => (
+ record?.ambiguous !== true
+ && activeTaskTokenValid
+ && record?.taskToken === activeTaskToken
+ && !!record?.readbackSha256
+ && this._normalizeUrl(record.pageUrl || '') === this._normalizeUrl(pageUrl)
+ && this._isGithubCommitMessageField(record?.fieldMeta)
+ ));
+ const summaryVerified = !!expectedSummarySha256 && commitFieldRecords.some(record => (
+ String(record?.fieldMeta?.tag || '').toLowerCase() !== 'textarea'
+ && record.expectedLength === expectedSummary.length
+ && record.expectedSha256 === expectedSummarySha256
+ ));
+ const bodyVerified = !expectedBody || (!!expectedBodySha256 && commitFieldRecords.some(record => (
+ String(record?.fieldMeta?.tag || '').toLowerCase() === 'textarea'
+ && record.expectedLength === expectedBody.length
+ && record.expectedSha256 === expectedBodySha256
+ )));
+ const commitMessageVerified = !commitMessageRequirement
+ || (composableMessage && summaryVerified && bodyVerified);
+ const githubFileCommit = !metadataIncomplete
+ && githubEditScope
+ && verifiedReplacement
+ && commitMessageVerified
+ ? {
+ ...githubEditScope,
+ expectedLength: verifiedReplacement.expectedLength,
+ expectedSha256: verifiedReplacement.expectedSha256,
+ commitMessageVerified,
+ // Chromium's contenteditable readback deterministically expands
+ // newline runs (see _contentEditableValueMatches), so a verified
+ // proof is not always byte-exact. Requiring byte-exact readback
+ // here would permanently block every newline-terminated file;
+ // record which notion of exactness authorized the binding instead.
+ // The byte-exact raw-blob check after the commit stays fail-closed.
+ readbackByteExact: verifiedReplacement.readbackLength === verifiedReplacement.expectedLength
+ && verifiedReplacement.readbackSha256 === verifiedReplacement.expectedSha256,
+ }
+ : null;
const verificationKind = this._workflowVerificationKind(siteWorkflow);
+ const preDispatchPublicationAccountIdentity = verificationKind === 'published_resource'
+ && ['twitter', 'bluesky'].includes(siteWorkflow.adapterName)
+ && detectedSubmit?.publicationAccountIdentityComplete === true
+ ? this._workflowSocialPublicationAccountIdentity(
+ siteWorkflow,
+ detectedSubmit.publicationAccountIdentity,
+ )
+ : '';
const normalizeOrderIdentities = values => [...new Set((Array.isArray(values) ? values : [])
.map(value => String(value || '').trim().toUpperCase())
.filter(value => /^[A-Z0-9][A-Z0-9-]{3,}$/.test(value)))];
@@@ -1710,13 -1578,7 +1823,14 @@@
metadataRequirements: metadataRequirements.map(requirement => ({ ...requirement })),
...(metadataIncomplete ? { metadataRequirementsIncomplete: true } : {}),
} : {}),
+ ...(verificationKind === 'published_resource'
+ && ['twitter', 'bluesky'].includes(siteWorkflow.adapterName)
+ ? {
+ preDispatchPublicationAccountIdentity,
+ preDispatchPublicationAccountIdentityComplete: !!preDispatchPublicationAccountIdentity,
+ }
+ : {}),
+ ...(githubFileCommit ? { githubFileCommit } : {}),
...(verificationKind === 'form_confirmation' ? {
formDocumentScope: this._workflowInventoryDocumentScope(tabId, pageUrl),
formIdentity: this._workflowFormOriginIdentity(pageUrl),
@@@ -1924,10 -1863,11 +2115,13 @@@
['arrival', ['arrival', 'to', 'destination', 'arrival station', 'varış', '到达站', '到着駅', '도착역']],
['passenger', ['passenger', 'traveller', 'traveler', 'yolcu', '乘客', '乗客', '승객']],
['seat_class', ['seat class', 'seat', 'class', 'berth', 'koltuk', '座位', '席', '좌석']],
+ ['account', ['account', 'profile', 'handle', 'username', 'publishing account', 'posting account']],
+ ['attachment', ['attachment', 'attachments', 'attach', 'attached', 'media', 'medias', 'image', 'images', 'photo', 'photos', 'picture', 'pictures', 'pic', 'pics', 'video', 'videos', 'clip', 'clips', 'file', 'files', 'pièce jointe', 'pièces jointes', 'médias', 'adjunto', 'adjuntos', 'medios', 'imagen', 'imágenes', 'foto', 'fotos', 'anexo', 'anexos', 'mídia', 'mídias', 'imagem', 'imagens', 'anhang', 'anhänge', 'medien', 'bild', 'bilder', 'allegato', 'allegati', 'immagine', 'immagini', 'ek', 'ekler', 'medya', 'görsel', 'resim', '添付', '添付ファイル', '画像', '写真', '動画', 'メディア', '첨부', '첨부파일', '이미지', '사진', '동영상', '미디어', '附件', '图片', '圖片', '照片', '相片', '视频', '視頻', '影片', '媒体', '媒體', 'вложение', 'вложения', 'медиа', 'изображение', 'изображения', 'фото', 'видео']],
['subject', ['subject', 'subject line', 'email subject', 'sujet', 'objet', 'asunto', 'assunto', 'betreff', 'oggetto', 'konu', '件名', '主题', '主旨']],
['body', ['body', 'post', 'post body', 'post text', 'composer']],
+ ['path', ['path', 'file path', 'repository path']],
+ ['branch', ['branch', 'git branch']],
+ ['commit_message', ['commit message', 'commit summary', 'commit title']],
['title', ['title', 'titre', 'título', 'titulo', 'titel', 'titolo', 'başlık', 'タイトル', '제목', '标题', '標題', 'название']],
];
const paddedText = ` ${text} `;
@@@ -1986,8 -1925,22 +2180,23 @@@
discarded += 1;
continue;
}
+ const maxLen = (field === 'body' || field === 'notes') ? 25000 : 10000;
- requirements.set(field, { field, value: this._workflowMetadataValue(value.value, maxLen) });
+ // Keep the byte-exact request text alongside the normalized value, but
+ // only when normalization changed something: Git paths preserve
+ // distinctions NFKC/trim fold (fullwidth A vs A, significant
+ // whitespace), and scope resolution must compare those. Absent means
+ // verbatim equals normalized, so existing shapes are untouched.
+ // Re-ingestion keeps an existing rawValue instead of re-deriving it
+ // from the already-normalized value.
- const normalizedValue = this._workflowMetadataValue(value.value);
++ const normalizedValue = this._workflowMetadataValue(value.value, maxLen);
+ const verbatimValue = typeof value.rawValue === 'string'
+ ? value.rawValue
+ : String(value.value ?? '');
+ requirements.set(field, {
+ field,
+ value: normalizedValue,
+ ...(verbatimValue !== normalizedValue ? { rawValue: verbatimValue } : {}),
+ });
}
return { items: [...requirements.values()], incomplete: discarded > 0 };
}
@@@ -18154,89 -17181,54 +18935,123 @@@ Rules: no prose intro, no conclusion, n
.map((link) => {
try { return new URL(link.getAttribute('href') || link.href || '', url).href; } catch { return ''; }
})
- .filter(value => /linkedin\.com\/(?:feed\/update|posts)\/|github\.com\/[^/]+\/[^/]+\/(?:releases\/tag\/|commit\/[0-9a-f]{7,40})|douyin\.com\/video\/\d+/i.test(value))
+ .filter((value) => {
+ try {
+ const parsed = new URL(value);
+ const resourceHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ const resourcePath = parsed.pathname.replace(/\/+$/, '') || '/';
+ return ((resourceHost === 'x.com' || resourceHost === 'twitter.com') && /^\/[^/]+\/status\/\d+$/i.test(resourcePath))
+ || (resourceHost === 'bsky.app' && /^\/profile\/[^/]+\/post\/[^/]+$/i.test(resourcePath))
+ || (resourceHost === 'linkedin.com' && /^\/(?:feed\/update\/[^/]+|posts\/[^/]+)$/i.test(resourcePath))
- || (resourceHost === 'github.com' && /^\/[^/]+\/[^/]+\/releases\/tag\/[^/]+$/i.test(resourcePath))
++ || (resourceHost === 'github.com' && /^\/[^/]+\/[^/]+\/(?:releases\/tag\/[^/]+|commit\/[0-9a-f]{7,40})$/i.test(resourcePath))
+ || (resourceHost === 'douyin.com' && /^\/video\/\d+$/i.test(resourcePath));
+ } catch {
+ return false;
+ }
+ })
.slice(0, 200);
} catch {
return [];
}
};
+ const publicationAccountEvidence = (submitTarget) => {
+ const siteHost = String(host || '').toLowerCase().replace(/^www\./, '');
+ const adapterName = siteHost === 'x.com' || siteHost === 'twitter.com'
+ ? 'twitter'
+ : siteHost === 'bsky.app'
+ ? 'bluesky'
+ : '';
+ if (!adapterName) return { identity: '', complete: false };
+ const accountFromHref = (href) => {
+ try {
+ const parsed = new URL(href || '', url);
+ const linkHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ const path = parsed.pathname.replace(/\/+$/, '') || '/';
+ if (adapterName === 'twitter' && (linkHost === 'x.com' || linkHost === 'twitter.com')) {
+ const handle = path.match(/^\/([A-Za-z0-9_]{1,15})$/)?.[1] || '';
+ const reserved = new Set(['home', 'explore', 'notifications', 'messages', 'search', 'settings', 'compose', 'i']);
+ return handle && !reserved.has(handle.toLowerCase()) ? `twitter:${handle.toLowerCase()}` : '';
+ }
+ if (adapterName === 'bluesky' && linkHost === 'bsky.app') {
+ const account = path.match(/^\/profile\/([^/]+)$/i)?.[1] || '';
+ return account ? `bluesky:${account.toLowerCase()}` : '';
+ }
+ } catch {}
+ return '';
+ };
+ const identitiesIn = (root, selector = 'a[href]') => {
+ if (!root?.querySelectorAll) return [];
+ return [...new Set(Array.from(root.querySelectorAll(selector))
+ .slice(0, 120)
+ .filter(isVisible)
+ .map(link => accountFromHref(link.getAttribute('href') || link.href || ''))
+ .filter(Boolean))];
+ };
+ if (adapterName === 'twitter') {
+ const profileNav = identitiesIn(doc, 'a[data-testid="AppTabBar_Profile_Link"][href]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
+ let node = submitTarget;
+ for (let depth = 0; node && depth < 10; depth++, node = node.parentElement) {
+ let hasEditor = false;
+ try {
+ hasEditor = !!node.querySelector?.('textarea,[contenteditable="true"],[role="textbox"]');
+ } catch {}
+ if (!hasEditor) continue;
+ const identities = identitiesIn(node);
+ if (identities.length === 1) return { identity: identities[0], complete: true };
+ if (identities.length > 1) break;
+ }
+ if (adapterName === 'bluesky') {
+ const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
+ return { identity: '', complete: false };
+ };
const transactionOrderSite = /(?:^|\.)12306\.cn$/i.test(host);
- const submitInfo = (form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitTarget = null) => {
+ const submitInfo = (form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitControl = null) => {
const formOrders = transactionOrderSite
? transactionOrderScan(form)
: { ids: [], complete: false };
const pageOrders = transactionOrderSite
? transactionOrderScan(doc.body || doc.documentElement)
: { ids: [], complete: false };
- const publicationAccount = publicationAccountEvidence(submitTarget);
++ const publicationAccount = publicationAccountEvidence(submitControl);
+ const formSummary = summarizeForm(form, pendingEl, pendingValue);
+ const control = labelControlFor(submitControl) || submitControl;
+ const controlLabel = compact(
+ control?.innerText || control?.textContent || control?.getAttribute?.('aria-label') || '',
+ 120,
+ );
+ const activeModal = findTopmostModal();
+ const controlInModal = !!(control && activeModal?.contains?.(control));
+ const githubEditPage = (() => {
+ try {
+ const parsed = new URL(url);
+ return parsed.hostname.toLowerCase().replace(/^www\./, '') === 'github.com'
+ && /^\/[^/]+\/[^/]+\/edit\//i.test(parsed.pathname);
+ } catch {
+ return false;
+ }
+ })();
+ // The launcher label is localized, so English text alone cannot
+ // identify it. A dialog-opening affordance is locale-independent: the
+ // launcher reversibly opens the commit dialog instead of submitting.
+ const controlOpensDialog = (() => {
+ try {
+ if (control?.hasAttribute?.('data-show-dialog-id')) return true;
+ const triggerAttrs = [
+ control?.getAttribute?.('aria-haspopup'),
+ control?.getAttribute?.('aria-controls'),
+ control?.getAttribute?.('data-show-dialog-id'),
+ control?.getAttribute?.('data-action'),
+ control?.getAttribute?.('data-target'),
+ ].filter(Boolean).join(' ');
+ return /dialog/i.test(triggerAttrs);
+ } catch {
+ return false;
+ }
+ })();
return {
isSubmit: true,
host,
@@@ -18250,11 -17240,10 +19065,14 @@@
transactionOrderIdsComplete: formOrders.complete,
transactionPageOrderIds: pageOrders.ids,
transactionPageOrderIdsComplete: pageOrders.complete,
+ githubCommitDialogLauncher: githubEditPage
+ && !controlInModal
+ && (/^commit changes(?:\.{3}|…)?$/i.test(controlLabel) || controlOpensDialog),
- ...summarizeForm(form, pendingEl, pendingValue),
+ ...formSummary,
+ summary: [
+ formSummary.summary,
+ publicationAccount.complete ? `Publishing account: ${publicationAccount.identity}.` : '',
+ ].filter(Boolean).join(' '),
};
};
const labelControlFor = (el) => {
@@@ -21165,7 -20912,7 +22953,7 @@@
'mode=active only when the user asks the agent to perform repeated item/action work that benefits from row tracking.',
'Exception: for siteContext.workflow.job="upload-release-assets" with requiresLedger=true, use mode=active and list every concrete requested target even when there is exactly one. Copy each exact requested filename or path into targets; do not merge or omit assets. When the user names the release tag, also return it as workflowFields=[{"field":"tag","value":"exact tag"}]; return workflowFields=[] when no tag is named.',
'For siteContext.workflow.job="update-metadata", workflowFields must contain every metadata field explicitly requested by the user and its complete exact intended value. Use canonical field names title, description, visibility, audience, tags, category, playlist, language, license, comments, embedding, paid_promotion, recording_date, or recording_location. Never infer a field or value from page content.',
- 'For siteContext.workflow.job="publish-release", "publish-post", or "publish-content", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value (for long post bodies or notes exceeding response budget, provide a short excerpt; complete bodies are preserved from task context). Use canonical field names tag, title, notes, body, visibility, or attachment; for publish-post only, also use account when the user explicitly names the publishing account. Never infer a field or value from page content.',
- 'For siteContext.workflow.job="publish-release", "publish-post", "publish-content", or "edit-file-and-commit", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value. Use canonical field names tag, title, notes, body, visibility, path, branch, or commit_message. For edit-file-and-commit, include path/branch/commit_message only when the user explicitly supplied them; the runtime separately binds the exact verified editor content. Never infer a field or value from page content.',
++ 'For siteContext.workflow.job="publish-release", "publish-post", "publish-content", or "edit-file-and-commit", workflowFields must contain every publication field explicitly requested by the user and its complete exact intended value (for long post bodies or notes exceeding response budget, provide a short excerpt; complete bodies are preserved from task context). Use canonical field names tag, title, notes, body, visibility, attachment, path, branch, or commit_message; for publish-post only, also use account when the user explicitly names the publishing account. For edit-file-and-commit, include path, branch, and commit_message only when the user explicitly supplied them; the runtime separately binds the exact verified editor content. Never infer a field or value from page content.',
'For siteContext.workflow.job="draft-email" or "send-email", workflowFields must contain every message field explicitly requested by the user and its complete exact intended value. Use canonical field names subject or body. Never infer a field or value from page content.',
'For siteContext.workflow.template="transaction", workflowFields must contain every booking detail explicitly requested by the user and its exact value. Use canonical field names train, travel_date, departure, arrival, passenger, or seat_class. Never infer a detail from page content.',
'For siteContext.workflow.template="form", workflowLabelValues must contain one entry per field the user supplied an exact value for, as {"label":"the field in the user\'s words","value":"the exact value"}. Return workflowLabelValues=[] when the user supplied no exact values, and never copy a value from page content.',
@@@ -26459,169 -26178,15 +28275,182 @@@
/success|saved|submitted|created|sent|published|complete|done|updated|added|approved|resolved/i.test(text)
&& !/\\b(?:not|never|failed|failure|error|unable|cannot|can't|could not|couldn't|did not|didn't|was not|wasn't|were not|weren't|invalid|denied|rejected|unsuccessful)\\b/i.test(text)
).slice(0, 5);
- const workflowResourceUrls = Array.from(document.querySelectorAll('a[href]'))
+ const publicationResourceIdentity = value => {
+ try {
+ const parsed = new URL(value, location.href);
+ const host = parsed.hostname.toLowerCase().replace(/^www\\./, '');
+ const path = parsed.pathname.replace(/\\/+$/, '') || '/';
+ const twitter = (host === 'x.com' || host === 'twitter.com')
+ ? path.match(/^\\/[^/]+\\/status\\/(\\d+)$/i)
+ : null;
+ if (twitter) return 'twitter:status:' + twitter[1];
+ if (host === 'bsky.app' && /^\\/profile\\/[^/]+\\/post\\/[^/]+$/i.test(path)) {
+ return 'bluesky:' + host + path.toLowerCase();
+ }
+ if (host === 'linkedin.com' && /^\\/(?:feed\\/update\\/[^/]+|posts\\/[^/]+)$/i.test(path)) {
+ return 'linkedin:' + host + path;
+ }
+ if (host === 'github.com' && /^\\/[^/]+\\/[^/]+\\/releases\\/tag\\/[^/]+$/i.test(path)) {
+ return 'github:' + host + path;
+ }
++ if (host === 'github.com' && /^\\/[^/]+\\/[^/]+\\/commit\\/[0-9a-f]{7,40}$/i.test(path)) {
++ return 'github:' + host + path;
++ }
+ if (host === 'douyin.com' && /^\\/video\\/\\d+$/i.test(path)) {
+ return 'douyin:' + host + path;
+ }
+ } catch {}
+ return '';
+ };
+ const workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
+ .slice(0, 2000)
+ .map(link => {
+ let url = '';
+ try { url = new URL(link.getAttribute('href') || link.href || '', location.href).href; } catch {}
+ return { link, url, identity: publicationResourceIdentity(url) };
+ })
+ .filter(item => !!item.identity);
- const workflowResourceUrls = Array.from(new Map(
- workflowResourceLinks.map(item => [item.identity, item.url]),
- ).values()).slice(0, 200);
++ // Commit pages expose changed files as blob links. They prove
++ // the commit's file scope without becoming published-resource
++ // records of their own.
++ const workflowBlobUrls = Array.from(document.querySelectorAll('a[href]'))
++ .slice(0, 2000)
+ .map(link => {
+ try { return new URL(link.getAttribute('href') || link.href || '', location.href).href; } catch { return ''; }
+ })
- // Blob links pin the changed-file list of an observed commit
- // page: raw-byte verification must only accept a path the
- // observed commit actually touched.
- .filter(url => /linkedin\\.com\\/(?:feed\\/update|posts)\\/|github\\.com\\/[^/]+\\/[^/]+\\/(?:releases\\/tag\\/|commit\\/[0-9a-f]{7,40}|blob\\/[0-9a-f]{7,40}\\/\\S+)|douyin\\.com\\/video\\/\\d+/i.test(url))
- .slice(0, 200);
++ .filter(value => /github\\.com\\/[^/]+\\/[^/]+\\/blob\\/[0-9a-f]{7,40}\\/\\S+/i.test(value));
++ const workflowResourceUrls = Array.from(new Map([
++ ...workflowResourceLinks.map(item => [item.identity, item.url]),
++ ...workflowBlobUrls.map(value => ['blob:' + value, value]),
++ ]).values()).slice(0, 200);
+ const workflowResourceRecordMap = new Map();
+ for (const { link, url, identity } of workflowResourceLinks) {
+ const record = publicationRecordRoot(link, identity, publicationResourceIdentity);
+ const best = record?.root || link;
+ const embedded = Array.isArray(record?.excluded) ? record.excluded : [];
+ const isEmbedded = node => embedded.some(entry => entry === node || entry.contains?.(node));
+ // innerText cannot be subtracted, so read it from every
+ // maximal subtree that holds no embedded post. A quote card's
+ // text never reaches the authored-body matcher this way.
+ const authoredText = (root) => {
+ if (!embedded.length) return String(root.innerText || '');
+ const parts = [];
+ const walk = (node) => {
+ if (isEmbedded(node)) return;
+ if (!embedded.some(entry => node.contains?.(entry))) {
+ parts.push(String(node.innerText || ''));
+ return;
+ }
+ for (const child of Array.from(node.childNodes || [])) {
+ if (child.nodeType === 3) parts.push(String(child.nodeValue || ''));
+ else if (child.nodeType === 1) walk(child);
+ }
+ };
+ walk(root);
+ return parts.join('\\n');
+ };
+ const normalizeLines = (value, limit) => String(value || '')
+ .replace(/\\r\\n?/g, '\\n')
+ .split('\\n')
+ .map(line => line.replace(/[^\\S\\n]+/g, ' ').trim())
+ .filter(Boolean)
+ .join('\\n')
+ .slice(0, limit);
+ const text = normalizeLines(authoredText(best), 5000);
+ // The app's own post-text elements, so a one-line requested
+ // body cannot be satisfied by the author name or timestamp
+ // the card also renders. Sized for X Premium long posts.
+ const authoredNodes = Array.isArray(record?.authored) ? record.authored : [];
+ const bodyText = authoredNodes.length
+ ? normalizeLines(authoredNodes.map(node => String(node.innerText || '')).join('\\n'), 25000)
+ : '';
+ const recordLinks = [
+ ...(best.matches?.('a[href]') ? [best] : []),
+ ...Array.from(best.querySelectorAll?.('a[href]') || []),
+ ].filter(candidate => !isEmbedded(candidate)).slice(0, 100).map(candidate => {
+ let href = '';
+ try { href = new URL(candidate.getAttribute('href') || candidate.href || '', location.href).href; } catch {}
+ const compact = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 1000);
+ let inAuthoredBody = false;
+ try {
+ inAuthoredBody = authoredNodes.some(node => node === candidate || node.contains?.(candidate));
+ } catch {}
+ return {
+ href: compact(href),
+ text: compact(candidate.innerText || candidate.textContent),
+ title: compact(candidate.getAttribute('title')),
+ ariaLabel: compact(candidate.getAttribute('aria-label')),
+ expandedUrl: compact(
+ candidate.getAttribute('data-expanded-url')
+ || candidate.getAttribute('data-full-url')
+ || candidate.getAttribute('data-url'),
+ ),
+ ...(inAuthoredBody ? { authored: true } : {}),
+ };
+ }).filter(candidate => candidate.href || candidate.text || candidate.expandedUrl);
+ const links = Array.from(new Map(recordLinks.map(candidate => [
+ [candidate.href, candidate.text, candidate.title, candidate.ariaLabel, candidate.expandedUrl, candidate.authored ? '1' : ''].join('\u0000'),
+ candidate,
+ ])).values()).slice(0, 24);
+ const mediaNodes = Array.isArray(record?.attachments) ? record.attachments : [];
+ const isAvatarOrEmoji = (node) => {
+ try {
+ if (node.closest?.('[data-testid*="Avatar"],[data-testid*="avatar"]')) return true;
+ if (node.closest?.('[data-testid="emoji"]') || node.classList?.contains?.('emoji')) return true;
+ const src = String(node.getAttribute?.('src') || node.src || '').toLowerCase();
+ if (src.includes('profile_images') || src.includes('/avatar/') || src.includes('/emoji/') || src.includes('twemoji')) return true;
+ const alt = String(node.getAttribute?.('alt') || '');
+ if (/^\\p{Emoji}+$/u.test(alt)) return true;
+ } catch {}
+ return false;
+ };
+ const isLinkPreview = (node) => {
+ try {
+ const cardContainer = node.closest?.('[data-testid*="card.layout"]');
+ if (!cardContainer) return false;
+ if (node.closest?.('[data-testid="tweetPhoto"],[data-testid^="postImage"]')) return false;
+ return true;
+ } catch {}
+ return false;
+ };
+ const filteredAttachments = Array.from(best.querySelectorAll?.(
+ 'img, video, [data-testid="tweetPhoto"], [data-testid="videoPlayer"], [data-testid="videoComponent"], [data-testid^="postImage"], [data-testid="postGalleryImage"], [data-testid="contentHider-post"], [data-testid="card.layoutLarge.media"]'
+ ) || []).filter(candidate => !isEmbedded(candidate) && !isAvatarOrEmoji(candidate) && !isLinkPreview(candidate));
+ const rawAttachments = mediaNodes.length
+ ? mediaNodes
+ : filteredAttachments.filter(node => !filteredAttachments.some(other => other !== node && other.contains?.(node)));
+ const attachments = rawAttachments.slice(0, 12).map(candidate => {
+ const tag = (candidate.tagName || '').toLowerCase();
+ const testId = typeof candidate.getAttribute === 'function' ? (candidate.getAttribute('data-testid') || '') : '';
+ const isVideo = tag === 'video' || /video/i.test(testId) || !!candidate.querySelector?.('video');
+ let src = '';
+ try {
+ src = candidate.getAttribute?.('src') || candidate.src
+ || candidate.querySelector?.('img, video, source')?.getAttribute?.('src')
+ || candidate.querySelector?.('img, video, source')?.src || '';
+ } catch {}
+ const alt = typeof candidate.getAttribute === 'function'
+ ? (candidate.getAttribute('alt') || candidate.getAttribute('aria-label')
+ || candidate.querySelector?.('img')?.getAttribute?.('alt') || '')
+ : '';
+ return {
+ type: isVideo ? 'video' : 'image',
+ src: String(src || '').slice(0, 500),
+ alt: String(alt || '').slice(0, 500),
+ };
+ });
+ const prior = workflowResourceRecordMap.get(identity);
+ if (!prior || text.length > prior.text.length || (!prior.attachments?.length && attachments.length)) {
+ workflowResourceRecordMap.set(identity, {
+ url,
+ text,
+ bodyText,
+ links,
+ attachments: attachments.length ? attachments : (prior?.attachments || []),
+ });
+ }
+ }
+ const workflowResourceRecords = Array.from(workflowResourceRecordMap.values()).slice(0, 40);
return {
url: location.href,
title: document.title,
diff --cc test/run.js
index d3f63687b,ba059e962..0f8ad957c
--- a/test/run.js
+++ b/test/run.js
@@@ -76500,22 -79640,10 +79903,23 @@@ test('submit detector source covers sub
assert.match(agent, /const labelControlFor = \(el\) => \{[\s\S]*String\(el\.tagName \|\| ''\)\.toUpperCase\(\) !== 'LABEL'[\s\S]*el\.htmlFor[\s\S]*doc\.getElementById\(el\.htmlFor\)[\s\S]*button,input,textarea,select/, `${label}: submit probe should resolve labels to associated controls`);
assert.match(agent, /const target = labelControlFor\(el\) \|\| el;[\s\S]*const candidate = target\.closest\?\.\('button,input,\[role="button"\],\[onclick\],\[data-action\]'\)/, `${label}: submit-control detection should inspect label-backed controls`);
assert.match(agent, /const submitControlEvidence = \(el\) => \{/, `${label}: custom submit controls should classify preflight evidence strength`);
+ assert.match(agent, /if \(!form\) return socialPublishControlEvidence\(candidate\);/, `${label}: form-less social publish controls should still reach the submit probe`);
+ assert.match(agent, /const socialPublishAdapterName = \(\) => \{[\s\S]*x\.com[\s\S]*twitter\.com[\s\S]*bsky\.app/, `${label}: the probe should recognize the X and Bluesky publish surfaces`);
+ assert.match(agent, /\^tweetButton\(\?:Inline\)\?\$/, `${label}: the X Post control should be recognized by its app-owned test id`);
+ assert.match(agent, /\^composerPublish\(\?:Btn\|Button\)\$/, `${label}: the Bluesky publish control should be recognized by its app-owned test id`);
+ assert.match(agent, /const socialPublishComposerFor = \(candidate\) => \{[\s\S]*textarea,\[contenteditable="true"\],\[role="textbox"\]/, `${label}: a form-less publish control must belong to an open composer`);
+ assert.match(agent, /return socialPublishComposerFor\(candidate\)\s*\n\s*\? \{ isSubmit: true, strong: publishTestId \}/, `${label}: only composer-bound social publish controls should count as submits`);
+ assert.match(agent, /if \(testId\) \{\s*\n\s*if \(!publishTestId\) return \{ isSubmit: false, strong: false \};/, `${label}: an app-named control that is not the publish control should be rejected outright`);
+ assert.match(agent, /candidate\.closest\?\.\('nav,\[role="navigation"\],header,\[role="banner"\]'\)/, `${label}: a navigation control that only opens a composer should not count as a publish`);
+ assert.match(agent, /\|\| socialPublishComposerFor\(candidate\)/, `${label}: the composer should stand in for the missing form when summarizing the publish`);
+ assert.match(agent, /Composer on \$\{action\} \(no enclosing HTML form\)/, `${label}: publish confirmations should summarize a form-less composer`);
- assert.match(agent, /const submitInfo = \(form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitTarget = null\)/, `${label}: submit summaries should carry preflight evidence strength`);
+ assert.match(agent, /const submitInfo = \(form, reason, pendingEl = null, pendingValue = null, validationSubmitEvidence = 'strong', submitControl = null\)/, `${label}: submit summaries should carry preflight evidence strength and the resolved control`);
+ assert.match(agent, /const publicationAccountEvidence = \(submitTarget\) => \{/, `${label}: social publication submits should bind the active account`);
+ assert.match(agent, /AppTabBar_Profile_Link/, `${label}: X publishing account should use the app-owned profile navigation link`);
+ assert.match(agent, /publicationAccountIdentityComplete: publicationAccount\.complete/, `${label}: account evidence completeness should survive the page probe`);
assert.match(agent, /evidence\.strong \? 'strong' : 'heuristic'/, `${label}: custom submit probes should label strong and heuristic evidence`);
assert.match(agent, /detected\.validationSubmitEvidence === 'strong' \? 'strong' : 'heuristic'/, `${label}: submit evidence strength should survive page-probe normalization`);
+ assert.match(agent, /githubCommitDialogLauncher: githubEditPage[\s\S]*!controlInModal[\s\S]*commit changes/, `${label}: GitHub's reversible commit-dialog launcher must be target- and modal-bound`);
assert.match(agent, /const findTopmostModal = \(\) => \{[\s\S]*dialog\[open\][\s\S]*\[role="dialog"\]\[aria-modal="true"\][\s\S]*\[class\*="DialogOverlay"\]/, `${label}: text submit probing should mirror modal scoping`);
assert.match(agent, /Array\.from\(\(findTopmostModal\(\) \|\| doc\)\.querySelectorAll/, `${label}: text submit probing should search inside the topmost modal when present`);
}
@@@ -86984,2860 -90112,10 +90388,2861 @@@ test('publication workflows classify an
], `${AgentClass.name}: trusted publication payload fields were not retained`);
const prompt = agent._progressIntentClassifierMessages(taskText, classifierContext)[0].content;
assert.match(prompt, /publish-release/);
- assert.match(prompt, /\bcanonical field names tag, title, notes, body, visibility, or attachment\b/);
- assert.match(
- prompt,
- /\bcanonical field names tag, title, notes, body, visibility, path, branch, or commit_message\b/,
++ assert.match(prompt, /\bcanonical field names tag, title, notes, body, visibility, attachment, path, branch, or commit_message\b/);
+ assert.match(prompt, /for publish-post only, also use account/);
++ assert.match(prompt, /For edit-file-and-commit, include path, branch, and commit_message only when the user explicitly supplied them/);
+ }
+});
+
+test('social publication workflow follows the live X or Bluesky destination and uses approved-plan payload context', async () => {
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({ getActive: () => ({ chat: async () => ({ content: '{}' }) }) });
+ agent.useSiteAdapters = true;
+ agent._persist = () => {};
+ const tabId = 9005 + index;
+ let liveUrl = 'https://x.com/compose/post';
+ agent._currentUrl = async () => liveUrl;
+ agent._currentProgressPageScope = () => liveUrl;
+ agent.conversations.set(tabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'and now on to X!' },
+ ]);
+ const priorBlueskyWorkflow = agent._resolvePlannerSiteWorkflow('https://bsky.app/', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow: priorBlueskyWorkflow,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ '- Publish this exact post on X: Shipping the workflow kernel today.',
+ ].join('\n'),
+ });
+ let classifierCalls = 0;
+ let classifierContext = null;
+ agent._chatWithCostAllowance = async (_provider, messages) => {
+ classifierCalls++;
+ classifierContext = JSON.parse(messages[1].content).siteContext;
+ return {
+ content: JSON.stringify({
+ mode: 'inactive',
+ allowedActions: [],
+ forbiddenActions: [],
+ targets: [],
+ workflowFields: [{ field: 'body', value: 'Shipping the workflow kernel today.' }],
+ confidence: 0.99,
+ pageScopePolicy: 'page',
+ }),
+ };
+ };
+ const provider = { chat: async () => ({ content: '{}' }) };
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId, provider), true);
+ assert.equal(guard.siteWorkflow?.adapterName, 'twitter');
+ assert.equal(guard.siteWorkflow?.job?.id, 'publish-post');
+ assert.match(classifierContext?.approvedPlan || '', /Shipping the workflow kernel today/);
+ assert.deepEqual(guard.workflowMetadataRequirements, [
+ { field: 'body', value: 'Shipping the workflow kernel today.' },
+ ]);
+
+ liveUrl = 'https://bsky.app/';
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId, provider), false);
+ assert.equal(guard.siteWorkflow?.adapterName, 'twitter');
+ assert.equal(classifierCalls, 1, AgentClass.name + ': destination rebind unnecessarily reclassified the same task payload');
+ assert.deepEqual(guard.workflowMetadataRequirements, [
+ { field: 'body', value: 'Shipping the workflow kernel today.' },
+ ]);
+
+ const blueskyTabId = tabId + 100;
+ agent.conversations.set(blueskyTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'Post it on Bluesky.' },
+ ]);
+ const blueskyGuard = agent._startPlanExecutionGuard(blueskyTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ '- Publish this exact post on Bluesky: Shipping the workflow kernel today.',
+ ].join('\n'),
+ });
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(blueskyTabId, provider), true);
+ assert.equal(blueskyGuard.siteWorkflow?.adapterName, 'bluesky');
+
+ liveUrl = 'https://x.com/compose/post';
+ const longBodyTabId = tabId + 150;
+ const fullLongText = ('Initial post content '.repeat(700)).trim();
+ agent.conversations.set(longBodyTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'Post this on X: ' + fullLongText },
+ ]);
+ const longBodyGuard = agent._startPlanExecutionGuard(longBodyTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ `- Post this on X: ${fullLongText}`,
+ ].join('\n'),
+ });
+ const priorChat = agent._chatWithCostAllowance;
+ agent._chatWithCostAllowance = async () => ({
+ content: JSON.stringify({
+ mode: 'inactive',
+ allowedActions: [],
+ forbiddenActions: [],
+ targets: [],
+ workflowFields: [{ field: 'body', value: fullLongText.slice(0, 100) }],
+ confidence: 0.99,
+ pageScopePolicy: 'page',
+ }),
+ });
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(longBodyTabId, provider), true);
+ assert.equal(longBodyGuard.workflowMetadataRequirements?.[0]?.value, fullLongText,
+ AgentClass.name + ': long post body was truncated by classifier output instead of preserved from context');
+ agent._chatWithCostAllowance = priorChat;
+
+ liveUrl = 'https://x.com/compose/post';
+ const nonEnglishTabId = tabId + 200;
+ agent.conversations.set(nonEnglishTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'Publícalo en https://x.com/home.' },
+ ]);
+ const nonEnglishGuard = agent._startPlanExecutionGuard(nonEnglishTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ '- Publícalo en https://x.com/home: Shipping the workflow kernel today.',
+ ].join('\n'),
+ });
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(nonEnglishTabId, provider), true);
+ assert.equal(nonEnglishGuard.siteWorkflow?.adapterName, 'twitter',
+ AgentClass.name + ': explicit social destination URL was hidden behind English-only intent words');
+
+ const referenceOnlyTabId = tabId + 250;
+ agent.conversations.set(referenceOnlyTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'Read https://x.com/nasa/status/1234567890 and submit its details in the form.' },
+ ]);
+ const referenceOnlyGuard = agent._startPlanExecutionGuard(referenceOnlyTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ '- Read https://x.com/nasa/status/1234567890 and submit its details in the form.',
+ ].join('\n'),
+ });
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(referenceOnlyTabId, provider), false,
+ AgentClass.name + ': a referenced X permalink was treated as the publication destination');
+ assert.equal(referenceOnlyGuard.siteWorkflow, null);
+ assert.equal(agent._socialPublishDestinationAdapter('https://x.com/nasa/status/1234567890'), '');
+ assert.equal(agent._socialPublishDestinationAdapter('https://bsky.app/profile/nasa.gov/post/3kabc'), '');
+ assert.equal(agent._socialPublishDestinationAdapter('https://x.com/nasa'), '');
+ assert.equal(agent._socialPublishDestinationAdapter('https://x.com/home'), 'twitter');
+ assert.equal(agent._socialPublishDestinationAdapter('https://x.com/compose'), 'twitter');
+ assert.equal(agent._socialPublishDestinationAdapter('https://x.com/compose/post'), 'twitter');
+ assert.equal(agent._socialPublishDestinationAdapter('https://bsky.app/'), 'bluesky');
+
+ // A publish verb and a platform name can both appear in a task that never
+ // asks for a post. Only a verb that governs the platform is a destination.
+ const readOnlyMentionTabId = tabId + 275;
+ agent.conversations.set(readOnlyMentionTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: "Read Acme's posts on X, then share the findings in the survey." },
+ ]);
+ const readOnlyMentionGuard = agent._startPlanExecutionGuard(readOnlyMentionTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ "- Read Acme's posts on X, then share the findings in the survey.",
+ ].join('\n'),
+ });
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(readOnlyMentionTabId, provider), false,
+ AgentClass.name + ': an unrelated X mention plus a publish verb bound the run to publish-post');
+ assert.equal(readOnlyMentionGuard.siteWorkflow, null);
+ assert.deepEqual(
+ [...agent._trustedSocialPublishTargetAdapters({
+ taskText: 'Read the latest tweets on Twitter and summarize them in the form.',
+ })],
+ [],
+ AgentClass.name + ': reading a platform was treated as publishing to it',
+ );
+ assert.deepEqual(
+ [...agent._trustedSocialPublishTargetAdapters({ taskText: 'Share this to bsky please' })],
+ ['bluesky'],
+ );
+ assert.deepEqual(
+ [...agent._trustedSocialPublishTargetAdapters({ taskText: 'tweet this: hello world' })],
+ ['twitter'],
+ );
+ for (const [taskText, expected, why] of [
+ ['Read https://x.com/home, then submit a summary in the survey.', [],
+ 'a feed used as a read source was treated as a destination'],
+ ['Open https://bsky.app/ and read the feed', [],
+ 'an opened feed was treated as a destination'],
+ ['Read the publication at https://x.com/home and submit it', [],
+ 'the noun "publication" was read as publication intent'],
+ // Publication language is not English-only, and a composer route needs
+ // no verb at all.
+ ['Publ\u00edcalo en https://x.com/home', ['twitter'], 'Spanish publication intent was not recognized'],
+ ['Yay\u0131nla: https://x.com/home', ['twitter'], 'Turkish publication intent was not recognized'],
+ ['\u6295\u7a3f\u3057\u3066\u304f\u3060\u3055\u3044 https://x.com/home', ['twitter'],
+ 'Japanese publication intent was not recognized'],
+ ['\u5728 https://x.com/compose/post \u4e0a\u53d1\u5e03\u8fd9\u6761\u6d88\u606f', ['twitter'],
+ 'a composer route needed an English verb'],
+ ['Just open https://x.com/compose/post', ['twitter'],
+ 'a composer route is a destination by construction'],
+ ['Use https://x.com/compose to send this update', ['twitter'],
+ 'the bare X composer route was not recognized as a destination by construction'],
+ // A destination can lead the command as easily as follow it.
+ ['On https://x.com/home, publish this update', ['twitter'],
+ 'a destination that leads the command was discarded'],
+ // JavaScript places no word boundary around a Cyrillic word.
+ ['\u041e\u043f\u0443\u0431\u043b\u0438\u043a\u0443\u0439 \u044d\u0442\u043e \u043d\u0430 https://x.com/home', ['twitter'],
+ 'Russian publication intent was not recognized'],
+ // Scripts without spacing need the read verb to win over the noun.
+ ['\u9605\u8bfb\u63a8\u6587 https://x.com/home \u7136\u540e\u628a\u6458\u8981\u63d0\u4ea4\u5230\u8868\u5355', [],
+ 'a CJK content noun was read as a publish command'],
+ ['\u9605\u8bfb\u6295\u7a3f https://x.com/home \u7136\u540e\u628a\u6458\u8981\u63d0\u4ea4\u5230\u8868\u5355', [],
+ 'a CJK publish word governed by a read verb was read as intent'],
+ // "post" and "posts" are nouns as often as commands. The clause decides.
+ ['Read posts on https://x.com/home, then submit a summary in the survey', [],
+ 'the noun "posts" was read as a publish command'],
+ ['Posts to read on X, then submit a summary in the survey', [],
+ 'noun-like publish token followed by read intent was treated as a publish command'],
+ ['Tweets to read on X, then summarize them', [],
+ 'tweets followed by read intent was treated as a publish command'],
+ ['Read the post on https://x.com/home and submit a summary in the survey', [],
+ 'a read verb governing "post" did not disqualify it'],
+ ['Check the latest posts on https://x.com/home then fill the form', [],
+ 'a read verb further from the noun did not disqualify it'],
+ ['Read the summary and publish it on https://x.com/home', ['twitter'],
+ 'a publish command in its own clause was lost to an earlier read verb'],
+ ['Inspect https://x.com/compose/post but do not publish anything; submit findings in the survey', [],
+ 'negation following a composer route was ignored'],
+ ['Find market share on X, then submit it in the survey', [],
+ 'noun use of share was treated as publication intent'],
+ ['Share our update on X, then submit it in the survey', ['twitter'],
+ 'valid publication command with share was not recognized'],
+ // Bare platforms use the same multilingual verbs as URLs, not English-only.
+ ['Publícalo en X', ['twitter'],
+ 'a Spanish bare platform destination was missed'],
+ ['Publicar en Bluesky', ['bluesky'],
+ 'a Spanish bare Bluesky destination was missed'],
+ ['Publiez ceci sur Bluesky', ['bluesky'],
+ 'a French bare platform destination was missed'],
+ // A reply is a publication: it composes and submits a post.
+ ['Reply "Thanks" on X', ['twitter'],
+ 'an English reply command was not read as publication intent'],
+ ['Respond on Bluesky', ['bluesky'],
+ 'an English respond command was not read as publication intent'],
+ ['Responde en X con "gracias"', ['twitter'],
+ 'a Spanish reply command was not read as publication intent'],
+ ['Répondez sur Bluesky', ['bluesky'],
+ 'a French reply command was not read as publication intent'],
+ ['Antworte auf X', ['twitter'],
+ 'a German reply command was not read as publication intent'],
+ ['Ответь в X', ['twitter'],
+ 'a Russian reply command was not read as publication intent'],
+ ['Xで返信して', ['twitter'],
+ 'a Japanese reply command was not read as publication intent'],
+ ['在X上回复', ['twitter'],
+ 'a Chinese reply command was not read as publication intent'],
+ // Reading replies is not writing one.
+ ['Read the replies on X', [],
+ 'reading replies was read as publication intent'],
+ ['Summarize responses on Bluesky', [],
+ 'summarizing responses was read as publication intent'],
+ ['Collect all replies on X', [],
+ 'collecting replies was read as publication intent'],
+ ['Do not reply on X', [],
+ 'a negated reply command was read as publication intent'],
+ ['发布到X', ['twitter'],
+ 'an unspaced Chinese bare X destination was missed'],
+ ['发布至X', ['twitter'],
+ 'a Chinese bare X destination with 至 was missed'],
+ ['发布在X', ['twitter'],
+ 'a Chinese bare X destination with 在 was missed'],
+ ['发布到X并在完成后通知我', ['twitter'],
+ 'an unspaced Chinese bare X destination followed by unspaced Chinese text was missed'],
+ ['发布到Bluesky', ['bluesky'],
+ 'an unspaced Chinese bare Bluesky destination was missed'],
+ ['发布在Bluesky', ['bluesky'],
+ 'a Chinese bare Bluesky destination with 在 was missed'],
+ ['在X上发布这条消息', ['twitter'],
+ 'a leading Chinese bare X destination with 在...上 was missed'],
+ ['在X发布这条消息', ['twitter'],
+ 'a leading Chinese bare X destination with 在 was missed'],
+ ['Xに投稿してください', ['twitter'],
+ 'a Japanese bare X destination with に was missed'],
+ ['Xへ投稿してください', ['twitter'],
+ 'a Japanese bare X destination with へ was missed'],
+ ['Xで投稿してください', ['twitter'],
+ 'a Japanese bare X destination with で was missed'],
+ ['X에 게시해주세요', ['twitter'],
+ 'a Korean bare X destination with 에 was missed'],
+ ['Blueskyに投稿してください', ['bluesky'],
+ 'a Japanese bare Bluesky destination was missed'],
+ ['Bluesky에 게시해주세요', ['bluesky'],
+ 'a Korean bare Bluesky destination was missed'],
+ ['在X上阅读推文', [],
+ 'a Chinese read command was wrongly treated as a publish destination'],
+ ['发布到xbox', [],
+ 'a word containing x was wrongly treated as X platform'],
+ ['retweet this', [],
+ 'retweet this was wrongly treated as a publish destination'],
+ ['retweet that', [],
+ 'retweet that was wrongly treated as a publish destination'],
+ ['retweet it', [],
+ 'retweet it was wrongly treated as a publish destination'],
+ ['Do not post this on X; submit it in the survey', [],
+ 'negated publication command was wrongly treated as a publish destination'],
+ ['Never publish to Bluesky', [],
+ 'negated Bluesky publication command was wrongly treated as a publish destination'],
+ ["Don't tweet this", [],
+ 'negated tweet-this command was wrongly treated as a publish destination'],
+ ['Do not post on https://x.com/home; fill the survey instead', [],
+ 'negated URL publication command was wrongly treated as a publish destination'],
+ ['You must not post on X', [],
+ 'negated must-not command was wrongly treated as a publish destination'],
+ ['No publicar esto en X; envíalo en la encuesta', [],
+ 'Spanish negated publication command was wrongly treated as a publish destination'],
+ ['Nicht auf X posten', [],
+ 'German negated publication command was wrongly treated as a publish destination'],
+ ['Ne pas publier sur X', [],
+ 'French negated publication command was wrongly treated as a publish destination'],
+ ['不要在X上发布这条消息', [],
+ 'Chinese negated publication command was wrongly treated as a publish destination'],
+ ['Xに投稿しないでください', [],
+ 'Japanese post-negated publication command was wrongly treated as a publish destination'],
+ ['Xに投稿してはいけない', [],
+ 'Japanese post-negated command with してはいけない was wrongly treated as a publish destination'],
+ ['X에 게시하지 마세요', [],
+ 'Korean post-negated publication command was wrongly treated as a publish destination'],
+ ['Post this on X with no attachments', ['twitter'],
+ 'post with no-attachments phrase was wrongly rejected'],
+ ['Do not post or publish this on X; submit it in the survey', [],
+ 'coordinated publish verbs under negation were wrongly treated as a publish destination'],
+ ['Never publish or post to Bluesky', [],
+ 'coordinated publish verbs under never were wrongly treated as Bluesky publish destination'],
+ ['Do not post on X or publish on Bluesky', [],
+ 'multiple publish destinations joined by or under negation were wrongly treated as a publish destination'],
+ ['Do not post on X, but publish on Bluesky', ['bluesky'],
+ 'contrastive but clause after negated post was wrongly rejected for Bluesky'],
+ ['Post or publish this on X', ['twitter'],
+ 'affirmative coordinated publish verbs were wrongly rejected for X'],
+ ['Post "Do not panic" on X', ['twitter'],
+ 'quoted negation inside payload was treated as command negation'],
+ ['Post “Never give up” on Bluesky', ['bluesky'],
+ 'smart-quoted negation inside payload was treated as command negation'],
+ ['Tweet \'Do not worry\' on X', ['twitter'],
+ 'single-quoted negation inside payload was treated as command negation'],
+ ['Do not post "panic" on X', [],
+ 'actual negation governing publish verb was missed'],
+ ['Do not submit the survey, post this on X', ['twitter'],
+ 'independent affirmative clause after negated non-publish clause separated by comma was wrongly rejected'],
+ ['Do not post on Bluesky, post this on X', ['twitter'],
+ 'independent affirmative publish clause separated by comma from negated publish clause was wrongly rejected'],
+ ['Publish on Bluesky; read https://x.com/home', ['bluesky'],
+ 'unrelated publication command in prior clause was wrongly attributed to read-only social URL'],
+ ['Without posting anything on X, inspect the feed and submit a summary', [],
+ 'without governing publish verb was not recognized as negation'],
+ ['Inspect the feed without posting anything on X, and submit a summary', [],
+ 'without governing publish verb in second clause was not recognized as negation'],
+ ['Post on X without attachments', ['twitter'],
+ 'without attachments in post metadata was wrongly treated as publish negation'],
+ ['Without delay, post on X', ['twitter'],
+ 'without delay was wrongly treated as publish negation'],
+ ['Post "This is a very long announcement body that contains far more than fifty or sixty characters and explains everything clearly" on X', ['twitter'],
+ 'long quoted body before on X was cut off by character window'],
+ ['Post "This is another long announcement body with more than sixty characters" to Bluesky', ['bluesky'],
+ 'long quoted body before to Bluesky was cut off by character window'],
+ ['Post "Check our thoughts on X" to Bluesky', ['bluesky'],
+ 'platform mentioned inside quoted body leaked into target detection'],
+ ['Post "This is a very long announcement body that contains far more than fifty or sixty characters and explains everything clearly" on https://x.com/home', ['twitter'],
+ 'long quoted body before on https://x.com/home was cut off by character window'],
+ ['Post "This is a very long announcement body that contains far more than fifty or sixty characters and explains everything clearly" to https://bsky.app/', ['bluesky'],
+ 'long quoted body before to https://bsky.app/ was cut off by character window'],
+ ['Publique no X: olá', ['twitter'],
+ 'Portuguese no X destination preposition was not recognized'],
+ ['Publique na Bluesky: olá', ['bluesky'],
+ 'Portuguese na Bluesky destination preposition was not recognized'],
+ ['Não publique no X: olá', [],
+ 'negated Portuguese no X command was wrongly treated as a publish destination'],
+ ['Post “He said \\"hello; world\\" today” on X', ['twitter'],
+ 'nested quotation styles mispaired opening curly quote with inner ASCII quote'],
+ ['Post “He said "hello; world" today” on X', ['twitter'],
+ 'nested quotation styles mispaired opening curly quote with inner ASCII quote'],
+ ['Post «He said "hello; world" today» to https://bsky.app/', ['bluesky'],
+ 'guillemet quotation containing inner ASCII quote mispaired delimiters'],
+ ['Post 「He said 『hello; world』 today」 on X', ['twitter'],
+ 'nested CJK quotation marks mispaired delimiters'],
+ ['Post research and development news on X', ['twitter'],
+ 'payload conjunction and before on X split command and destination into separate clauses'],
+ ['Post research and development news to https://x.com/home', ['twitter'],
+ 'payload conjunction and before explicit social URL split command and destination into separate clauses'],
+ ['Post research, development, and marketing news on X', ['twitter'],
+ 'multiple payload conjunctions and commas before on X split command and destination into separate clauses'],
+ ['Publica noticias de investigación y desarrollo en X', ['twitter'],
+ 'Spanish payload conjunction y before en X was not recognized in coordinated clause scan'],
+ ['Publica noticias de investigación e innovación en X', ['twitter'],
+ 'Spanish payload conjunction e before en X was not recognized in coordinated clause scan'],
+ ['Publica noticias de investigación y desarrollo en https://x.com/home', ['twitter'],
+ 'Spanish payload conjunction y before explicit social URL was not recognized in coordinated clause scan'],
+ ['Publie des nouvelles de recherche et développement sur X', ['twitter'],
+ 'French payload conjunction et before sur X was not recognized in coordinated clause scan'],
+ ['Publie des nouvelles de recherche et développement sur https://x.com/home', ['twitter'],
+ 'French payload conjunction et before explicit social URL was not recognized in coordinated clause scan'],
+ ['Veröffentliche Neuigkeiten zu Forschung und Entwicklung auf X', ['twitter'],
+ 'German payload conjunction und before auf X was not recognized in coordinated clause scan'],
+ ['Veröffentliche Neuigkeiten zu Forschung und Entwicklung auf https://x.com/home', ['twitter'],
+ 'German payload conjunction und before explicit social URL was not recognized in coordinated clause scan'],
+ ['Publique notícias de pesquisa e desenvolvimento no X', ['twitter'],
+ 'Portuguese payload conjunction e before no X was not recognized in coordinated clause scan'],
+ ['Publique notícias de pesquisa e desenvolvimento em https://x.com/home', ['twitter'],
+ 'Portuguese payload conjunction e before explicit social URL was not recognized in coordinated clause scan'],
+ ['Não publique notícias de pesquisa e desenvolvimento no X', [],
+ 'negated Portuguese coordinated command was wrongly treated as a publish destination'],
+ ['Опубликуй новости о научных исследованиях и разработках в X', ['twitter'],
+ 'Russian payload conjunction и before в X was not recognized in coordinated clause scan'],
+ ['Опубликуй новости о научных исследованиях и разработках на https://x.com/home', ['twitter'],
+ 'Russian payload conjunction и before explicit social URL was not recognized in coordinated clause scan'],
+ // Reject source-only platform phrases after publish verbs
+ ['Publish a summary of the news available on X in the survey', [],
+ 'source-only platform modifying available was treated as publish destination'],
+ ['Publish a summary of the news found on X in the survey', [],
+ 'source-only platform modifying found was treated as publish destination'],
+ ['Publish a summary of the news seen on X in the survey', [],
+ 'source-only platform modifying seen was treated as publish destination'],
+ ['Publish a summary of the news reported on X in the survey', [],
+ 'source-only platform modifying reported was treated as publish destination'],
+ ['Publish a summary of the news available on X', [],
+ 'source-only platform modifying available without destination was treated as publish destination'],
+ ['Publish a summary of the news on X in the survey', [],
+ 'topic on platform followed by survey destination was treated as publish destination'],
+ ['Publica un resumen de las noticias disponibles en X en la encuesta', [],
+ 'Spanish source-only platform modifying disponibles was treated as publish destination'],
+ ['Publie un résumé des actualités disponibles sur X dans le formulaire', [],
+ 'French source-only platform modifying disponibles was treated as publish destination'],
+ // Preserve leading destinations across intervening clauses
+ ['On X, after reviewing the draft, publish it', ['twitter'],
+ 'leading destination across intervening modifier clause was lost'],
+ ['On X, before noon, publish this update', ['twitter'],
+ 'leading destination across time modifier clause was lost'],
+ ['On X, once approved, publish the draft', ['twitter'],
+ 'leading destination across conditional modifier clause was lost'],
+ ['On X, today, after reviewing the draft, publish it', ['twitter'],
+ 'leading destination across multiple intervening modifier clauses was lost'],
+ ['On Bluesky, after reviewing the draft, publish it', ['bluesky'],
+ 'leading Bluesky destination across intervening modifier clause was lost'],
+ ['En X, tras revisar el borrador, publícalo', ['twitter'],
+ 'Spanish leading destination across intervening clause was lost'],
+ ['Sur X, après avoir vérifié le brouillon, publiez-le', ['twitter'],
+ 'French leading destination across intervening clause was lost'],
+ ['On X, after reviewing the draft, publish it in the survey', [],
+ 'leading platform before intervening clause was wrongly kept when publish command specifies survey destination'],
+ ['Read posts on X. After reviewing the draft, publish it.', [],
+ 'leading platform across sentence boundary was wrongly adopted'],
+ // Platform names used as report topics with non-social destinations
+ ['Publish a report on X adoption in the survey', [],
+ 'report on X adoption followed by survey destination was treated as publish destination'],
+ ['Publish a report on X in the survey', [],
+ 'report on X followed by survey destination was treated as publish destination'],
+ ['Publish a study on Bluesky usage in the spreadsheet', [],
+ 'study on Bluesky usage followed by spreadsheet destination was treated as publish destination'],
+ ['Publish research on X trends into the form', [],
+ 'research on X trends into form was treated as publish destination'],
+ ['Publica un informe sobre la adopción de X en la encuesta', [],
+ 'Spanish report on X adoption in survey was treated as publish destination'],
+ ['Publie un rapport sur l\'adoption de X dans le formulaire', [],
+ 'French report on X adoption in form was treated as publish destination'],
+ ['Publish a report on X adoption', ['twitter'],
+ 'report on X adoption without non-social destination should publish to X'],
+ ['Publish on X and in the survey: Update', ['twitter'],
+ 'coordinated publish on X and in survey should publish to X'],
+ // Leading non-social destinations followed by source platforms
+ ['Publish in the survey a summary of posts on X', [],
+ 'leading survey destination before summary of posts on X was treated as publish destination'],
+ ['Publish into the form a collection of updates on Bluesky', [],
+ 'leading form destination before collection of updates on Bluesky was treated as publish destination'],
+ ['Publica en la encuesta un resumen de publicaciones en X', [],
+ 'Spanish leading survey destination before summary of publications on X was treated as publish destination'],
+ ['Publie dans le formulaire un résumé des posts sur X', [],
+ 'French leading form destination before summary of posts on X was treated as publish destination'],
+ ['Veröffentliche in der Umfrage eine Zusammenfassung von Beiträgen auf X', [],
+ 'German leading survey destination before summary of posts on X was treated as publish destination'],
+ ['Publish in the survey and on X: Update', ['twitter'],
+ 'coordinated publish in survey and on X should publish to X'],
+ ['Publish into the form and to Bluesky: Update', ['bluesky'],
+ 'coordinated publish into form and to Bluesky should publish to Bluesky'],
+ // Multi-platform coordination across conjunctions
+ ['Post on X and Bluesky', ['twitter', 'bluesky'],
+ 'coordinated destinations on X and Bluesky should both be targeted'],
+ ['Post to X or Bluesky: Launch announcement', ['twitter', 'bluesky'],
+ 'coordinated destination with "or" should target both platforms'],
+ ['Publish on X, Threads, and Bluesky', ['twitter', 'bluesky'],
+ 'coordinated destination list with intervening platforms should target supported platforms'],
+ ['Publica en X y Bluesky', ['twitter', 'bluesky'],
+ 'Spanish coordinated destinations on X and Bluesky should both be targeted'],
+ ['Publie sur X et Bluesky', ['twitter', 'bluesky'],
+ 'French coordinated destinations on X and Bluesky should both be targeted'],
+ ['Veröffentliche auf X und Bluesky', ['twitter', 'bluesky'],
+ 'German coordinated destinations on X and Bluesky should both be targeted'],
+ ['Posta su X e Bluesky', ['twitter', 'bluesky'],
+ 'Italian coordinated destinations on X and Bluesky should both be targeted'],
+ ['Post on both X and Bluesky', ['twitter', 'bluesky'],
+ 'coordinated destinations with "both" on X and Bluesky should both be targeted'],
+ ['Post to either X or Bluesky: Launch announcement', ['twitter', 'bluesky'],
+ 'coordinated destination with "either" on X or Bluesky should target both platforms'],
+ // Content links should not be treated as competing destinations
+ ['Post a link to the survey on X', ['twitter'],
+ 'content link to survey should not compete with X publish destination'],
+ ['Publish a link to the form on Bluesky', ['bluesky'],
+ 'content link to form should not compete with Bluesky publish destination'],
+ ['Share the URL to the spreadsheet on X', ['twitter'],
+ 'URL to spreadsheet should not compete with X publish destination'],
+ ['Post an invite to the survey on Bluesky', ['bluesky'],
+ 'invite to survey should not compete with Bluesky publish destination'],
+ ['Publica un enlace a la encuesta en X', ['twitter'],
+ 'Spanish content link to survey should not compete with X publish destination'],
+ ['Publie un lien vers le formulaire sur Bluesky', ['bluesky'],
+ 'French content link to form should not compete with Bluesky publish destination'],
+ ['Veröffentliche einen Link zur Umfrage auf X', ['twitter'],
+ 'German content link to survey should not compete with X publish destination'],
+ ]) {
+ assert.deepEqual(
+ [...agent._trustedSocialPublishTargetAdapters({ taskText })].sort(),
+ expected.slice().sort(),
+ AgentClass.name + ': ' + why,
+ );
+ }
+
+ const genericTabId = tabId + 300;
+ agent.conversations.set(genericTabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: 'Submit the approved form.' },
+ ]);
+ const genericGuard = agent._startPlanExecutionGuard(genericTabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ approvedScratchpadText: [
+ '[Approved plan pinned by planner]',
+ '- Submit the approved form.',
+ ].join('\n'),
+ });
+ genericGuard.verifiedSubmissionEvidence = true;
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(genericTabId, provider), false);
+ assert.equal(genericGuard.siteWorkflow, null);
+ assert.equal(genericGuard.verifiedSubmissionEvidence, true);
+ }
+});
+
+test('multi-platform social publication requires verified evidence for every destination', async () => {
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({});
+ agent.useSiteAdapters = true;
+ agent._persist = () => {};
+ agent._ensureWorkflowMetadataRequirements = async () => {};
+ const tabId = 9075 + index;
+ const taskText = 'Post this update on X and Bluesky.';
+ const approvedScratchpadText = [
+ '[Approved plan pinned by planner]',
+ '- Post this update on X and Bluesky.',
+ ].join('\n');
+ agent.conversations.set(tabId, [
+ { role: 'system', content: 'system' },
+ { role: 'user', content: taskText },
+ ]);
+
+ const twitterWorkflow = agent._resolvePlannerSiteWorkflow('https://x.com/compose/post', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ let guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow: twitterWorkflow,
+ siteWorkflowUrl: 'https://x.com/compose/post',
+ approvedScratchpadText,
+ });
+ guard.successfulConsequentialToolCalls = 1;
+ guard.evidenceTaskKey = guard.taskKey;
+
+ // A candidate permalink alone is not enough to checkpoint a destination.
+ agent._recordSocialPublishTargetSatisfied(guard);
+ assert.deepEqual(guard.socialPublishSatisfiedTargets, [],
+ AgentClass.name + ': an unverified first destination was checkpointed');
+
+ guard.workflowTerminalEvidence = {
+ bindingKey: agent._adapterWorkflowBindingKey(guard.siteWorkflow),
+ job: guard.siteWorkflow.job.id,
+ verificationKind: agent._workflowVerificationKind(guard.siteWorkflow),
+ source: 'dispatch_bound_published_resource',
+ };
+ guard.verifiedSubmissionEvidence = true;
+ agent._recordSocialPublishTargetSatisfied(guard);
+ assert.deepEqual(guard.socialPublishSatisfiedTargets, ['twitter']);
+ assert.deepEqual(agent._missingSocialPublishTargets(guard), ['bluesky']);
+ assert.equal(agent._executionEvidenceSatisfied(guard), false,
+ AgentClass.name + ': one verified platform completed a two-platform task');
+
+ let liveUrl = 'https://bsky.app/';
+ agent._currentUrl = async () => liveUrl;
+ agent._currentProgressPageScope = () => liveUrl;
+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId, {}), true);
+ assert.equal(guard.siteWorkflow.adapterName, 'bluesky');
+ assert.deepEqual(guard.socialPublishSatisfiedTargets, ['twitter'],
+ AgentClass.name + ': rebinding discarded the first platform checkpoint');
+ assert.equal(guard.workflowTerminalEvidence, null);
+
+ // A trusted Continue may occur between destinations; keep the verified
+ // checkpoint so the resumed run is not asked to republish on X.
+ agent._storeContinuationExecutionEvidence(tabId);
+ guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow: guard.siteWorkflow,
+ siteWorkflowUrl: liveUrl,
+ approvedScratchpadText,
+ }, { trustedContinuation: true });
+ assert.deepEqual(guard.socialPublishSatisfiedTargets, ['twitter'],
+ AgentClass.name + ': Continue discarded a verified platform checkpoint');
+
+ guard.workflowTerminalEvidence = {
+ bindingKey: agent._adapterWorkflowBindingKey(guard.siteWorkflow),
+ job: guard.siteWorkflow.job.id,
+ verificationKind: agent._workflowVerificationKind(guard.siteWorkflow),
+ source: 'dispatch_bound_published_resource',
+ };
+ guard.verifiedSubmissionEvidence = true;
+ agent._recordSocialPublishTargetSatisfied(guard);
+ assert.deepEqual(guard.socialPublishSatisfiedTargets, ['twitter', 'bluesky']);
+ assert.deepEqual(agent._missingSocialPublishTargets(guard), []);
+ assert.equal(agent._executionEvidenceSatisfied(guard), true,
+ AgentClass.name + ': both verified platforms did not complete the task');
+ }
+});
+
+test('X and Bluesky same-route publication accepts only one new permalink with the exact reviewed body', () => {
+ const fixtures = [
+ {
+ adapterName: 'twitter',
+ feedUrl: 'https://x.com/home',
+ existingUrl: 'https://twitter.com/webbrain/status/1111111111111111111',
+ publishedUrl: 'https://x.com/webbrain/status/2222222222222222222',
+ otherNewUrl: 'https://x.com/webbrain/status/3333333333333333333',
+ expectedIdentity: 'twitter:status:2222222222222222222',
+ accountIdentity: 'twitter:webbrain',
+ wrongAccountUrl: 'https://x.com/notwebbrain/status/4444444444444444444',
+ displayedRepoUrl: 'github.com/webbrain-one/…',
+ repoLink: {
+ href: 'https://t.co/abc123',
+ text: 'github.com/webbrain-one/…',
+ expandedUrl: 'https://github.com/webbrain-one/webbrain',
+ },
+ },
+ {
+ adapterName: 'bluesky',
+ feedUrl: 'https://bsky.app/',
+ existingUrl: 'https://bsky.app/profile/webbrain.one/post/3abc',
+ publishedUrl: 'https://bsky.app/profile/webbrain.one/post/4DEF',
+ otherNewUrl: 'https://bsky.app/profile/webbrain.one/post/5ghi',
+ expectedIdentity: 'bluesky:bsky.app/profile/webbrain.one/post/4def',
+ accountIdentity: 'bluesky:webbrain.one',
+ wrongAccountUrl: 'https://bsky.app/profile/notwebbrain.test/post/6jkl',
+ displayedRepoUrl: 'github.com/webbrain-one/webbrain',
+ repoLink: {
+ href: 'https://github.com/webbrain-one/webbrain',
+ text: 'github.com/webbrain-one/webbrain',
+ },
+ },
+ ];
+ const body = [
+ '🎉 Milestone Alert! 🎉',
+ '',
+ 'We just passed 1,000 stars and 50 contributors on @GitHub!',
+ '',
+ 'Huge thanks to everyone starring, contributing code, testing local models, and sharing feedback. WebBrain wouldn’t be here without you. 🤗',
+ '',
+ '🔗 https://github.com/webbrain-one/webbrain',
+ '#OpenSource #AI #LocalAI',
+ ].join('\n');
+ for (const [buildIndex, AgentClass] of [AgentCh, AgentFx].entries()) {
+ for (const [fixtureIndex, fixture] of fixtures.entries()) {
+ const agent = new AgentClass({});
+ agent.useSiteAdapters = true;
+ const tabId = 9010 + (buildIndex * 10) + fixtureIndex;
+ const workflow = agent._resolvePlannerSiteWorkflow(fixture.feedUrl, {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ assert.equal(workflow?.adapterName, fixture.adapterName);
+ assert.equal(
+ agent._workflowSocialPublicationAccountIdentity(workflow, fixture.publishedUrl),
+ fixture.accountIdentity,
+ );
+ assert.equal(agent._workflowMetadataFieldKey('Publishing account'), 'account');
+ for (const alias of ['attachment', 'attachments', 'media', 'image', 'photo', 'video', '添付', '附件', '사진']) {
+ assert.equal(agent._workflowMetadataFieldKey(alias), 'attachment',
+ `${AgentClass.name}: ${alias} was not recognized as attachment field`);
+ }
+ const firstLongUrl = 'https://github.com/webbrain-one/webbrain/issues/100';
+ const secondLongUrl = 'https://github.com/webbrain-one/webbrain/issues/200';
+ const repeatedDisplayUrl = 'github.com/webbrain-one/webbrain/…';
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ {
+ field: 'body',
+ value: `First: ${firstLongUrl}\nSecond: ${secondLongUrl}`,
+ },
+ {
+ text: `First: ${repeatedDisplayUrl}\nSecond: ${repeatedDisplayUrl}`,
+ links: [
+ { href: 'https://t.co/first', text: repeatedDisplayUrl, expandedUrl: firstLongUrl },
+ { href: 'https://t.co/second', text: repeatedDisplayUrl, expandedUrl: secondLongUrl },
+ ],
+ },
+ ), true, AgentClass.name + ': repeated shortened URL labels were not consumed positionally');
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ {
+ field: 'body',
+ value: `First: ${firstLongUrl}\nSecond: ${secondLongUrl}`,
+ },
+ {
+ text: `First: ${repeatedDisplayUrl}\nSecond: ${repeatedDisplayUrl}`,
+ links: [
+ { href: 'https://t.co/second', text: repeatedDisplayUrl, expandedUrl: secondLongUrl },
+ { href: 'https://t.co/first', text: repeatedDisplayUrl, expandedUrl: firstLongUrl },
+ ],
+ },
+ ), false, AgentClass.name + ': swapped link destinations were incorrectly accepted');
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow: workflow,
+ });
+ guard.successfulConsequentialToolCalls = 1;
+ guard.workflowMetadataRequirements = [{ field: 'body', value: body }];
+ guard.workflowMetadataRequirementsResolved = true;
+ agent._beginCompletionInvariant(tabId);
+ agent._recordCompletionToolResult(
+ tabId,
+ 'click_ax',
+ { ref_id: 'publish-post' },
+ { success: true, dispatched: true },
+ );
+ agent._recordCompletionSubmitAttempt(
+ tabId,
+ {
+ isSubmit: true,
+ publicationResourceUrls: [fixture.existingUrl],
+ publicationAccountIdentity: fixture.accountIdentity,
+ publicationAccountIdentityComplete: true,
+ },
+ 'click_ax',
+ { ref_id: 'publish-post' },
+ fixture.feedUrl,
+ fixture.feedUrl,
+ { success: true, dispatched: true },
+ );
+ agent._recordCompletionToolResult(tabId, 'read_page', {}, {
+ success: true,
+ url: fixture.feedUrl,
+ content: 'Feed refreshed.',
+ });
+ const submit = agent._completionSubmitStates.get(tabId);
+ assert.equal(submit.workflowBinding?.preDispatchPublicationAccountIdentity, fixture.accountIdentity);
+ assert.equal(submit.workflowBinding?.preDispatchPublicationAccountIdentityComplete, true);
+ assert.equal(agent._completionSubmissionEvidence(
+ tabId,
+ { relevantFormCount: 0, successMessages: [] },
+ fixture.feedUrl,
+ ).verifiedFinalSubmit, false, AgentClass.name + ': same-route feed invented generic submit success');
+
+ const ambiguousPageState = {
+ workflowResourceUrls: [fixture.existingUrl, fixture.publishedUrl, fixture.otherNewUrl],
+ workflowResourceRecords: [
+ { url: fixture.publishedUrl, text: 'WebBrain\n' + body + '\n2m' },
+ { url: fixture.otherNewUrl, text: 'WebBrain\n' + body + '\n1m' },
+ ],
+ };
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ ambiguousPageState,
+ fixture.feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ ), null, AgentClass.name + ': multiple new ' + fixture.adapterName + ' permalinks were bound ambiguously');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, undefined);
+
+ const renderedBody = body.replace('https://github.com/webbrain-one/webbrain', fixture.displayedRepoUrl);
+ const productionNormalizedBody = renderedBody
+ .split('\n')
+ .map(line => line.replace(/[^\S\n]+/g, ' ').trim())
+ .filter(Boolean)
+ .join('\n');
+ const wrongBodyPageState = {
+ workflowResourceUrls: [fixture.existingUrl, fixture.publishedUrl],
+ workflowResourceRecords: [
+ { url: fixture.publishedUrl, text: 'WebBrain\nA different post body.\n2m' },
+ ],
+ };
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ wrongBodyPageState,
+ fixture.feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ ), null, AgentClass.name + ': wrong-body ' + fixture.adapterName + ' post satisfied publication');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, undefined);
+
+ const missingLinkEvidencePageState = {
+ workflowResourceUrls: [fixture.existingUrl, fixture.publishedUrl],
+ workflowResourceRecords: [
+ { url: fixture.publishedUrl, text: 'WebBrain\n' + renderedBody + '\n2m', links: [] },
+ ],
+ };
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ missingLinkEvidencePageState,
+ fixture.feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ ), null, AgentClass.name + ': shortened URL text passed without card-bound link evidence');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, undefined);
+
+ const wrongAccountPageState = {
+ workflowResourceUrls: [fixture.existingUrl, fixture.wrongAccountUrl],
+ workflowResourceRecords: [
+ {
+ url: fixture.wrongAccountUrl,
+ text: 'Not WebBrain\n' + productionNormalizedBody + '\n2m',
+ links: [fixture.repoLink],
+ },
+ ],
+ };
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ wrongAccountPageState,
+ fixture.feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ ), null, AgentClass.name + ': matching body on the wrong publishing account satisfied publication');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, undefined);
+
+ const exactPageState = {
+ workflowResourceUrls: [fixture.existingUrl, fixture.publishedUrl],
+ workflowResourceRecords: [
+ {
+ url: fixture.publishedUrl,
+ text: 'WebBrain\n' + productionNormalizedBody + '\n2m',
+ links: [fixture.repoLink],
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: '',
+ preDispatchPublicationAccountIdentityComplete: false,
+ },
+ guard,
+ exactPageState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': publication passed without an intended-account binding');
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'account', value: fixture.accountIdentity },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.adapterName === 'twitter'
+ ? 'twitter:notwebbrain'
+ : 'bluesky:notwebbrain.test',
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ exactPageState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': requested account hid a conflicting active account at dispatch');
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'image' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ exactPageState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': post without attachments satisfied attachment requirement');
+
+ const pageStateWithImage = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/xyz.jpg', alt: 'screenshot' },
+ ],
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'image' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': post with matching image attachment was rejected');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'video' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': image attachment satisfied video requirement');
+
+ const pageStateWithVideo = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'video', src: 'https://video.twimg.com/media/clip.mp4', alt: 'demo clip' },
+ ],
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'video' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithVideo,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': post with matching video attachment was rejected');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'quarterly-chart.png' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': wrong uploaded asset satisfied specific attachment requirement');
+
+ const pageStateWithSpecificImage = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/quarterly-chart.png', alt: 'quarterly-chart.png' },
+ ],
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'quarterly-chart.png' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithSpecificImage,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': post with matching specific attachment was rejected');
+
+ const pageStateWithTwoImages = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/xyz1.jpg', alt: 'screenshot 1' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/xyz2.jpg', alt: 'screenshot 2' },
+ ],
+ },
+ ],
+ };
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'an image' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': generic attachment phrase "an image" was rejected');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'two images' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': single attachment satisfied requirement for two images');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'two images' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithTwoImages,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': requirement for two images was rejected when two were published');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'an image of quarterly-chart.png' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithSpecificImage,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': specific attachment phrase with generic wrapper was rejected');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'an image of quarterly-chart.png' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': wrong asset satisfied specific attachment phrase with generic wrapper');
+
+ const pageStateWithImageAndVideo = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/xyz1.jpg', alt: 'screenshot 1' },
+ { type: 'video', src: 'https://video.twimg.com/media/clip.mp4', alt: 'demo clip' },
+ ],
+ },
+ ],
+ };
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: '1 image, 1 video' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': single image satisfied requirement for 1 image, 1 video');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: '1 image, 1 video' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithTwoImages,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': two images satisfied requirement for 1 image, 1 video');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: '1 image, 1 video' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImageAndVideo,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': requirement for 1 image, 1 video was rejected when both were published');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'a GIF' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithImage,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': image satisfied requirement for a GIF');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'a GIF' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithVideo,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': an ordinary mp4 satisfied a requirement for a GIF');
+
+ const pageStateWithSpecificGif = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ attachments: [
+ { type: 'video', src: 'https://video.twimg.com/tweet_video/animation.gif.mp4', alt: 'animation.gif' },
+ ],
+ },
+ ],
+ };
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'animation.gif' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithVideo,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': wrong video satisfied requirement for animation.gif');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ ...submit.workflowBinding.metadataRequirements,
+ { field: 'attachment', value: 'animation.gif' },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ pageStateWithSpecificGif,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': matching GIF video was rejected for animation.gif');
+
+ if (fixture.adapterName === 'twitter') {
+ const longBody1 = 'A'.repeat(10500) + ' first suffix';
+ const longBody2 = 'A'.repeat(10500) + ' second suffix';
+ const longBodyState = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ bodyText: longBody1,
+ text: 'WebBrain\n' + longBody1 + '\n2m',
+ },
+ ],
+ };
+ const longBodyMismatchState = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ bodyText: longBody2,
+ text: 'WebBrain\n' + longBody2 + '\n2m',
+ },
+ ],
+ };
+ const longBodyBinding = {
+ ...submit.workflowBinding,
+ metadataRequirements: [
+ { field: 'body', value: longBody1 },
+ ],
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ longBodyBinding,
+ guard,
+ longBodyState,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': full Premium body (>10k chars) was rejected');
+
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ longBodyBinding,
+ guard,
+ longBodyMismatchState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': Premium body with mismatched suffix past 10k chars was accepted');
+ }
+
+ const staleFooterState = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ bodyText: productionNormalizedBody + '\nstale footer text',
+ text: 'WebBrain\n' + productionNormalizedBody + '\nstale footer text\n2m',
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ staleFooterState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': bodyText with stale footer was accepted instead of requiring complete equality');
+
+ const exactBodyTextState = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ bodyText: productionNormalizedBody,
+ text: 'WebBrain\n' + productionNormalizedBody + '\n2m',
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ exactBodyTextState,
+ fixture.feedUrl,
+ submit,
+ ), true, AgentClass.name + ': exact bodyText was rejected');
+
+ if (fixture.adapterName === 'twitter') {
+ const ambiguousLinkPageState = {
+ ...exactPageState,
+ workflowResourceRecords: [
+ {
+ ...exactPageState.workflowResourceRecords[0],
+ links: [{ href: 'https://t.co/ambiguous', text: 'github.com/webbrain-one/…' }],
+ },
+ ],
+ };
+ assert.equal(agent._workflowPublishedResourcePayloadMatch(
+ {
+ ...submit.workflowBinding,
+ publishedResourceIdentity: fixture.expectedIdentity,
+ preDispatchPublicationAccountIdentity: fixture.accountIdentity,
+ preDispatchPublicationAccountIdentityComplete: true,
+ },
+ guard,
+ ambiguousLinkPageState,
+ fixture.feedUrl,
+ submit,
+ ), false, AgentClass.name + ': ambiguous truncated URL label without full URL proof was accepted');
+ }
+
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ exactPageState,
+ fixture.feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ )?.source, 'dispatch_bound_published_resource');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, fixture.expectedIdentity);
+ }
+ }
+});
+
+test('a requested URL keeps the closing delimiter it opened', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const balanced = 'https://en.wikipedia.org/wiki/Function_(mathematics)';
+ assert.equal(agent._workflowTrimUrlPunctuation(balanced), balanced,
+ AgentClass.name + ': a balanced closing parenthesis was stripped from the requested URL');
+ assert.equal(agent._workflowTrimUrlPunctuation(balanced + '.'), balanced,
+ AgentClass.name + ': sentence punctuation after a balanced URL survived');
+ assert.equal(agent._workflowTrimUrlPunctuation('https://example.com/a),'), 'https://example.com/a',
+ AgentClass.name + ': an unopened closer was kept');
+ assert.equal(
+ agent._workflowTrimUrlPunctuation('https://example.com/x?y=(1)'),
+ 'https://example.com/x?y=(1)',
+ );
+ // CJK sentence delimiters survive NFKC and the site keeps them as post
+ // text outside the link.
+ assert.equal(agent._workflowTrimUrlPunctuation('https://example.com/path\u3002'), 'https://example.com/path',
+ AgentClass.name + ': a CJK full stop stayed inside the requested URL');
+ assert.equal(agent._workflowTrimUrlPunctuation('https://example.com/path\u3001'), 'https://example.com/path');
+ assert.equal(agent._workflowTrimUrlPunctuation('https://example.com/path\u2026'), 'https://example.com/path');
+ assert.equal(
+ agent._workflowTrimUrlPunctuation('https://ja.wikipedia.org/wiki/\u95a2\u6570\uff08\u6570\u5b66\uff09\u3002'),
+ 'https://ja.wikipedia.org/wiki/\u95a2\u6570\uff08\u6570\u5b66\uff09',
+ AgentClass.name + ': a balanced full-width closer was stripped with the sentence punctuation',
+ );
+
+ // Sentence delimiters are also valid path characters, so the raw URL wins
+ // whenever the page actually rendered it.
+ // CJK prose runs the delimiter straight into the next clause.
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: '\u8a73\u3057\u304f\u306fhttps://example.com/path\u3002\u7d9a\u5831\u3067\u3059' },
+ {
+ bodyText: '\u8a73\u3057\u304f\u306fexample.com/path\u3002\u7d9a\u5831\u3067\u3059',
+ links: [{ href: 'https://t.co/z', text: 'example.com/path', expandedUrl: 'https://example.com/path' }],
+ },
+ ), true, AgentClass.name + ': a URL ran into the CJK sentence that followed it');
+
+ const yahoo = 'https://en.wikipedia.org/wiki/Yahoo!';
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: `See ${yahoo} now` },
+ {
+ bodyText: `See ${yahoo} now`,
+ links: [{ href: 'https://t.co/z', text: 'en.wikipedia.org/wiki/Yahoo!', expandedUrl: yahoo }],
+ },
+ ), true, AgentClass.name + ': a URL ending in "!" was trimmed even though the post rendered it');
+ // With no evidence the site kept it, the delimiter is still sentence
+ // punctuation and comes off.
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: 'See https://example.com/path! now' },
+ {
+ // The site keeps the delimiter as post text, outside the link.
+ bodyText: 'See example.com/path! now',
+ links: [{ href: 'https://t.co/z', text: 'example.com/path', expandedUrl: 'https://example.com/path' }],
+ },
+ ), true, AgentClass.name + ': trailing sentence punctuation blocked the shortened-link match');
+
+ // The whole point is that exact-body verification still matches the link
+ // the site rendered for a URL shaped like that.
+ assert.equal(agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: `Read ${balanced} today` },
+ {
+ text: 'Read en.wikipedia.org/wiki/Function_… today',
+ links: [{ href: 'https://t.co/abc', text: 'en.wikipedia.org/wiki/Function_…', expandedUrl: balanced }],
+ },
+ ), true, AgentClass.name + ': a URL ending in a balanced closer blocked exact-body verification');
+ }
+});
+
+test('social body verification reads the authored post text, not the card chrome', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ // The account is called WebBrain, so the card's byline equals the body the
+ // task asked for while the post itself says something else entirely.
+ const staleCard = {
+ url: 'https://x.com/webbrain/status/2222222222222222222',
+ text: 'WebBrain\n@webbrain\nA completely different post.\n2m',
+ bodyText: 'A completely different post.',
+ links: [],
+ };
+ assert.equal(
+ agent._workflowSocialPublishedBodyObserved({ field: 'body', value: 'WebBrain' }, staleCard),
+ false,
+ AgentClass.name + ': the author byline satisfied the requested body',
+ );
+ assert.equal(
+ agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: 'A completely different post.' },
+ staleCard,
+ ),
+ true,
+ AgentClass.name + ': the authored post text did not satisfy its own body',
+ );
+ // Without the app's post-text element there is nothing better than the
+ // card, so the previous behavior has to stay available.
+ assert.equal(
+ agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: 'A completely different post.' },
+ { ...staleCard, bodyText: '' },
+ ),
+ true,
+ AgentClass.name + ': a card without app-owned post text lost body verification',
+ );
+ }
+});
+
+test('social body verification prefers authored link over author-profile anchor when body links to own profile', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const ownProfileUrl = 'https://x.com/myhandle';
+ const card = {
+ bodyText: 'Follow my profile x.com/myhandle for updates',
+ links: [
+ // Earlier anchor on the card (e.g. author avatar/name linking to profile)
+ { href: ownProfileUrl, text: 'My Author Name', authored: false },
+ // Authored anchor inside the tweet text
+ { href: ownProfileUrl, text: 'x.com/myhandle', expandedUrl: ownProfileUrl, authored: true },
+ ],
+ };
+ assert.equal(
+ agent._workflowSocialPublishedBodyObserved(
+ { field: 'body', value: `Follow my profile ${ownProfileUrl} for updates` },
+ card,
+ ),
+ true,
+ AgentClass.name + ': should bind to authored anchor when linking to own profile'
+ );
+ }
+});
+
+
+test('a Bluesky DID and handle name one account only on the card that proves it', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const workflow = agent._resolvePlannerSiteWorkflow('https://bsky.app/', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const did = 'bluesky:did:plc:abc123';
+ const handle = 'bluesky:webbrain.one';
+ const cardWithDid = {
+ url: 'https://bsky.app/profile/webbrain.one/post/4def',
+ links: [{ href: 'https://bsky.app/profile/did:plc:abc123' }],
+ };
+ assert.equal(agent._workflowSocialAccountAliasProven(workflow, did, handle, cardWithDid), true,
+ AgentClass.name + ': the card proving the DID belongs to this post was ignored');
+
+ // A mention adds another handle, so a handle-form intent stays ambiguous.
+ assert.equal(agent._workflowSocialAccountAliasProven(
+ workflow,
+ handle,
+ did,
+ {
+ url: 'https://bsky.app/profile/did:plc:abc123/post/4def',
+ links: [
+ { href: 'https://bsky.app/profile/webbrain.one' },
+ { href: 'https://bsky.app/profile/someone.else' },
+ ],
+ },
+ ), false, AgentClass.name + ': an ambiguous card bridged two account identifiers');
+
+ // Two accounts of the same kind are a plain mismatch, never an alias.
+ assert.equal(agent._workflowSocialAccountAliasProven(
+ workflow,
+ 'bluesky:notwebbrain.test',
+ handle,
+ cardWithDid,
+ ), false, AgentClass.name + ': a different handle was accepted as an alias');
+
+ // A link the author wrote in the post body is content, not proof of who
+ // wrote the post. A wrong-account post linking to the requested DID must
+ // not certify itself.
+ assert.equal(agent._workflowSocialAccountAliasProven(
+ workflow,
+ did,
+ 'bluesky:attacker.one',
+ {
+ url: 'https://bsky.app/profile/attacker.one/post/9xyz',
+ links: [{ href: 'https://bsky.app/profile/did:plc:abc123', authored: true }],
+ },
+ ), false, AgentClass.name + ': a body link to the intended DID was accepted as alias proof');
+ assert.equal(agent._workflowSocialAccountAliasProven(
+ workflow,
+ did,
+ 'bluesky:attacker.one',
+ {
+ url: 'https://bsky.app/profile/attacker.one/post/9xyz',
+ links: [
+ { href: 'https://bsky.app/profile/attacker.one' },
+ { href: 'https://bsky.app/profile/did:plc:abc123', authored: true },
+ ],
+ },
+ ), false, AgentClass.name + ': an authored DID link bridged two unrelated accounts');
+ assert.equal(
+ agent._workflowSocialAccountAliasProven(
+ agent._resolvePlannerSiteWorkflow('https://x.com/home', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ }),
+ 'twitter:webbrain',
+ 'twitter:notwebbrain',
+ { links: [] },
+ ),
+ false,
+ AgentClass.name + ': X accounts were bridged by an alias rule that only Bluesky needs',
+ );
+ }
+});
+
+test('a thread published with Post all binds the post carrying the reviewed body', () => {
+ // One dispatch can create several permalinks at once. Requiring exactly one
+ // new identity would leave a published thread unverifiable forever and push
+ // the run toward publishing it a second time.
+ const feedUrl = 'https://x.com/home';
+ const existingUrl = 'https://x.com/webbrain/status/1111111111111111111';
+ const rootUrl = 'https://x.com/webbrain/status/2222222222222222222';
+ const continuationUrl = 'https://x.com/webbrain/status/3333333333333333333';
+ const accountIdentity = 'twitter:webbrain';
+ const body = 'Shipping the workflow kernel today.';
+ const continuation = 'And here is why the evidence contract matters.';
+
+ const armed = (agent, tabId) => {
+ const workflow = agent._resolvePlannerSiteWorkflow(feedUrl, {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow: workflow,
+ });
+ guard.successfulConsequentialToolCalls = 1;
+ guard.workflowMetadataRequirements = [{ field: 'body', value: body }];
+ guard.workflowMetadataRequirementsResolved = true;
+ agent._beginCompletionInvariant(tabId);
+ agent._recordCompletionToolResult(tabId, 'click_ax', { ref_id: 'post-all' }, {
+ success: true, dispatched: true,
+ });
+ agent._recordCompletionSubmitAttempt(
+ tabId,
+ {
+ isSubmit: true,
+ publicationResourceUrls: [existingUrl],
+ publicationAccountIdentity: accountIdentity,
+ publicationAccountIdentityComplete: true,
+ },
+ 'click_ax',
+ { ref_id: 'post-all' },
+ feedUrl,
+ feedUrl,
+ { success: true, dispatched: true },
+ );
+ agent._recordCompletionToolResult(tabId, 'read_page', {}, {
+ success: true, url: feedUrl, content: 'Feed refreshed.',
+ });
+ return agent._completionSubmitStates.get(tabId);
+ };
+
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({});
+ agent.useSiteAdapters = true;
+ const tabId = 9210 + index;
+ const submit = armed(agent, tabId);
+
+ const threadPageState = {
+ workflowResourceUrls: [existingUrl, rootUrl, continuationUrl],
+ workflowResourceRecords: [
+ { url: rootUrl, text: 'WebBrain\n' + body + '\n2m', links: [] },
+ { url: continuationUrl, text: 'WebBrain\n' + continuation + '\n2m', links: [] },
+ ],
+ };
+ assert.equal(agent._workflowTerminalEvidenceFromDone(
+ tabId,
+ threadPageState,
+ feedUrl,
+ { submit, verifiedFinalSubmit: false, relevantForms: 0 },
+ )?.source, 'dispatch_bound_published_resource',
+ AgentClass.name + ': a published thread could not produce terminal evidence');
+ assert.equal(submit.workflowBinding?.publishedResourceIdentity, 'twitter:status:2222222222222222222',
+ AgentClass.name + ': the thread bound a post other than the reviewed body');
+
+ // Two new permalinks that both carry the reviewed body stay ambiguous.
+ const ambiguousAgent = new AgentClass({});
+ ambiguousAgent.useSiteAdapters = true;
+ const ambiguousTabId = 9212 + index;
+ const ambiguousSubmit = armed(ambiguousAgent, ambiguousTabId);
+ assert.equal(ambiguousAgent._workflowTerminalEvidenceFromDone(
+ ambiguousTabId,
+ {
+ workflowResourceUrls: [existingUrl, rootUrl, continuationUrl],
+ workflowResourceRecords: [
+ { url: rootUrl, text: 'WebBrain\n' + body + '\n2m', links: [] },
+ { url: continuationUrl, text: 'WebBrain\n' + body + '\n1m', links: [] },
+ ],
+ },
+ feedUrl,
+ { submit: ambiguousSubmit, verifiedFinalSubmit: false, relevantForms: 0 },
+ ), null, AgentClass.name + ': two matching new permalinks were bound ambiguously');
+ assert.equal(ambiguousSubmit.workflowBinding?.publishedResourceIdentity, undefined);
+ }
+});
+
+test('article-qualified mixed media requirements are counted and typed correctly', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const req1 = agent._parseWorkflowAttachmentRequirement('an image and a video');
+ assert.equal(req1.expectedCount, 2, AgentClass.name + ': expectedCount should be 2 for an image and a video');
+ assert.equal(req1.expectedImageCount, 1, AgentClass.name + ': expectedImageCount should be 1');
+ assert.equal(req1.expectedVideoCount, 1, AgentClass.name + ': expectedVideoCount should be 1');
+ assert.equal(req1.wantsImage, true, AgentClass.name + ': wantsImage should be true');
+ assert.equal(req1.wantsVideo, true, AgentClass.name + ': wantsVideo should be true');
+
+ const req2 = agent._parseWorkflowAttachmentRequirement('an image, a video');
+ assert.equal(req2.expectedCount, 2, AgentClass.name + ': expectedCount should be 2 for an image, a video');
+ assert.equal(req2.expectedImageCount, 1, AgentClass.name + ': expectedImageCount should be 1');
+ assert.equal(req2.expectedVideoCount, 1, AgentClass.name + ': expectedVideoCount should be 1');
+
+ const req3 = agent._parseWorkflowAttachmentRequirement('a photo and a clip');
+ assert.equal(req3.expectedCount, 2, AgentClass.name + ': expectedCount should be 2 for a photo and a clip');
+ assert.equal(req3.expectedImageCount, 1);
+ assert.equal(req3.expectedVideoCount, 1);
+ }
+});
+
+test('extracting post body skips URL scheme colons', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ assert.equal(
+ agent._extractWorkflowTaskBody('Publish this on https://x.com/home: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': URL scheme colon halted body extraction',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post to https://x.com: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': URL scheme colon before domain colon halted body extraction',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post the following on https://bluesky.app/: Announcing v2!'),
+ 'Announcing v2!',
+ AgentClass.name + ': Bluesky URL scheme colon halted body extraction',
+ );
+ }
+});
+
+test('extracting post body supports multilingual commands with colons and quotes', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ assert.equal(
+ agent._extractWorkflowTaskBody('Publica en X: Este es un texto largo para publicar'),
+ 'Este es un texto largo para publicar',
+ AgentClass.name + ': Spanish colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Publícalo en Bluesky: «Bonjour tout le monde»'),
+ 'Bonjour tout le monde',
+ AgentClass.name + ': French colon and guillemets extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Veröffentliche auf X: Dies ist ein langer Text'),
+ 'Dies ist ein langer Text',
+ AgentClass.name + ': German colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Опубликуй в X: Длинный текст поста'),
+ 'Длинный текст поста',
+ AgentClass.name + ': Russian colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Xに投稿:これはテスト投稿です'),
+ 'これはテスト投稿です',
+ AgentClass.name + ': Japanese full-width colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('在X发布:这是长文本内容'),
+ '这是长文本内容',
+ AgentClass.name + ': Chinese full-width colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('X에 게시: 이것은 게시물 내용입니다'),
+ '이것은 게시물 내용입니다',
+ AgentClass.name + ': Korean colon extraction failed',
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Publica en X "texto largo aquí"'),
+ 'texto largo aquí',
+ AgentClass.name + ': Spanish quoted extraction failed',
+ );
+ }
+});
+
+test('classifier fallback leaves metadata requirements incomplete and unresolved', async () => {
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({});
+ const tabId = 9870 + index;
+ const siteWorkflow = agent._resolvePlannerSiteWorkflow('https://x.com/home', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow,
+ });
+ const failingProvider = {
+ chat: async () => {
+ throw new Error('Classifier network error');
+ },
+ };
+ await agent._classifyProgressIntentWithProvider(tabId, {
+ provider: failingProvider,
+ taskText: 'Publish this on X: Hello from fallback',
+ pageScope: 'https://x.com/home',
+ });
+ assert.equal(guard.workflowMetadataRequirementsIncomplete, true,
+ AgentClass.name + ': fallback should mark workflowMetadataRequirementsIncomplete as true');
+ assert.notEqual(guard.workflowMetadataRequirementsResolved, true,
+ AgentClass.name + ': fallback should not mark workflowMetadataRequirementsResolved as true');
+ assert.deepEqual(guard.workflowMetadataRequirements, [{
+ field: 'body',
+ value: 'Hello from fallback',
+ }], AgentClass.name + ': fallback should extract body requirement');
+ }
+});
+
+test('attachment requirement parser ignores numbers in specific attachment filenames', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const req1 = agent._parseWorkflowAttachmentRequirement('quarterly-chart-2.png');
+ assert.equal(req1.expectedCount, 1, AgentClass.name + ': quarterly-chart-2.png should expect 1 attachment');
+ assert.equal(req1.isGeneric, false, AgentClass.name + ': quarterly-chart-2.png should not be generic');
+
+ const req2 = agent._parseWorkflowAttachmentRequirement('photo-2024-12.jpg');
+ assert.equal(req2.expectedCount, 1, AgentClass.name + ': photo-2024-12.jpg should expect 1 attachment');
+ assert.equal(req2.isGeneric, false, AgentClass.name + ': photo-2024-12.jpg should not be generic');
+
+ const req3 = agent._parseWorkflowAttachmentRequirement('2 attachments');
+ assert.equal(req3.expectedCount, 2, AgentClass.name + ': 2 attachments should expect 2 attachments');
+ assert.equal(req3.isGeneric, true, AgentClass.name + ': 2 attachments should be generic');
+
+ const req4 = agent._parseWorkflowAttachmentRequirement('2枚');
+ assert.equal(req4.expectedCount, 2, AgentClass.name + ': 2枚 should expect 2 attachments');
+ assert.equal(req4.isGeneric, true, AgentClass.name + ': 2枚 should be generic');
+
+ const reqBrand = agent._parseWorkflowAttachmentRequirement('brand2images.png');
+ assert.equal(reqBrand.expectedCount, 1, AgentClass.name + ': brand2images.png should expect 1 attachment');
+ assert.equal(reqBrand.expectedImageCount, 0, AgentClass.name + ': brand2images.png should have 0 expectedImageCount');
+ assert.equal(reqBrand.hasExplicitImageCount, false, AgentClass.name + ': brand2images.png should not have explicit image count');
+ assert.equal(reqBrand.hasExplicitCardinality, false, AgentClass.name + ': brand2images.png should not have explicit cardinality');
+ assert.equal(reqBrand.isGeneric, false, AgentClass.name + ': brand2images.png should not be generic');
+ assert.equal(reqBrand.wantsImage, true, AgentClass.name + ': brand2images.png should want image');
+ assert.equal(reqBrand.wantsVideo, false, AgentClass.name + ': brand2images.png should not want video');
+
+ const brandVerified = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'brand2images.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/brand2images.png' }] },
+ );
+ assert.equal(brandVerified, true, AgentClass.name + ': single matching brand2images.png should pass');
+
+ const brandWrongFile = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'brand2images.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/other.png' }] },
+ );
+ assert.equal(brandWrongFile, false, AgentClass.name + ': non-matching file for brand2images.png should fail');
+
+ const reqBrandVid = agent._parseWorkflowAttachmentRequirement('brand2videos.mp4');
+ assert.equal(reqBrandVid.expectedCount, 1, AgentClass.name + ': brand2videos.mp4 should expect 1 attachment');
+ assert.equal(reqBrandVid.expectedVideoCount, 0, AgentClass.name + ': brand2videos.mp4 should have 0 expectedVideoCount');
+ assert.equal(reqBrandVid.hasExplicitVideoCount, false, AgentClass.name + ': brand2videos.mp4 should not have explicit video count');
+ assert.equal(reqBrandVid.isGeneric, false, AgentClass.name + ': brand2videos.mp4 should not be generic');
+ assert.equal(reqBrandVid.wantsVideo, true, AgentClass.name + ': brand2videos.mp4 should want video');
+ assert.equal(reqBrandVid.wantsImage, false, AgentClass.name + ': brand2videos.mp4 should not want image');
+
+ const brandVidVerified = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'brand2videos.mp4' },
+ { attachments: [{ type: 'video', src: 'https://video.twimg.com/media/brand2videos.mp4' }] },
+ );
+ assert.equal(brandVidVerified, true, AgentClass.name + ': single matching brand2videos.mp4 should pass');
+ }
+});
+
+test('attachment requirement parser treats conjunction-based requirements as generic', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const req = agent._parseWorkflowAttachmentRequirement('an image and a video');
+ assert.equal(req.isGeneric, true, AgentClass.name + ': an image and a video should be generic');
+ assert.equal(req.expectedCount, 2, AgentClass.name + ': should expect 2 attachments');
+ assert.equal(req.expectedImageCount, 1, AgentClass.name + ': should expect 1 image');
+ assert.equal(req.expectedVideoCount, 1, AgentClass.name + ': should expect 1 video');
+
+ const verified = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'an image and a video' },
+ { attachments: [{ type: 'image', src: 'pic.png' }, { type: 'video', src: 'vid.mp4' }] }
+ );
+ assert.equal(verified, true, AgentClass.name + ': image plus video should satisfy generic conjunction requirement');
+ }
+});
+
+test('attachment requirement parser recognizes Korean generic media nouns and counts', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const reqImg = agent._parseWorkflowAttachmentRequirement('사진');
+ assert.equal(reqImg.isGeneric, true, AgentClass.name + ': 사진 should be generic');
+ assert.equal(reqImg.wantsImage, true, AgentClass.name + ': 사진 should want image');
+ assert.equal(reqImg.expectedCount, 1, AgentClass.name + ': 사진 should expect 1 attachment');
+
+ const reqVid = agent._parseWorkflowAttachmentRequirement('동영상');
+ assert.equal(reqVid.isGeneric, true, AgentClass.name + ': 동영상 should be generic');
+ assert.equal(reqVid.wantsVideo, true, AgentClass.name + ': 동영상 should want video');
+ assert.equal(reqVid.expectedCount, 1, AgentClass.name + ': 동영상 should expect 1 attachment');
+
+ const reqImg2 = agent._parseWorkflowAttachmentRequirement('사진 2장');
+ assert.equal(reqImg2.isGeneric, true, AgentClass.name + ': 사진 2장 should be generic');
+ assert.equal(reqImg2.expectedCount, 2, AgentClass.name + ': 사진 2장 should expect 2 attachments');
+ assert.equal(reqImg2.expectedImageCount, 2, AgentClass.name + ': 사진 2장 should expect 2 images');
+
+ const reqBoth = agent._parseWorkflowAttachmentRequirement('이미지와 동영상');
+ assert.equal(reqBoth.isGeneric, true, AgentClass.name + ': 이미지와 동영상 should be generic');
+ assert.equal(reqBoth.wantsImage, true, AgentClass.name + ': 이미지와 동영상 should want image');
+ assert.equal(reqBoth.wantsVideo, true, AgentClass.name + ': 이미지와 동영상 should want video');
+ assert.equal(reqBoth.expectedCount, 2, AgentClass.name + ': 이미지와 동영상 should expect 2 attachments');
+
+ const verifiedImg = agent._workflowSocialPublishedAttachmentObserved(
+ { value: '사진' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }] }
+ );
+ assert.equal(verifiedImg, true, AgentClass.name + ': valid image should satisfy 사진 requirement');
+
+ const rejectedImg = agent._workflowSocialPublishedAttachmentObserved(
+ { value: '사진' },
+ { attachments: [{ type: 'video', src: 'https://video.twimg.com/media/clip.mp4' }] }
+ );
+ assert.equal(rejectedImg, false, AgentClass.name + ': video attachment should not satisfy 사진 requirement');
+
+ const verifiedVid = agent._workflowSocialPublishedAttachmentObserved(
+ { value: '동영상' },
+ { attachments: [{ type: 'video', src: 'https://video.twimg.com/media/clip.mp4' }] }
+ );
+ assert.equal(verifiedVid, true, AgentClass.name + ': valid video should satisfy 동영상 requirement');
+
+ const rejectedVid = agent._workflowSocialPublishedAttachmentObserved(
+ { value: '동영상' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }] }
+ );
+ assert.equal(rejectedVid, false, AgentClass.name + ': image attachment should not satisfy 동영상 requirement');
+ }
+});
+
+test('attachment verification requires each media type in unquantified mixed-media requests', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const req = agent._parseWorkflowAttachmentRequirement('image and video');
+ assert.equal(req.isGeneric, true, AgentClass.name + ': image and video should be generic');
+ assert.equal(req.wantsImage, true, AgentClass.name + ': should want image');
+ assert.equal(req.wantsVideo, true, AgentClass.name + ': should want video');
+ assert.equal(req.expectedCount, 2, AgentClass.name + ': should expect at least 2 attachments');
+
+ const twoImages = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'image and video' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }] }
+ );
+ assert.equal(twoImages, false, AgentClass.name + ': two images without video should be rejected for image and video');
+
+ const twoVideos = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'image and video' },
+ { attachments: [{ type: 'video', src: 'clip1.mp4' }, { type: 'video', src: 'clip2.mp4' }] }
+ );
+ assert.equal(twoVideos, false, AgentClass.name + ': two videos without image should be rejected for image and video');
+
+ const imageAndVideo = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'image and video' },
+ { attachments: [{ type: 'image', src: 'pic.png' }, { type: 'video', src: 'clip.mp4' }] }
+ );
+ assert.equal(imageAndVideo, true, AgentClass.name + ': image plus video should satisfy image and video');
+
+ const twoImagesAndVideo = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'image and video' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }, { type: 'video', src: 'clip.mp4' }] }
+ );
+ assert.equal(twoImagesAndVideo, true, AgentClass.name + ': 2 images plus video should satisfy image and video');
+ }
+});
+
+test('attachment verification rejects extra media beyond explicitly requested counts and types', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+
+ const reqOneImg = agent._parseWorkflowAttachmentRequirement('one image');
+ assert.equal(reqOneImg.hasExplicitCardinality, true, AgentClass.name + ': one image should have explicit cardinality');
+ assert.equal(reqOneImg.hasExplicitImageCount, true, AgentClass.name + ': one image should have explicit image count');
+ assert.equal(reqOneImg.expectedCount, 1, AgentClass.name + ': one image should expect 1');
+
+ // one image exact match
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one image' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }] }
+ ),
+ true,
+ AgentClass.name + ': exact one image should pass'
+ );
+
+ // one image with extra image
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one image' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }] }
+ ),
+ false,
+ AgentClass.name + ': extra image beyond one image should be rejected'
+ );
+
+ // one image with unintended video
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one image' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'video', src: 'vid.mp4' }] }
+ ),
+ false,
+ AgentClass.name + ': unintended video with one image should be rejected'
+ );
+
+ // two videos
+ const reqTwoVid = agent._parseWorkflowAttachmentRequirement('two videos');
+ assert.equal(reqTwoVid.hasExplicitCardinality, true, AgentClass.name + ': two videos should have explicit cardinality');
+ assert.equal(reqTwoVid.hasExplicitVideoCount, true, AgentClass.name + ': two videos should have explicit video count');
+ assert.equal(reqTwoVid.expectedCount, 2, AgentClass.name + ': two videos should expect 2');
+
+ // two videos exact match
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two videos' },
+ { attachments: [{ type: 'video', src: 'vid1.mp4' }, { type: 'video', src: 'vid2.mp4' }] }
+ ),
+ true,
+ AgentClass.name + ': exact two videos should pass'
+ );
+
+ // two videos with extra video
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two videos' },
+ { attachments: [{ type: 'video', src: 'vid1.mp4' }, { type: 'video', src: 'vid2.mp4' }, { type: 'video', src: 'vid3.mp4' }] }
+ ),
+ false,
+ AgentClass.name + ': extra video beyond two videos should be rejected'
+ );
+
+ // two videos with unintended image
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two videos' },
+ { attachments: [{ type: 'video', src: 'vid1.mp4' }, { type: 'video', src: 'vid2.mp4' }, { type: 'image', src: 'pic.png' }] }
+ ),
+ false,
+ AgentClass.name + ': unintended image with two videos should be rejected'
+ );
+
+ // one image and two videos
+ const reqMixed = agent._parseWorkflowAttachmentRequirement('one image and two videos');
+ assert.equal(reqMixed.hasExplicitCardinality, true, AgentClass.name + ': one image and two videos should have explicit cardinality');
+ assert.equal(reqMixed.hasExplicitImageCount, true, AgentClass.name + ': should have explicit image count');
+ assert.equal(reqMixed.hasExplicitVideoCount, true, AgentClass.name + ': should have explicit video count');
+ assert.equal(reqMixed.expectedCount, 3, AgentClass.name + ': should expect 3 attachments');
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one image and two videos' },
+ { attachments: [{ type: 'image', src: 'pic.png' }, { type: 'video', src: 'vid1.mp4' }, { type: 'video', src: 'vid2.mp4' }] }
+ ),
+ true,
+ AgentClass.name + ': exact 1 image + 2 videos should pass'
+ );
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one image and two videos' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }, { type: 'video', src: 'vid1.mp4' }, { type: 'video', src: 'vid2.mp4' }] }
+ ),
+ false,
+ AgentClass.name + ': 2 images + 2 videos should be rejected for 1 image and 2 videos'
+ );
+
+ // two attachments
+ const reqTwoAtt = agent._parseWorkflowAttachmentRequirement('two attachments');
+ assert.equal(reqTwoAtt.hasExplicitCardinality, true, AgentClass.name + ': two attachments should have explicit cardinality');
+ assert.equal(reqTwoAtt.expectedCount, 2, AgentClass.name + ': two attachments should expect 2');
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two attachments' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'video', src: 'vid1.mp4' }] }
+ ),
+ true,
+ AgentClass.name + ': 2 attachments should pass'
+ );
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two attachments' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'video', src: 'vid1.mp4' }, { type: 'image', src: 'pic2.png' }] }
+ ),
+ false,
+ AgentClass.name + ': 3 attachments should be rejected for two attachments'
+ );
+
+ // Korean 사진 2장
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: '사진 2장' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }] }
+ ),
+ true,
+ AgentClass.name + ': 2 images should satisfy 사진 2장'
+ );
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: '사진 2장' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }, { type: 'image', src: 'pic3.png' }] }
+ ),
+ false,
+ AgentClass.name + ': 3 images should be rejected for 사진 2장'
+ );
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: '사진 2장' },
+ { attachments: [{ type: 'image', src: 'pic1.png' }, { type: 'image', src: 'pic2.png' }, { type: 'video', src: 'vid.mp4' }] }
+ ),
+ false,
+ AgentClass.name + ': 2 images + 1 video should be rejected for 사진 2장'
+ );
+ }
+});
+
+
+test('attachment verification matches specific attachment names without substring collisions', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+
+ const oldChartUrl = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/old-chart.png', alt: 'old-chart.png' }] }
+ );
+ assert.equal(oldChartUrl, false, AgentClass.name + ': old-chart.png should not satisfy chart.png');
+
+ const notChartUrl = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/not-chart.png', alt: 'not-chart.png' }] }
+ );
+ assert.equal(notChartUrl, false, AgentClass.name + ': not-chart.png should not satisfy chart.png');
+
+ const oldChartAlt = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/random-id.jpg', alt: 'Uploaded old-chart.png' }] }
+ );
+ assert.equal(oldChartAlt, false, AgentClass.name + ': alt with old-chart.png should not satisfy chart.png');
+
+ const exactChartUrl = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/chart.png' }] }
+ );
+ assert.equal(exactChartUrl, true, AgentClass.name + ': chart.png in URL should satisfy chart.png');
+
+ const exactChartAlt = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/random-id.jpg', alt: 'Uploaded chart.png' }] }
+ );
+ assert.equal(exactChartAlt, true, AgentClass.name + ': alt with chart.png should satisfy chart.png');
+
+ const cleanedPrefixAccepted = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'an image of chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/chart.png' }] }
+ );
+ assert.equal(cleanedPrefixAccepted, true, AgentClass.name + ': an image of chart.png should accept chart.png');
+
+ const cleanedPrefixRejected = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'an image of chart.png' },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/old-chart.png' }] }
+ );
+ assert.equal(cleanedPrefixRejected, false, AgentClass.name + ': an image of chart.png should reject old-chart.png');
+
+ // Multiple specific attachment targets
+ const multiSpecificReq = agent._parseWorkflowAttachmentRequirement({ value: 'cat.png and dog.jpg' });
+ assert.equal(multiSpecificReq.expectedCount, 2, AgentClass.name + ': expectedCount for cat.png and dog.jpg should be 2');
+ assert.equal(multiSpecificReq.hasExplicitCardinality, true, AgentClass.name + ': hasExplicitCardinality should be true for multi-target');
+ assert.deepEqual(multiSpecificReq.specificTargets, ['cat.png', 'dog.jpg'], AgentClass.name + ': specific targets parsed correctly');
+
+ const bothMatched = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'cat.png and dog.jpg' },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/cat.png' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/dog.jpg' },
+ ],
+ }
+ );
+ assert.equal(bothMatched, true, AgentClass.name + ': both distinct attachments matched should satisfy requirement');
+
+ const duplicateAttachment = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'cat.png and dog.jpg' },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/cat.png' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/cat.png' },
+ ],
+ }
+ );
+ assert.equal(duplicateAttachment, false, AgentClass.name + ': duplicate single attachment cannot satisfy two distinct targets');
+
+ const missingAttachment = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'cat.png and dog.jpg' },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/cat.png' },
+ ],
+ }
+ );
+ assert.equal(missingAttachment, false, AgentClass.name + ': missing second attachment should reject');
+
+ const wrongSecondAttachment = agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'cat.png and dog.jpg' },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/cat.png' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/bird.png' },
+ ],
+ }
+ );
+ assert.equal(wrongSecondAttachment, false, AgentClass.name + ': wrong second attachment should reject');
+
+ // Multilingual conjunctions / delimiters in specific targets
+ for (const conjCase of [
+ 'image1.png, image2.png',
+ 'chart.png und graphic.png',
+ 'foto1.jpg y foto2.jpg',
+ 'pic1.png & pic2.png',
+ 'diagram1.png et diagram2.png',
+ ]) {
+ const parsedConj = agent._parseWorkflowAttachmentRequirement({ value: conjCase });
+ assert.equal(parsedConj.expectedCount, 2, AgentClass.name + `: expectedCount should be 2 for "${conjCase}"`);
+ assert.equal(parsedConj.specificTargets.length, 2, AgentClass.name + `: should parse 2 targets for "${conjCase}"`);
+ }
+
+ // A conjunction inside one filename is part of the name, not a separator.
+ for (const [singleName, expected] of [
+ ['"research and development.png"', 'research and development.png'],
+ ['research and development.png', 'research and development.png'],
+ ['sales & marketing.png', 'sales & marketing.png'],
+ ['\u201cq1 and q2 summary.pdf\u201d', 'q1 and q2 summary.pdf'],
+ ]) {
+ const parsedName = agent._parseWorkflowAttachmentRequirement({ value: singleName });
+ assert.deepEqual(parsedName.specificTargets, [expected],
+ AgentClass.name + `: "${singleName}" should stay one attachment target`);
+ assert.equal(parsedName.expectedCount, 1,
+ AgentClass.name + `: "${singleName}" should expect one attachment`);
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: singleName },
+ { attachments: [{ type: 'image', src: `https://pbs.twimg.com/media/${encodeURIComponent(expected)}` }] },
+ ),
+ true,
+ AgentClass.name + `: the uploaded "${expected}" should satisfy "${singleName}"`,
+ );
+ }
+
+ // A quoted name keeps its conjunction while the list around it still splits.
+ const quotedListReq = agent._parseWorkflowAttachmentRequirement({
+ value: '"research and development.png", "q1 report.png"',
+ });
+ assert.deepEqual(quotedListReq.specificTargets, ['research and development.png', 'q1 report.png'],
+ AgentClass.name + ': quoted names split on the delimiter but not on their own conjunctions');
+
+ // A finished quoted name still ends a target, so the list around it splits.
+ for (const [mixedValue, mixedTargets] of [
+ ['"research and development.png" and cover.jpg', ['research and development.png', 'cover.jpg']],
+ ['cover.jpg and "research and development.png"', ['cover.jpg', 'research and development.png']],
+ ['research and "development.png"', ['research', 'development.png']],
+ ['"my notes" and cover.jpg', ['my notes', 'cover.jpg']],
+ ]) {
+ assert.deepEqual(agent._parseSpecificAttachmentTargets(mixedValue), mixedTargets,
+ AgentClass.name + `: "${mixedValue}" should split around the quoted name`);
+ }
+
+ // An unquoted conjunction still separates two named files.
+ const mixedListReq = agent._parseWorkflowAttachmentRequirement({
+ value: 'research and development.png and cover.jpg',
+ });
+ assert.deepEqual(mixedListReq.specificTargets, ['research and development.png', 'cover.jpg'],
+ AgentClass.name + ': a trailing conjunction between two filenames still splits');
+
+ // A GIF is a video, but an ordinary video is not a GIF.
+ const gifMedia = {
+ mp4: { type: 'video', src: 'https://video.twimg.com/media/clip.mp4' },
+ typed: { type: 'animated_gif', src: 'https://video.twimg.com/tweet_video/loop.mp4' },
+ named: { type: 'video', src: 'https://video.twimg.com/tweet_video/animation.gif.mp4', alt: 'animation.gif' },
+ plain: { type: 'video', src: 'https://cdn.example.com/loop.gif' },
+ };
+ for (const [gifKey, gifLabel] of [['typed', 'a typed animated GIF'], ['named', 'an mp4-served GIF'], ['plain', 'a plain .gif']]) {
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved({ value: 'a GIF' }, { attachments: [gifMedia[gifKey]] }),
+ true,
+ AgentClass.name + `: ${gifLabel} should satisfy a GIF requirement`,
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one video and no GIFs' },
+ { attachments: [gifMedia[gifKey]] },
+ ),
+ false,
+ AgentClass.name + `: ${gifLabel} should not pass a negated GIF requirement`,
+ );
+ }
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved({ value: 'a GIF' }, { attachments: [gifMedia.mp4] }),
+ false,
+ AgentClass.name + ': an ordinary mp4 should not satisfy a GIF requirement',
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'one video and no GIFs' },
+ { attachments: [gifMedia.mp4] },
+ ),
+ true,
+ AgentClass.name + ': an ordinary mp4 should pass a negated GIF requirement',
+ );
+
+ // A singular article counts as exactly one, the same as the word "one".
+ const oneImage = { type: 'image', src: 'https://pbs.twimg.com/media/first.png' };
+ const otherImage = { type: 'image', src: 'https://pbs.twimg.com/media/second.png' };
+ const oneVideo = { type: 'video', src: 'https://video.twimg.com/media/clip.mp4' };
+ for (const articleReq of ['a video', 'an image', 'un video', 'une image', 'ein bild', 'uma imagem']) {
+ assert.equal(agent._parseWorkflowAttachmentRequirement({ value: articleReq }).hasExplicitCardinality, true,
+ AgentClass.name + `: "${articleReq}" should read as an explicit count of one`);
+ }
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved({ value: 'a video' }, { attachments: [oneVideo] }), true,
+ AgentClass.name + ': one video should satisfy "a video"');
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'a video' },
+ { attachments: [oneVideo, { type: 'video', src: 'https://video.twimg.com/media/other.mp4' }] },
+ ),
+ false,
+ AgentClass.name + ': two videos should not satisfy "a video"',
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'an image and a video' },
+ { attachments: [oneImage, oneVideo] },
+ ),
+ true,
+ AgentClass.name + ': one image and one video should satisfy "an image and a video"',
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'an image and a video' },
+ { attachments: [oneImage, otherImage, oneVideo] },
+ ),
+ false,
+ AgentClass.name + ': an extra image should not satisfy "an image and a video"',
+ );
+
+ // Minimum-count qualifiers bound the count from below instead of naming a file.
+ for (const [minReq, minCount] of [
+ ['at least two images', 2],
+ ['at least 2 images', 2],
+ ['minimum of 3 photos', 3],
+ ['no fewer than two images', 2],
+ ['mindestens zwei bilder', 2],
+ ['au moins deux photos', 2],
+ ['al menos dos im\u00e1genes', 2],
+ ['en az 2 foto\u011fraf', 2],
+ ['\u81f3\u5c11\u4e24\u5f20\u56fe\u7247', 2],
+ ['\ucd5c\uc18c 2\uc7a5 \uc0ac\uc9c4', 2],
+ ]) {
+ const parsedMin = agent._parseWorkflowAttachmentRequirement({ value: minReq });
+ assert.equal(parsedMin.isGeneric, true,
+ AgentClass.name + `: "${minReq}" should read as a generic media requirement`);
+ assert.equal(parsedMin.isMinimumCount, true,
+ AgentClass.name + `: "${minReq}" should carry lower-bound semantics`);
+ assert.deepEqual(parsedMin.specificTargets, [],
+ AgentClass.name + `: "${minReq}" should not name an attachment`);
+ assert.equal(parsedMin.expectedCount, minCount,
+ AgentClass.name + `: "${minReq}" should expect ${minCount}`);
+ const images = count => ({
+ attachments: Array.from({ length: count }, (unused, index) => (
+ { type: 'image', src: `https://pbs.twimg.com/media/shot${index}.png` }
+ )),
+ });
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved({ value: minReq }, images(minCount)), true,
+ AgentClass.name + `: exactly ${minCount} attachments should satisfy "${minReq}"`);
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved({ value: minReq }, images(minCount + 1)), true,
+ AgentClass.name + `: more than ${minCount} attachments should satisfy "${minReq}"`);
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved({ value: minReq }, images(minCount - 1)), false,
+ AgentClass.name + `: fewer than ${minCount} attachments should reject "${minReq}"`);
+ }
+
+ // A minimum qualifier applies only to the media count in its own phrase.
+ const image = index => ({ type: 'image', src: `https://pbs.twimg.com/media/image${index}.png` });
+ const video = index => ({ type: 'video', src: `https://video.twimg.com/media/video${index}.mp4` });
+ const scopedImageMinimum = { value: 'at least two images and one video' };
+ const parsedScopedImageMinimum = agent._parseWorkflowAttachmentRequirement(scopedImageMinimum);
+ assert.equal(parsedScopedImageMinimum.isImageMinimum, true,
+ AgentClass.name + ': the image minimum qualifier was not retained');
+ assert.equal(parsedScopedImageMinimum.isVideoMinimum, false,
+ AgentClass.name + ': the image minimum qualifier leaked onto the exact video count');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ scopedImageMinimum,
+ { attachments: [image(1), image(2), video(1)] },
+ ), true, AgentClass.name + ': the exact mixed minimum requirement did not pass');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ scopedImageMinimum,
+ { attachments: [image(1), image(2), image(3), video(1)] },
+ ), true, AgentClass.name + ': an extra image did not satisfy the image minimum');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ scopedImageMinimum,
+ { attachments: [image(1), image(2), video(1), video(2)] },
+ ), false, AgentClass.name + ': the image minimum incorrectly loosened the exact video count');
+
+ const scopedVideoMinimum = { value: 'one image and at least two videos' };
+ const parsedScopedVideoMinimum = agent._parseWorkflowAttachmentRequirement(scopedVideoMinimum);
+ assert.equal(parsedScopedVideoMinimum.isImageMinimum, false,
+ AgentClass.name + ': the video minimum qualifier leaked onto the exact image count');
+ assert.equal(parsedScopedVideoMinimum.isVideoMinimum, true,
+ AgentClass.name + ': the video minimum qualifier was not retained');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ scopedVideoMinimum,
+ { attachments: [image(1), video(1), video(2), video(3)] },
+ ), true, AgentClass.name + ': an extra video did not satisfy the video minimum');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ scopedVideoMinimum,
+ { attachments: [image(1), image(2), video(1), video(2)] },
+ ), false, AgentClass.name + ': the video minimum incorrectly loosened the exact image count');
+
+ const alternativeScopedMinimum = { value: 'at least two images or one video' };
+ const parsedAlternativeScopedMinimum = agent._parseWorkflowAttachmentRequirement(alternativeScopedMinimum);
+ assert.equal(parsedAlternativeScopedMinimum.isImageMinimum, true,
+ AgentClass.name + ': the alternative image minimum qualifier was not retained');
+ assert.equal(parsedAlternativeScopedMinimum.isVideoMinimum, false,
+ AgentClass.name + ': an alternative image minimum leaked onto the exact video count');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ alternativeScopedMinimum,
+ { attachments: [image(1), image(2), image(3)] },
+ ), true, AgentClass.name + ': extra images did not satisfy the alternative image minimum');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ alternativeScopedMinimum,
+ { attachments: [video(1)] },
+ ), true, AgentClass.name + ': one video did not satisfy the exact alternative');
+ assert.equal(agent._workflowSocialPublishedAttachmentObserved(
+ alternativeScopedMinimum,
+ { attachments: [video(1), video(2)] },
+ ), false, AgentClass.name + ': an image minimum loosened the alternative exact video count');
+
+ // An unqualified count stays exact.
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: 'two images' },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/one.png' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/two.png' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/three.png' },
+ ],
+ },
+ ),
+ false,
+ AgentClass.name + ': three attachments should not satisfy an exact two-image requirement',
+ );
+
+ // Negative attachment requirements
+ for (const negReq of [
+ 'no attachments',
+ 'without media',
+ 'without any media',
+ '0 attachments',
+ 'zero attachments',
+ 'none',
+ 'sin archivos',
+ 'sans photos',
+ 'sem anexos',
+ 'senza allegati',
+ 'ohne anhang',
+ 'без вложений',
+ '添付なし',
+ '첨부 없음',
+ '无附件',
+ 'ek yok',
+ ]) {
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: negReq },
+ { attachments: [] }
+ ),
+ true,
+ AgentClass.name + `: text-only post (0 attachments) should satisfy "${negReq}"`
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: negReq },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }] }
+ ),
+ false,
+ AgentClass.name + `: post with attachment should reject "${negReq}"`
+ );
+ }
+
+ // Mixed positive and negative media types
+ const mixedCases = [
+ {
+ req: 'one video and no images',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '2 photos without video',
+ valid: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/2.jpg' },
+ ],
+ invalidExtra: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/2.jpg' },
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' }],
+ },
+ {
+ req: '1 video, 0 images',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: 'un video sin imágenes',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '1 vidéo sans photos',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '1 Video ohne Bilder',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '動画1つ、画像なし',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '동영상 1개, 사진 없음',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: '1个视频,无图片',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: 'no images, no videos',
+ valid: [],
+ invalidExtra: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ invalidWrong: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ },
+ {
+ req: 'videos and no images',
+ valid: [
+ { type: 'video', src: 'https://video.twimg.com/clip1.mp4' },
+ { type: 'video', src: 'https://video.twimg.com/clip2.mp4' },
+ ],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip1.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ {
+ req: 'images only',
+ valid: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic1.jpg' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic2.jpg' },
+ ],
+ invalidExtra: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic1.jpg' },
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ ],
+ invalidWrong: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ },
+ {
+ req: 'video only',
+ valid: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }],
+ invalidExtra: [
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' },
+ ],
+ invalidWrong: [{ type: 'image', src: 'https://pbs.twimg.com/media/pic.jpg' }],
+ },
+ ];
+
+ for (const { req, valid, invalidExtra, invalidWrong } of mixedCases) {
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved({ value: req }, { attachments: valid }),
+ true,
+ AgentClass.name + `: valid post should satisfy "${req}"`
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved({ value: req }, { attachments: invalidExtra }),
+ false,
+ AgentClass.name + `: post with extra forbidden media should reject "${req}"`
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved({ value: req }, { attachments: invalidWrong }),
+ false,
+ AgentClass.name + `: post with wrong media should reject "${req}"`
+ );
+ }
+
+ // Media disjunctions (e.g. "one image or one video")
+ const altReq = 'one image or one video';
+ const parsedAlt = agent._parseWorkflowAttachmentRequirement({ value: altReq });
+ assert.equal(parsedAlt.isAlternative, true, AgentClass.name + ': isAlternative should be true for "one image or one video"');
+ assert.equal(parsedAlt.expectedCount, 1, AgentClass.name + ': expectedCount should be 1 for alternative');
+
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: altReq },
+ { attachments: [{ type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' }] },
+ ),
+ true,
+ AgentClass.name + ': 1 image should satisfy "one image or one video"'
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: altReq },
+ { attachments: [{ type: 'video', src: 'https://video.twimg.com/clip.mp4' }] },
+ ),
+ true,
+ AgentClass.name + ': 1 video should satisfy "one image or one video"'
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: altReq },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' },
+ { type: 'image', src: 'https://pbs.twimg.com/media/2.jpg' },
+ ],
+ },
+ ),
+ false,
+ AgentClass.name + ': 2 images should reject "one image or one video"'
+ );
+ assert.equal(
+ agent._workflowSocialPublishedAttachmentObserved(
+ { value: altReq },
+ {
+ attachments: [
+ { type: 'image', src: 'https://pbs.twimg.com/media/1.jpg' },
+ { type: 'video', src: 'https://video.twimg.com/clip.mp4' },
+ ],
+ },
+ ),
+ false,
+ AgentClass.name + ': simultaneous image and video should reject "one image or one video"'
+ );
+
+ // Media-only generic phrase check
+ const parsedOnly = agent._parseWorkflowAttachmentRequirement({ value: 'images only' });
+ assert.equal(parsedOnly.isGeneric, true, AgentClass.name + ': "images only" should be parsed as generic');
+ assert.equal(parsedOnly.wantsImage, true, AgentClass.name + ': "images only" should want image');
+ }
+});
+
+test('post body extraction prefers colon-introduced body when colon precedes incidental quotes', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ const longBodyWithQuotes = 'Post on X: Here is a long announcement containing "important news" and more updates today';
+ assert.equal(
+ agent._extractWorkflowTaskBody(longBodyWithQuotes),
+ 'Here is a long announcement containing "important news" and more updates today',
+ AgentClass.name + ': colon-introduced body should preserve text containing incidental quotes'
+ );
+
+ const quotedBeforeColon = 'Post "breaking news" on X: see updates now';
+ assert.equal(
+ agent._extractWorkflowTaskBody(quotedBeforeColon),
+ 'breaking news',
+ AgentClass.name + ': quote before colon should take precedence'
+ );
+
+ const colonWrappedInQuotes = 'Post on X: "Hello world with updates"';
+ assert.equal(
+ agent._extractWorkflowTaskBody(colonWrappedInQuotes),
+ 'Hello world with updates',
+ AgentClass.name + ': colon body completely wrapped in quotes should be unwrapped'
+ );
+ }
+});
+
+test('post body extraction skips incidental command colons and parenthesized metadata', () => {
+ for (const AgentClass of [AgentCh, AgentFx]) {
+ const agent = new AgentClass({});
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X (account: @acme): Hello world'),
+ 'Hello world',
+ AgentClass.name + ': parenthesized account metadata with colon should not be captured as body'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X [account: @acme]: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': bracketed account metadata with colon should not be captured as body'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X (account: @acme): Here is a long announcement containing "important news" and more updates today'),
+ 'Here is a long announcement containing "important news" and more updates today',
+ AgentClass.name + ': parenthesized metadata with colon preceding inner quotes should extract full body'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X, account: @acme: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': metadata key prefix with colon should be skipped in favor of payload colon'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Xに投稿(アカウント:@acme):こんにちは世界'),
+ 'こんにちは世界',
+ AgentClass.name + ': Japanese full-width parenthesized account with colon should not be captured as body'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X (account: @acme): Breaking: Version 2 is released'),
+ 'Breaking: Version 2 is released',
+ AgentClass.name + ': body containing colon should preserve colon after payload delimiter'
);
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X at 3:00: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': clock colon in at 3:00 should not be captured as body delimiter'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X at 14:30: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': 24-hour clock colon in at 14:30 should not be captured as body delimiter'
+ );
+ assert.equal(
+ agent._extractWorkflowTaskBody('Post on X at 3:00 PM: Hello world'),
+ 'Hello world',
+ AgentClass.name + ': clock colon with AM/PM should not be captured as body delimiter'
+ );
+ }
+});
+
+test('post body extraction preserves nested quotation marks and does not overwrite full body with prefix', async () => {
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({});
+ const taskText = 'Post “He said "hello" today” on X';
+ const extracted = agent._extractWorkflowTaskBody(taskText);
+ assert.equal(extracted, 'He said "hello" today', AgentClass.name + ': should extract body containing nested quotes');
+
+ const tabId = 9890 + index;
+ const siteWorkflow = agent._resolvePlannerSiteWorkflow('https://x.com/home', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow,
+ });
+ const provider = {
+ chat: async () => ({
+ content: JSON.stringify({
+ workflowFields: [
+ { field: 'body', value: 'He said "hello" today' },
+ ],
+ }),
+ }),
+ };
+ await agent._classifyProgressIntentWithProvider(tabId, {
+ provider,
+ taskText,
+ pageScope: 'https://x.com/home',
+ });
+ assert.equal(guard.workflowMetadataRequirements?.[0]?.value, 'He said "hello" today',
+ AgentClass.name + ': should retain complete classified body without prefix truncation');
+ }
+});
+
+test('partially classified metadata retains incomplete state despite extracted body', async () => {
+ for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {
+ const agent = new AgentClass({});
+ const tabId = 9880 + index;
+ const siteWorkflow = agent._resolvePlannerSiteWorkflow('https://x.com/home', {
+ request_kind: 'execute',
+ site_job: 'publish-post',
+ });
+ const guard = agent._startPlanExecutionGuard(tabId, 'act', {
+ requestKind: 'execute',
+ requiresStateChange: true,
+ requiresSubmission: true,
+ siteWorkflow,
+ });
+ const partialProvider = {
+ chat: async () => ({
+ content: JSON.stringify({
+ workflowFields: [
+ { field: 'body', value: 'Hello world' },
+ { field: 'attachment' }, // omitted value -> discarded
+ ],
+ }),
+ }),
+ };
+ await agent._classifyProgressIntentWithProvider(tabId, {
+ provider: partialProvider,
+ taskText: 'Publish this on X: Hello world with quarterly-chart-2.png',
+ pageScope: 'https://x.com/home',
+ });
+ assert.equal(guard.workflowMetadataRequirementsIncomplete, true,
+ AgentClass.name + ': partial classifier output should mark workflowMetadataRequirementsIncomplete as true');
+ assert.notEqual(guard.workflowMetadataRequirementsResolved, true,
+ AgentClass.name + ': partial classifier output should not mark workflowMetadataRequirementsResolved as true');
+ assert.equal(guard.workflowMetadataRequirements?.length, 1,
+ AgentClass.name + ': valid body field should be preserved');
}
});