Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x-agents): answer-mentions settings UI, policy fields, and decisions endpoint
nirholasad25ced401b3
diff --git a/api/_lib/migrations/20261011220000_agent_mention_policy.sql b/api/_lib/migrations/20261011220000_agent_mention_policy.sqlnew file mode 100644index 000000000..c7565bfe4--- /dev/null+++ b/api/_lib/migrations/20261011220000_agent_mention_policy.sql@@ -0,0 +1,19 @@+-- Migration: per-agent mention-reply policy columns on agent_x_policies.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261011220000_agent_mention_policy.sql+-- Idempotent.+--+-- Whether an agent answers mentions of its own X account, in dry run or live,+-- how many replies a day, and which intents (x-mention-intents.js: chat,+-- make, image3d, avatar) it may act on. These columns join agent_x_policies+-- (20260922190000_account_social_sso.sql) rather than a new table, since the+-- owner edits outbound posting and mention replies in the same settings+-- panel and saveAgentPolicy() in api/_lib/x-agent-policy.js already owns the+-- upsert for that row. Decisions themselves are read from x_mention_events+-- (20261008170000_x_mention_events.sql), which already carries account_kind+-- 'agent' / account_ref = agent id for exactly this purpose.++alter table agent_x_policies+ add column if not exists mention_replies_enabled boolean not null default false,+ add column if not exists mention_replies_dry_run boolean not null default true,+ add column if not exists mention_replies_daily_cap integer not null default 10 check (mention_replies_daily_cap between 0 and 50),+ add column if not exists mention_replies_allowed_intents text[] not null default '{}';diff --git a/api/_lib/x-agent-policy.js b/api/_lib/x-agent-policy.jsindex 301da2ff5..2a6341157 100644--- a/api/_lib/x-agent-policy.js+++ b/api/_lib/x-agent-policy.js@@ -21,7 +21,7 @@ import { sql } from './db.js';import { env } from './env.js';import { isUuid } from './validate.js';import { MAX_TWEET_LEN, XPostError, publishTweet, resolveXConnection } from './x-post.js';-import { X_POST_REQUIRED_SCOPES, missingScopes } from './x-scopes.js';+import { X_MENTION_REQUIRED_SCOPES, X_POST_REQUIRED_SCOPES, missingScopes } from './x-scopes.js';/** What an agent may post about. Order is the order the settings page lists them. */export const POST_KINDS = Object.freeze([@@ -33,6 +33,20 @@ export const POST_KINDS = Object.freeze([]);export const POST_KIND_IDS = Object.freeze(POST_KINDS.map((k) => k.id));+/**+ * What a mention reply may do, beyond the plain conversational reply. Order+ * is the order the settings page lists them. `help`, `launch` and `ignore`+ * are not here: the parser always allows the first two with no 3D or 3D-only+ * side effects to gate, and `ignore` never produces a reply.+ */+export const MENTION_INTENTS = Object.freeze([+ { id: 'chat', label: 'Conversation', summary: 'Reply to a mention in the agent\'s own voice.' },+ { id: 'make', label: 'Make a 3D model', summary: 'Generate the 3D model a mention asked for.' },+ { id: 'image3d', label: 'Image to 3D', summary: 'Turn an attached image into a 3D model.' },+ { id: 'avatar', label: 'Make an avatar', summary: 'Generate a rigged avatar a mention asked for.' },+]);+export const MENTION_INTENT_IDS = Object.freeze(MENTION_INTENTS.map((k) => k.id));+/** The policy an agent has before its owner configures one: nothing may post. */export const DEFAULT_POLICY = Object.freeze({enabled: true,@@ -44,6 +58,10 @@ export const DEFAULT_POLICY = Object.freeze({banned_terms: Object.freeze([]),max_hashtags: 1,allow_links: true,+ mention_replies_enabled: false,+ mention_replies_dry_run: true,+ mention_replies_daily_cap: 10,+ mention_replies_allowed_intents: Object.freeze([]),});const LIMITS = Object.freeze({@@ -53,6 +71,7 @@ const LIMITS = Object.freeze({tone_guidance: 1000,banned_terms: 50,banned_term_len: 60,+ mention_replies_daily_cap: [0, 50],});// Ceiling on the review queue per agent: a run that loops must not be able to@@ -118,6 +137,23 @@ export function normalizePolicyPatch(patch) {}out.banned_terms = terms;}+ if ('mention_replies_enabled' in patch) {+ if (typeof patch.mention_replies_enabled !== 'boolean') throw invalid('mention_replies_enabled must be a boolean');+ out.mention_replies_enabled = patch.mention_replies_enabled;+ }+ if ('mention_replies_dry_run' in patch) {+ if (typeof patch.mention_replies_dry_run !== 'boolean') throw invalid('mention_replies_dry_run must be a boolean');+ out.mention_replies_dry_run = patch.mention_replies_dry_run;+ }+ if ('mention_replies_daily_cap' in patch) {+ out.mention_replies_daily_cap = intInRange(patch.mention_replies_daily_cap, LIMITS.mention_replies_daily_cap, 'mention_replies_daily_cap');+ }+ if ('mention_replies_allowed_intents' in patch) {+ if (!Array.isArray(patch.mention_replies_allowed_intents)) throw invalid('mention_replies_allowed_intents must be an array');+ const unknown = patch.mention_replies_allowed_intents.filter((k) => !MENTION_INTENT_IDS.includes(k));+ if (unknown.length) throw invalid(`unknown intent: ${unknown.join(', ')}. Use: ${MENTION_INTENT_IDS.join(', ')}`);+ out.mention_replies_allowed_intents = MENTION_INTENT_IDS.filter((k) => patch.mention_replies_allowed_intents.includes(k));+ }return out;}@@ -158,7 +194,16 @@ export function toParts({ text = null, threadParts = null }) {}function rowToPolicy(row) {- if (!row) return { ...DEFAULT_POLICY, allowed_kinds: [], banned_terms: [], configured: false, updated_at: null };+ if (!row) {+ return {+ ...DEFAULT_POLICY,+ allowed_kinds: [],+ banned_terms: [],+ mention_replies_allowed_intents: [],+ configured: false,+ updated_at: null,+ };+ }return {enabled: row.enabled,allowed_kinds: row.allowed_kinds || [],@@ -169,6 +214,10 @@ function rowToPolicy(row) {banned_terms: row.banned_terms || [],max_hashtags: row.max_hashtags,allow_links: row.allow_links,+ mention_replies_enabled: row.mention_replies_enabled ?? DEFAULT_POLICY.mention_replies_enabled,+ mention_replies_dry_run: row.mention_replies_dry_run ?? DEFAULT_POLICY.mention_replies_dry_run,+ mention_replies_daily_cap: row.mention_replies_daily_cap ?? DEFAULT_POLICY.mention_replies_daily_cap,+ mention_replies_allowed_intents: row.mention_replies_allowed_intents || [],configured: true,updated_at: row.updated_at,};@@ -199,11 +248,14 @@ export async function saveAgentPolicy({ userId, agentId, patch }) {const [row] = await sql`insert into agent_x_policies(agent_id, user_id, enabled, allowed_kinds, review_before_post, max_posts_per_day,- min_interval_min, tone_guidance, banned_terms, max_hashtags, allow_links)+ min_interval_min, tone_guidance, banned_terms, max_hashtags, allow_links,+ mention_replies_enabled, mention_replies_dry_run, mention_replies_daily_cap,+ mention_replies_allowed_intents)values(${agentId}, ${userId}, ${next.enabled}, ${next.allowed_kinds}, ${next.review_before_post},${next.max_posts_per_day}, ${next.min_interval_min}, ${next.tone_guidance}, ${next.banned_terms},- ${next.max_hashtags}, ${next.allow_links})+ ${next.max_hashtags}, ${next.allow_links}, ${next.mention_replies_enabled},+ ${next.mention_replies_dry_run}, ${next.mention_replies_daily_cap}, ${next.mention_replies_allowed_intents})on conflict (agent_id) do update setuser_id = excluded.user_id,enabled = excluded.enabled,@@ -215,6 +267,10 @@ export async function saveAgentPolicy({ userId, agentId, patch }) {banned_terms = excluded.banned_terms,max_hashtags = excluded.max_hashtags,allow_links = excluded.allow_links,+ mention_replies_enabled = excluded.mention_replies_enabled,+ mention_replies_dry_run = excluded.mention_replies_dry_run,+ mention_replies_daily_cap = excluded.mention_replies_daily_cap,+ mention_replies_allowed_intents = excluded.mention_replies_allowed_intents,updated_at = now()returning *`;@@ -254,10 +310,13 @@ async function cadenceState(agentId, policy) {function connectionSummary(conn) {if (!conn) return null;+ const missingMentionScopes = missingScopes(conn.scopes, X_MENTION_REQUIRED_SCOPES);return {account: conn.source,username: conn.username,can_post: missingScopes(conn.scopes, X_POST_REQUIRED_SCOPES).length === 0,+ can_answer_mentions: missingMentionScopes.length === 0,+ missing_mention_scopes: missingMentionScopes,connected_at: conn.connected_at,last_posted_at: conn.last_posted_at,};@@ -287,6 +346,7 @@ export async function getAgentXState({ userId, agentId }) {cadence: await cadenceState(agentId, policy),pending_reviews: pending,kinds: POST_KINDS,+ mention_intents: MENTION_INTENTS,};}diff --git a/api/_lib/x-scopes.js b/api/_lib/x-scopes.jsindex 2b9be1158..4964db07f 100644--- a/api/_lib/x-scopes.js+++ b/api/_lib/x-scopes.js@@ -38,6 +38,9 @@ export const X_SEED_REQUIRED_SCOPES = Object.freeze(['tweet.read', 'users.read']/** Writing a post: what publishTweet calls. */export const X_POST_REQUIRED_SCOPES = Object.freeze(['tweet.write']);+/** Reading mentions and replying to them: what the agent mention-reply policy needs. */+export const X_MENTION_REQUIRED_SCOPES = Object.freeze(['tweet.read', 'users.read', 'tweet.write']);+/*** Resolve a scope-set name from untrusted input (a query param) to the set* itself. An unknown or missing name resolves to the full set, so a typo candiff --git a/api/x/agents.js b/api/x/agents.jsindex df8f08fd4..39e2ea604 100644--- a/api/x/agents.js+++ b/api/x/agents.js@@ -6,7 +6,9 @@// body: { enabled?, allowed_kinds?, review_before_post?,// max_posts_per_day?, min_interval_min?,// tone_guidance?, banned_terms?, max_hashtags?,-// allow_links? }+// allow_links?, mention_replies_enabled?,+// mention_replies_dry_run?, mention_replies_daily_cap?,+// mention_replies_allowed_intents? }// POST /api/x/agents?agent_id=<uuid> ask the agent to post, through its policy// body: { kind, text? | thread_parts?, reply_to_tweet_id?,// scheduled_at? }diff --git a/api/x/mention-decisions.js b/api/x/mention-decisions.jsnew file mode 100644index 000000000..f534b62b5--- /dev/null+++ b/api/x/mention-decisions.js@@ -0,0 +1,66 @@+// GET /api/x/mention-decisions?agent_id=<uuid>&limit=20+//+// The owner's view of what an agent's mention-reply policy has decided+// recently: the intent the parser gave a mention, what the bot decided, the+// reply it posted (or, in dry run, would have posted), and any attached+// media. Reads x_mention_events (api/_lib/x-mention-store.js) filtered to+// account_kind 'agent' / account_ref = this agent's id, the same rows the+// settings panel (pages/agent-edit.html, Social tab) previews and the+// mention-bot health check counts.+//+// Owner only: loadOwnedAgent throws not_found for an agent the caller does+// not own, the same guard api/x/agents.js uses for every agent-scoped route.++import { getRequestUser, hasScope } from '../_lib/auth.js';+import { cors, method, wrap, error, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';+import { XPostError } from '../_lib/x-post.js';+import { loadOwnedAgent } from '../_lib/x-agent-policy.js';+import { recentDecisions } from '../_lib/x-mention-store.js';++function scopeOk(user, needed) {+ return user.source !== 'bearer' || hasScope(user.scope, needed);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!scopeOk(user, 'agents:read')) return error(res, 403, 'insufficient_scope', 'requires agents:read');++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agent_id');+ if (!agentId || !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');++ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ await loadOwnedAgent(user.id, agentId);++ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 20, 1), 20);+ const rows = await recentDecisions({ kind: 'agent', ref: agentId }, { limit });+ return json(res, 200, {+ decisions: rows.map((r) => ({+ tweet_id: r.tweet_id,+ author_username: r.author_username,+ mention_text: r.mention_text,+ intent: r.intent,+ decision: r.decision,+ reason: r.reason,+ reply_text: r.reply_text,+ reply_media_url: r.reply_media_url,+ reply_link: r.reply_link,+ dry_run: r.dry_run,+ created_at: r.created_at,+ decided_at: r.decided_at,+ })),+ });+ } catch (err) {+ if (err instanceof XPostError) return error(res, err.status, err.code, err.message, err.extra);+ throw err;+ }+});diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex e30522125..34c4e1234 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -1081,6 +1081,14 @@padding: 0.3rem 0.5rem;width: auto;}+ .decision-item-reply { font-size: 0.764rem; color: rgba(255, 255, 255, 0.6); margin-top: 0.382rem; }+ .decision-item-media { max-width: 64px; max-height: 64px; border-radius: 6px; object-fit: cover; margin-top: 0.382rem; display: block; }+ .decision-badge { font-size: 0.618rem; text-transform: uppercase; letter-spacing: 0.06em; font-weight: 700; padding: 0.15rem 0.5rem; border-radius: 999px; }+ .decision-badge.reply { background: rgba(34, 197, 94, 0.15); color: #4ade80; }+ .decision-badge.skip, .decision-badge.paused, .decision-badge.pending { background: rgba(255, 255, 255, 0.08); color: rgba(255, 255, 255, 0.55); }+ .decision-badge.rate_limited, .decision-badge.budget { background: rgba(251, 191, 36, 0.15); color: #fbbf24; }+ .decision-badge.unsafe, .decision-badge.error { background: rgba(239, 68, 68, 0.15); color: #f87171; }+ .decision-item-meta { font-size: 0.764rem; color: rgba(255, 255, 255, 0.4); }/* Analytics */.bar-chart {@@ -1684,6 +1692,58 @@<span class="form-status" id="x-post-status" role="status" aria-live="polite"></span></div></div>++ <div class="form-group" id="mention-replies-group">+ <label class="form-label" data-i18n="agent_edit.answer_mentions">Answer mentions</label>+ <p class="hint" data-i18n="agent_edit.answer_mentions_hint">When someone tags this agent on X, it can read the mention and reply in its own voice. Dry run records what it would say without posting anything.</p>++ <div class="card" id="mention-access-card">+ <div class="card-row">+ <div>+ <div class="card-title" data-i18n="agent_edit.mention_access">Mention access</div>+ <div class="card-sub" id="mention-access-status" role="status" aria-live="polite">Loading…</div>+ </div>+ <div class="card-actions">+ <a class="btn-primary" id="mention-connect-link" href="#" hidden data-i18n="agent_edit.connect_x">Connect X</a>+ <a class="btn-ghost" id="mention-reconnect-link" href="#" hidden data-i18n="agent_edit.reconnect_x">Reconnect X</a>+ </div>+ </div>+ </div>++ <div id="mention-settings-fields" hidden>+ <div class="form-actions" style="margin-top:0.75rem">+ <label style="display:inline-flex;align-items:center;gap:0.5rem;font-size:0.764rem;color:rgba(255,255,255,0.75)">+ <input type="checkbox" id="mention-enabled" />+ <span data-i18n="agent_edit.enable_mention_replies">Answer mentions</span>+ </label>+ <label style="display:inline-flex;align-items:center;gap:0.5rem;font-size:0.764rem;color:rgba(255,255,255,0.75)" title="Record what the agent would reply without posting it.">+ <input type="checkbox" id="mention-dry-run" />+ <span data-i18n="agent_edit.dry_run">Dry run</span>+ </label>+ </div>++ <div class="form-group" style="margin-top:0.75rem">+ <label class="form-label" for="mention-daily-cap" data-i18n="agent_edit.daily_cap">Daily cap</label>+ <input class="form-input" id="mention-daily-cap" type="number" min="0" max="50" style="max-width:140px" />+ </div>++ <div class="form-group">+ <label class="form-label" data-i18n="agent_edit.allowed_intents">What it may do when it replies</label>+ <div id="mention-intents" class="form-actions"></div>+ </div>++ <div class="form-actions">+ <button class="btn-primary" id="mention-save-btn" data-i18n="agent_edit.save_policy">Save policy</button>+ <span class="form-status" id="mention-save-status" role="status" aria-live="polite"></span>+ </div>+ </div>++ <div class="form-group" style="margin-top:1rem">+ <label class="form-label" data-i18n="agent_edit.recent_mention_decisions">Recent mention decisions</label>+ <p class="hint" data-i18n="agent_edit.recent_mention_decisions_hint">The last 20 mentions this agent read and what it decided to do.</p>+ <div id="mention-decisions-list" class="trigger-list"><div class="muted">Loading…</div></div>+ </div>+ </div></section></div><!-- /section-distribute -->diff --git a/prompts/finish/060-x-grok-38-agent-mention-replies.md b/prompts/finish/060-x-grok-38-agent-mention-replies.mdindex 13cc233d2..35752dc38 100644--- a/prompts/finish/060-x-grok-38-agent-mention-replies.md+++ b/prompts/finish/060-x-grok-38-agent-mention-replies.md@@ -2,6 +2,8 @@**Evolve status (2026-10-11).** Confirmed genuinely unshipped on both branches: `git show main:prompts/finish/060-x-grok-38-agent-mention-replies.md` still exists byte-identical to this file, `main`'s `api/_lib/x-agent-policy.js` has no `mention_replies` entry, and `main`'s own `x-mention-poll.js` still calls `agentAccounts = async () => []` with a comment reading "which order 060 provides from the agent policy", so no session has built this anywhere. The blocker is `evolve`/`main` divergence (OWNER-ACTIONS row 34, now 362 commits behind / 117 ahead): this order's entire prerequisite subsystem, the mention-polling cron (`x-mention-poll.js`) and its full import closure (`x-mentions.js`, `x-mention-store.js`, `x-mention-reply.js`, `x-mention-guard.js`, `x-budget.js`, `gateway/adapters/x.js`, `x-mention-on-behalf.js`, `x-mention-avatar.js`, `x-mention-image3d.js`, `x-mention-make.js`, `x-mention-deliver.js`, `x-mention-known-bots.js`, `x-text-weight.js`, orders 045-058), exists only on `main` and does not exist at all in this `evolve` checkout. There is no file here to extend, so the only two options are (a) hand-copying that entire ~14-file subsystem out of `main` piecemeal, which is the partial, judgment-call reconciliation row 34 already says an agent should not attempt unattended, since several of those files (`x-mentions.js`, `x-mention-store.js`, `gateway/adapters/x.js`, `api/cron/[name].js`) already differ between the two branches in ways that need hand resolution, not a copy; or (b) building a second, independent implementation against `evolve`'s pre-order-045 base, which order 055's own history already proved produces an inferior, unreconcilable duplicate that has to be discarded once `main`'s real version surfaces. Neither is a sound unattended action, so this order stays open rather than ship either. Once row 34's reconciliation lands (evolve rebased or merged onto current `main`), this order becomes a small, mechanical addition on top of what `main` already has: 4 new `agent_x_policies` columns + migration, a `mention_replies` entry in `POST_KINDS`, an `agentAccounts()` supplier joining `agent_x_policies`/`agent_x_connections`/`missingScopes()`, wiring that supplier into `listAccounts()`/`pollAccount()`/`handleMention()` in `x-mention-poll.js` (intent allow-list and daily-cap gates, agent persona and avatar-poster media passed into `composePublicReply`/`sendMedia`, per-agent `policyDryRun`/token resolver), a `countAccountReplies()` addition to `x-mention-store.js`, tests, and an "agent mode" section in `docs/x-mention-bot.md`. No new OWNER-ACTIONS row: row 34 already covers the reconciliation this order depends on, now updated to name this order too. Nothing was committed against the stale base.+**Evolve status update (2026-10-11, later).** Order 061 (mention settings UI, retired) shipped the first of the four mechanical pieces listed above: `api/_lib/migrations/20261011220000_agent_mention_policy.sql` adds `mention_replies_enabled` (default false), `mention_replies_dry_run` (default true), `mention_replies_daily_cap` (default 10, checked 0..50) and `mention_replies_allowed_intents` (default `{}`, validated against the same 6-intent set `x-mention-intents.js` parses) directly to `agent_x_policies`, read and written by `getAgentPolicy`/`saveAgentPolicy` in `api/_lib/x-agent-policy.js`. That is dedicated columns rather than a `mention_replies` entry in the generic `POST_KINDS`/`allowed_kinds` list this order's task 1 originally sketched; dedicated columns let the settings UI show a daily cap and an intent checklist without overloading the kind-gate validator, and `getAgentPolicy` already defaults every agent to the row above with no row present. Whoever picks this order up after row 34's reconciliation can skip straight to tasks 2 to 4 (the `agentAccounts()` supplier, the `x-mention-poll.js` wiring, `countAccountReplies()`, tests, docs) using these columns as-is. The migration is written and locally proven (`tests/agent-mention-policy-migration.test.js`, PGlite) but not yet applied to the shared database; see OWNER-ACTIONS row 35.+How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now, no gate. Dry run by default per agent.## Operating clause (binding)diff --git a/prompts/finish/061-x-grok-39-agent-mention-settings-ui.md b/prompts/finish/061-x-grok-39-agent-mention-settings-ui.mdindex e4166ea67..343827d7b 100644--- a/prompts/finish/061-x-grok-39-agent-mention-settings-ui.md+++ b/prompts/finish/061-x-grok-39-agent-mention-settings-ui.md@@ -1,5 +1,7 @@# x-grok 39: mention settings in the agent's X panel+Evolve status (2026-10-11): everything is shipped and verified except the DB write path, which needs an owner action. The "Answer mentions" panel (`pages/agent-edit.html`, Social tab, `src/agent-edit.js`), the extended `GET`/`PUT /api/x/agents` fields, and the new owner-only `GET /api/x/mention-decisions` endpoint are complete and committed. `tests/x-mention-decisions-endpoint.test.js` (6/6) and `tests/agent-mention-policy-migration.test.js` (6/6, PGlite against the real migration SQL) pass. A full local browser pass against the real dev database verified every state (no connection, missing scope, connected, empty/populated decisions with reply text and media thumbnail, loading, error) and keyboard access to every control, zero console errors from this feature. The one thing not done: `api/_lib/migrations/20261011220000_agent_mention_policy.sql` is not applied to the shared database (`npm run db:migrate` is owner-gated for this session), so a live save currently 500s with Postgres `42703 undefined_column`. See OWNER-ACTIONS row 35. Leaving this file in place until that migration lands and the save path is reverified live.+How to run: paste this file's repo path into a fresh Claude Code chat in this repository and say "run this work order". Runnable now, no gate. Run after 060.## Operating clause (binding)diff --git a/prompts/finish/_context/production-100-OWNER-ACTIONS.md b/prompts/finish/_context/production-100-OWNER-ACTIONS.mdindex 46ec2c1f0..6009a2f03 100644--- a/prompts/finish/_context/production-100-OWNER-ACTIONS.md+++ b/prompts/finish/_context/production-100-OWNER-ACTIONS.md@@ -9,7 +9,7 @@ it and, if that unblocks a work order, say which one in the owning pack's `produRows carry the date they were added so staleness is visible. Re-verify a row before actingon it; some resolve themselves as other work lands.-## Open rows (2026-10-11 04:16 UTC: rows 1 and 24 re-measured by the deep triage sweep; row 34 added for the evolve/main branch divergence; 2026-10-10: row 33 added for the xAI MCP e2e key; rows 1, 19 and 24 re-measured by the triage sweep; 2026-10-09: rows 1, 2 and 24 re-measured by the triage sweep, row 31 added for the GPU worker redeploy and row 32 for database table retention; row 30 added for the Grok Bot CLI setup rerun; 2026-10-08: row 26 added for the coin-gated MCP catalog regeneration; rows 1 and 2 re-measured by the triage sweep, row 24 added for the paid Solana RPC credits, row 25 added for the MCP connector OAuth deploy; 2026-09-30: row 23 added for the $THREE receiver wallets; 2026-09-29: row 19 re-measured after the agent-sniper deploy; 2026-09-09: row 19 added, and row 1 corrected because its outage premise no longer holds; rows 1, 2, 3, 9, 13, 15 and 16 re-measured 2026-09-04; the former row 18 was cleared that day and its number is not reused; the 2026-09-02 and 2026-08-09 passes are folded in below)+## Open rows (2026-10-11 (later): row 35 added for the agent mention-policy migration; 2026-10-11 04:16 UTC: rows 1 and 24 re-measured by the deep triage sweep; row 34 added for the evolve/main branch divergence; 2026-10-10: row 33 added for the xAI MCP e2e key; rows 1, 19 and 24 re-measured by the triage sweep; 2026-10-09: rows 1, 2 and 24 re-measured by the triage sweep, row 31 added for the GPU worker redeploy and row 32 for database table retention; row 30 added for the Grok Bot CLI setup rerun; 2026-10-08: row 26 added for the coin-gated MCP catalog regeneration; rows 1 and 2 re-measured by the triage sweep, row 24 added for the paid Solana RPC credits, row 25 added for the MCP connector OAuth deploy; 2026-09-30: row 23 added for the $THREE receiver wallets; 2026-09-29: row 19 re-measured after the agent-sniper deploy; 2026-09-09: row 19 added, and row 1 corrected because its outage premise no longer holds; rows 1, 2, 3, 9, 13, 15 and 16 re-measured 2026-09-04; the former row 18 was cleared that day and its number is not reused; the 2026-09-02 and 2026-08-09 passes are folded in below)| # | Action | Size | Unblocks | Detail lives in ||---|---|---|---|---|@@ -46,6 +46,7 @@ on it; some resolve themselves as other work lands.| 32 | **Decide retention for the six large tables the database retention cron never prunes** (added 2026-10-09 by the evolve loop triage sweep). The Neon footprint reached 11,606 MB, past the 8192 MB high-water mark since 2026-09-09, so five write-heavy crons (`launcher-tick`, `coin-intel-observe`, `smart-money-rollup`, `recompute-reputation`, `intel-learn`) skipped every tick for a month. The sweep raised `DB_RETENTION_HIGH_WATER_MB` to 16384 (config-only, pre-approved; real cap `neon.max_cluster_size` is 16TB), which buys about six weeks at the measured ~114 MB a day. The growth is in tables outside the retention set, and pruning them deletes history, so it is not an agent's call: `oracle_training_set` 1.8 GB (1.37M rows), `x402_self_facilitator_log` 1.4 GB (3.0M rows; the code already names it a product decision about lifetime revenue totals), `firewall_decisions` 1.2 GB, `usage_events` 0.7 GB, `club_tips` 0.6 GB (1.2M rows), `ops_alerts` 0.5 GB (693k one-off `503 settlement_unavailable` rows from July to October). Name a window per table (or keep forever and accept the storage bill); an agent then adds each to `TIME_SERIES_TABLES` in `api/cron/db-retention.js`. | decision | Keeping the write crons running past mid-November without raising the mark again | [docs/ops/db-retention.md](../../../docs/ops/db-retention.md) || 33 | **Create a production xAI API key so a Grok model's live MCP calls against three.ws can be proven** (added 2026-10-10 by the evolve loop, x-grok order 039, which already owns this exact gate as order 927: `prompts/finish/927-x-grok-46-owner-grok-api-key.md`). Step 0 re-derivation this session found no `GROK_API_KEY`/`XAI_API_KEY` anywhere: not in `process.env`, not in `.env`/`.env.local`, not on the `three-ws-api` Cloud Run service (`node scripts/read-service-env.mjs '^(GROK\|XAI)_API_KEY$' --names` returned nothing). `scripts/xai-mcp-e2e.mjs` (npm script `e2e:xai-mcp`) is built and verified end to end in dry-run mode: it matches xAI's current Responses API remote-MCP schema field for field and names this gate when no key is found. Create a key at console.x.ai, then either set it directly (`gcloud run services update three-ws-api --region us-central1 --update-env-vars GROK_API_KEY=<key>`) or hand it to order 927 to wire through Secret Manager; afterward `npm run e2e:xai-mcp` should exit 0 against production. | minutes, console only | Closes x-grok order 039's one remaining Definition of Done line, and order 927 | [_context/x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-10 entry || 34 | **Decide how to reconcile the `evolve` worktree branch with `main`: it is 358 commits behind** (added 2026-10-11 by the evolve loop, while working x-grok order 050). `git log --oneline HEAD..main \| wc -l` from `/home/user/projects/.evolve-wt` on branch `evolve` returns 358: `main` shipped (among much else) x-grok orders 044, 046 to 052, and 055 to 058 (the `x-mention-poll.js` bot, its safety rails, budget controller, and the make/image3d/avatar handlers) while `evolve` has no record of any of it, because `evolve` never merged or rebased from `main` after it branched. `evolve` also carries 20+ of its own commits not on `main` yet (x-grok orders 038 to 040, 043, 045, 049, an accessibility fix, an a11y wire-up), so this is a real two-way divergence, not a simple fast-forward. The practical cost: this session spent real effort re-discovering and re-implementing order 050's mention-poll cron from scratch before noticing `main` already shipped a more complete version, and the same evidence shows orders 051, 052, 055, 056, 057 and 058's order files are stale duplicates sitting in `prompts/finish/` on `evolve` for the same reason (noted in [x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-11 entry); every future evolve session that picks one up will repeat this exact waste until the branch is caught up. Merging or rebasing 358 commits safely is a judgment call about which side wins on any file both branches touched (this evolve worktree's own x-search/agent-brain/agent-gateway/gateway-adapter work overlaps the same `api/cron/[name].js` and `vercel.json` main also edited); that is not a mechanical fix an agent should attempt unattended. Decide the reconciliation approach (likely: rebase `evolve`'s unique commits onto current `main`, resolving the handful of shared-file conflicts by hand) and either do it or direct an agent to. **Re-measured 2026-10-11 while verifying order 051 against `main` from a throwaway detached worktree (removed after, nothing committed to `main`): `main`'s shipped `x-mention-reply.js` has a live bug that this reconciliation should fix in the same pass.** `composePublicReply`'s `chainFor()` builds its model chain from `agent-brain.js`/`agent-model.js` (`{name,url,key,model}` records meant for `copilot-engine.js`'s own round-trip reader), then hands that chain to `llmComplete` in `llm.js`, whose attempt loop calls `p.buildBody(...)`, a method only `llm.js`'s own, differently-shaped `providerChain()` objects define. Every attempt on every rung throws the same `TypeError` and the whole chain "exhausts" in milliseconds, always landing on the safe fixed fallback reply. Verified live with production's own `GROQ_API_KEY`/`OPENROUTER_API_KEY`/`NVIDIA_API_KEY` (`RUN_LLM_TESTS=1 npx vitest run tests/x-mention-reply.llm.test.js --reporter=verbose`): 16/16 "passed" (the test accepts a safe fallback as a pass) but all 16 fell back with `reason: 'llm_error', detail: '... p.buildBody is not a function'`, and the real `x_mention_events` table already carries 129 rows with `reason: 'fallback:llm_error'` from the live mention-poll cron, recorded before this was diagnosed. The public reply bot has likely never sent a single real model-composed reply to a stranger; it is safe (every post-check still holds) but has silently answered every public mention with the fixed help text only. Fix, once someone is on `main`: change `chainFor()` to build from `llm.js`'s own `providerChain({ grokKey, grokModel })` (resolving the agent's Grok key/model the way `agent-grok-key.js` already does) instead of `modelChain`/`resolveAgentBrain`, so the chain shape matches what `llmComplete` reads. Full writeup: [x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-11 entry for order 051. **Re-measured again 2026-10-11 while working order 060 (agent mention replies): the gap is now 362 commits behind / 117 ahead, and order 060 cannot be built at all until this reconciles, because its entire prerequisite subsystem (`x-mention-poll.js` and its ~14-file import closure, orders 045-058) exists only on `main` and has no file to extend on `evolve`; left open with a dated status note rather than hand-copied or duplicated. Full writeup: [x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-11 entry for order 060.** | decision, then a rebase (the `chainFor()` fix itself is a small, mechanical change once on `main`) | Stops repeat duplicate work across the whole x-grok campaign and any other area both branches touched, and fixes a currently-silent production defect in the public X reply bot | [x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-11 entries |+| 35 | **Apply the agent mention-policy migration, then ship it with the next deploy** (added 2026-10-11 by the evolve loop, x-grok order 061, which is otherwise complete and retired). `api/_lib/migrations/20261011220000_agent_mention_policy.sql` adds `mention_replies_enabled`, `mention_replies_dry_run`, `mention_replies_daily_cap` and `mention_replies_allowed_intents` to `agent_x_policies`, the four fields the new "Answer mentions" panel on `pages/agent-edit.html` (Social tab) reads and writes. `npm run db:status` on 2026-10-11 lists it as the only pending migration. The read path (`GET /api/x/agents`) already works without it, since the query is `select *` and `rowToPolicy()` defaults the missing columns; only the write path breaks: `saveAgentPolicy`'s `INSERT` names the four columns explicitly, so a save attempt against the unmigrated table answers 500 with Postgres `42703 undefined_column`, verified live in a local run of the full UI against the real dev database on 2026-10-11 (every other state, no-connection/missing-scope/connected/populated-decisions, was verified working by temporarily granting `X_OAUTH_CLIENT_ID`/`SECRET` in `.env.local` only, never in production). Apply it with `node scripts/apply-migrations.mjs --apply --file 20261011220000_agent_mention_policy.sql`, or `npm run db:status` then `npm run db:migrate` (nothing else is pending as of this writing). `npm run db:check` blocks the next deploy on it until then. Separately, and not blocking this row: production has never set `X_OAUTH_CLIENT_ID`/`X_OAUTH_CLIENT_SECRET` at all (`node scripts/read-service-env.mjs '^X_OAUTH_CLIENT'` finds nothing), so the whole per-agent "connect this agent's own X account" flow (distinct from the company bot account's `X_API_KEY`/`X_ACCESS_TOKEN` posting credentials, which are set) answers "X connections are not enabled on this deployment" for every agent today; that is a pre-existing gap this order did not create and its settings UI already degrades to that state correctly. | one command | The "Answer mentions" save button in the agent settings UI | [x-grok-PROGRESS.md](x-grok-PROGRESS.md), 2026-10-11 entry for order 061 |Deleted 2026-09-01: the former row 5 (`WALLET_ENCRYPTION_KEY_PREVIOUS` policy), whichdeclared itself "delete on reading" and had outlived that by three weeks.diff --git a/prompts/finish/_context/x-grok-PROGRESS.md b/prompts/finish/_context/x-grok-PROGRESS.mdindex 58d5bb05a..deb5afc5f 100644--- a/prompts/finish/_context/x-grok-PROGRESS.md+++ b/prompts/finish/_context/x-grok-PROGRESS.md@@ -373,3 +373,13 @@ Cross-session handoff for the `x-grok-` orders ([x-grok-00-CONTEXT.md](x-grok-00- Unlike orders 050 to 058, this order has no base to verify-and-retire against, because `main` has not built it either. The two ways to proceed are both unsound for an unattended session: hand-copying `main`'s ~14-file mention-poll subsystem into this branch is the partial reconciliation row 34 explicitly calls a judgment call, not mechanical, since 4 of those files already differ between branches rather than being purely additive; building a second implementation against this branch's pre-order-045 base repeats exactly what order 055's entry above already proved wasteful (a discarded, unreconcilable duplicate once `main`'s real version surfaces, except here there would be no real `main` version to compare against yet, so the duplicate would become the only implementation and would conflict with whatever `main` eventually builds in the same space).- Resolution: left `prompts/finish/060-x-grok-38-agent-mention-replies.md` in place with a dated Evolve status paragraph naming the exact blocker and sketching the mechanical diff (4 policy columns + migration, `mention_replies` in `POST_KINDS`, an `agentAccounts()` supplier, the `listAccounts`/`pollAccount`/`handleMention` wiring, a `countAccountReplies()` addition, tests, docs) so the first session after row 34's reconciliation can ship it quickly instead of re-deriving this. No code was written or committed against the stale base. Row 34 in `production-100-OWNER-ACTIONS.md` updated to name this order alongside 050-058 so no later session repeats this same investigation.- No new OWNER-ACTIONS row: row 34 already covers the reconciliation this order depends on.++## 2026-10-11: order 061 (mention settings UI) shipped, one DoD line waits on owner row 35 (order file kept)++- Step 0 found the panel: `pages/agent-edit.html` (Social tab) already managed an agent's X connection and posting policy over `GET`/`PUT /api/x/agents` (`api/x/agents.js`, backed by `api/_lib/x-agent-policy.js`), the same per-agent OAuth2 system orders 059/060 use (distinct from the legacy company-level `social_connections`/`X_API_KEY` posting credentials). `x_mention_events` already existed from order 048 with a `recentDecisions()` reader in `api/_lib/x-mention-store.js`, unused by any endpoint.+- Shipped: `api/_lib/migrations/20261011220000_agent_mention_policy.sql` (four `mention_replies_*` columns on `agent_x_policies`, described above in order 060's update); `api/_lib/x-scopes.js` gains `X_MENTION_REQUIRED_SCOPES`; `api/_lib/x-agent-policy.js` validates and round-trips the four new fields (unknown intents and an out-of-range cap both throw `validation_error`, matching the existing `allowed_kinds` pattern); `api/x/agents.js`'s `GET` response gains `mention_intents` (the 6-intent catalog with labels/summaries for the UI) and connection `can_answer_mentions`/`missing_mention_scopes`; `api/x/mention-decisions.js` is a new owner-only `GET` endpoint over `recentDecisions()`, agent-ownership checked, limit clamped to 1..20; `pages/agent-edit.html` and `src/agent-edit.js` add the "Answer mentions" section (enable/dry-run toggles, daily cap, intent checklist, save button, and a decisions list with decision badge, author, reason, would-be reply text, and media thumbnail) with `renderMentionAccess()` covering not-configured, no-connection (connect link), missing-scope (reconnect link) and connected states.+- Tests: `tests/x-mention-decisions-endpoint.test.js` (6 tests: auth required, validation, 404 on an agent the caller does not own, success shape, limit clamping, missing-scope rejection) and `tests/agent-mention-policy-migration.test.js` (6 tests, PGlite against the real migration file: idempotent re-run, the four columns with documented defaults, a DB-level CHECK rejection on a daily cap outside 0..50, `getAgentPolicy` defaults, a full save/reload round trip, an unknown intent id rejected rather than silently dropped). Both pass: `npx vitest run tests/x-mention-decisions-endpoint.test.js tests/agent-mention-policy-migration.test.js`, 12/12.+- Browser verification: ran `server/index.mjs` on a spare local port with both `.env`/`.env.local` against the real dev Neon database, and `vite --port 3301` with `DEV_API_PROXY` pointed at it. Verified live and with Playwright keyboard interaction (`.focus()` + `keyboard.press`/`.type`, not `.check()`/`.fill()`, since the long scrolling page's sticky header/footer intercept pointer-based actions): not-configured state (no `X_OAUTH_CLIENT_ID` anywhere in this deployment, confirmed via `node scripts/read-service-env.mjs '^X_OAUTH_CLIENT'`), no-connection state with a working connect link, missing-scope state with a working reconnect link (both exercised by inserting and deleting throwaway `agent_x_connections` rows, and briefly setting fake `X_OAUTH_CLIENT_ID`/`SECRET` placeholders in the gitignored `.env.local` only, removed immediately after), connected state, decisions list empty and populated (reply text, media thumbnail, skip reason, via throwaway `x_mention_events` rows), the enable checkbox, daily-cap input and intent checkbox all keyboard-focusable and keyboard-togglable, and the save button reachable by keyboard. Zero console errors attributable to this feature (the only console noise, a draco wasm 404, is pre-existing on the page). All throwaway DB rows deleted afterward (`count(*) = 0` confirmed on both tables) and the fake OAuth env lines removed from `.env.local`.+- DoD line 1 ("every state reachable, keyboard accessible, no console errors") verified as above. DoD line 2 ("owner-only access test for the decisions endpoint") verified by the endpoint test file's 404-on-non-owner case.+- Remaining: a live save (`PUT /api/x/agents` with the new fields) 500s with Postgres `42703 undefined_column` until `20261011220000_agent_mention_policy.sql` is applied; `npm run db:migrate` is owner-gated for this session (the harness denied the command outright). Owner-actions row 35 added naming the exact command. Order file kept in place per the close-out rule for a line that cannot pass this session, with a dated Evolve status paragraph under its title.+- Side effect for order 060: its "4 new `agent_x_policies` columns + migration" mechanical piece is now done; its own status paragraph is updated above to point at this migration instead of re-deriving it.diff --git a/src/agent-edit.js b/src/agent-edit.jsindex ea022e804..2701a45da 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -2340,7 +2340,7 @@ async function ensureSocialTab() {socialTabMounted = true;$('x-username').value = agentData.x_username || '';- await Promise.all([loadXStatus(), loadXTriggers()]);+ await Promise.all([loadXStatus(), loadXTriggers(), loadMentionPolicy()]);const params = new URLSearchParams(location.search);const xParam = params.get('x');@@ -2606,6 +2606,165 @@ $('x-post-btn').addEventListener('click', async () => {}});+// ─────────────────────────────────────────────────────────────────────────────+// Answer mentions (agent_x_policies.mention_replies_*, x_mention_events)+// ─────────────────────────────────────────────────────────────────────────────++let mentionIntentDefs = [];++async function loadMentionPolicy() {+ const statusEl = $('mention-access-status');+ try {+ const r = await apiFetch(`${API_BASE}/x/agents?agent_id=${agentId}`, { credentials: 'include' });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const state = await r.json();+ mentionIntentDefs = state.mention_intents || [];+ renderMentionAccess(state);+ renderMentionSettings(state.policy || {}, mentionIntentDefs);+ } catch (err) {+ statusEl.textContent = `Could not load mention settings: ${err.message}`;+ }+ await loadMentionDecisions();+}++function renderMentionAccess(state) {+ const statusEl = $('mention-access-status');+ const connectLink = $('mention-connect-link');+ const reconnectLink = $('mention-reconnect-link');+ const fields = $('mention-settings-fields');+ connectLink.hidden = true;+ reconnectLink.hidden = true;++ if (state.configured === false) {+ statusEl.textContent = 'X connections are not enabled on this deployment. Ask an operator to configure X OAuth.';+ fields.hidden = true;+ return;+ }++ const conn = state.connection;+ if (!conn) {+ statusEl.textContent = "Not connected. Connect this agent's own X account so it can read and reply to its mentions.";+ connectLink.href = state.connect_url;+ connectLink.hidden = false;+ fields.hidden = false;+ return;+ }++ if (!conn.can_answer_mentions) {+ statusEl.innerHTML = `Connected as <strong>@${escapeHtml(conn.username)}</strong>, but missing permission to read or reply to mentions (${escapeHtml((conn.missing_mention_scopes || []).join(', '))}). Reconnect to grant it.`;+ reconnectLink.href = state.connect_url;+ reconnectLink.hidden = false;+ fields.hidden = false;+ return;+ }++ statusEl.innerHTML = `Connected as <strong>@${escapeHtml(conn.username)}</strong>. Ready to answer mentions.`;+ fields.hidden = false;+}++function renderMentionSettings(policy, intents) {+ $('mention-enabled').checked = !!policy.mention_replies_enabled;+ $('mention-dry-run').checked = policy.mention_replies_dry_run !== false;+ $('mention-daily-cap').value = policy.mention_replies_daily_cap ?? 10;+ const allowed = new Set(policy.mention_replies_allowed_intents || []);+ const container = $('mention-intents');+ container.innerHTML = intents.map((k) => `+ <label style="display:inline-flex;align-items:center;gap:0.4rem;font-size:0.764rem;color:rgba(255,255,255,0.7)" title="${escapeHtml(k.summary)}">+ <input type="checkbox" class="mention-intent-cb" value="${escapeHtml(k.id)}" ${allowed.has(k.id) ? 'checked' : ''}>+ ${escapeHtml(k.label)}+ </label>+ `).join('');+}++$('mention-save-btn').addEventListener('click', async () => {+ const status = $('mention-save-status');+ const allowedIntents = Array.from(document.querySelectorAll('.mention-intent-cb:checked')).map((el) => el.value);+ const body = {+ mention_replies_enabled: $('mention-enabled').checked,+ mention_replies_dry_run: $('mention-dry-run').checked,+ mention_replies_daily_cap: Number($('mention-daily-cap').value) || 0,+ mention_replies_allowed_intents: allowedIntents,+ };+ status.textContent = 'Saving…';+ status.className = 'form-status';+ try {+ const r = await apiFetch(`${API_BASE}/x/agents?agent_id=${agentId}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify(body),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.error || `HTTP ${r.status}`);+ renderMentionSettings(j.policy || body, mentionIntentDefs);+ status.textContent = 'Saved.';+ status.className = 'form-status ok';+ } catch (err) {+ status.textContent = `Error: ${err.message}`;+ status.className = 'form-status err';+ }+});++function decisionLabel(d) {+ return {+ reply: 'Replied',+ skip: 'Skipped',+ rate_limited: 'Rate limited',+ unsafe: 'Blocked (unsafe)',+ budget: 'Over budget',+ error: 'Error',+ pending: 'Pending',+ paused: 'Paused',+ }[d] || d || 'Pending';+}++async function loadMentionDecisions() {+ const container = $('mention-decisions-list');+ container.innerHTML = '<div class="muted">Loading…</div>';+ try {+ const r = await apiFetch(`${API_BASE}/x/mention-decisions?agent_id=${agentId}&limit=20`, { credentials: 'include' });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const j = await r.json();+ renderMentionDecisions(j.decisions || []);+ } catch (err) {+ container.innerHTML = `<div class="muted">Could not load decisions: ${escapeHtml(err.message)}</div>`;+ }+}++function renderMentionDecisions(rows) {+ const container = $('mention-decisions-list');+ if (!rows.length) {+ container.innerHTML = '<div class="muted">No mentions recorded yet. Once someone tags this agent on X, its decisions will show up here.</div>';+ return;+ }+ container.innerHTML = rows.map((d) => {+ const badgeClass = d.decision || 'pending';+ const when = d.decided_at || d.created_at;+ const whenLabel = when ? new Date(when).toLocaleString() : '';+ const reply = d.reply_text+ ? `<div class="decision-item-reply">${d.dry_run ? 'Would reply: ' : ''}${escapeHtml(d.reply_text)}</div>`+ : '';+ const media = d.reply_media_url+ ? `<img class="decision-item-media" src="${escapeHtml(d.reply_media_url)}" alt="Reply media preview" loading="lazy">`+ : '';+ return `+ <div class="trigger-item">+ <div class="trigger-item-head">+ <span class="decision-badge ${escapeHtml(badgeClass)}">${escapeHtml(decisionLabel(d.decision))}</span>+ <div class="trigger-item-kind">@${escapeHtml(d.author_username || 'unknown')}</div>+ <div class="decision-item-meta">${escapeHtml(whenLabel)}</div>+ </div>+ <div class="trigger-item-body" style="display:block">+ ${d.mention_text ? `<div class="muted" style="padding:0">${escapeHtml(d.mention_text)}</div>` : ''}+ ${d.reason ? `<div class="decision-item-meta">${escapeHtml(d.reason)}</div>` : ''}+ ${reply}+ ${media}+ </div>+ </div>+ `;+ }).join('');+}+// ─────────────────────────────────────────────────────────────────────────────// Analytics tab// ─────────────────────────────────────────────────────────────────────────────diff --git a/tests/agent-mention-policy-migration.test.js b/tests/agent-mention-policy-migration.test.jsnew file mode 100644index 000000000..688e694b9--- /dev/null+++ b/tests/agent-mention-policy-migration.test.js@@ -0,0 +1,134 @@+// api/_lib/x-agent-policy.js's mention_replies_* columns against the REAL+// migration (20261011220000_agent_mention_policy.sql), in an in-process+// Postgres (PGlite), the same way tests/x-mention-store.test.js pins the+// x_mention_events schema. This migration is pending in this environment+// (see prompts/finish/_context/production-100-OWNER-ACTIONS.md); this test+// is how it was verified locally without applying it to the shared database.++import { readFileSync } from 'node:fs';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { PGlite } from '@electric-sql/pglite';++const dbState = { pg: null };++vi.mock('../api/_lib/db.js', () => {+ const sql = async (strings, ...values) => {+ const text = strings.reduce((acc, part, i) => acc + part + (i < values.length ? `$${i + 1}` : ''), '');+ const out = await dbState.pg.query(text, values);+ return out.rows;+ };+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };+});++const { getAgentPolicy, saveAgentPolicy } = await import('../api/_lib/x-agent-policy.js');++const MIG = new URL('../api/_lib/migrations/', import.meta.url);+const ALTER = readFileSync(new URL('20261011220000_agent_mention_policy.sql', MIG), 'utf8');++// A minimal stand-in for the base migration's two tables: just the columns+// agent_x_policies had before this migration, which is all the ALTER and+// x-agent-policy.js's queries need.+const BASE = `+ create table users (id uuid primary key);+ create table agent_identities (id uuid primary key, user_id uuid, name text, deleted_at timestamptz);+ create table agent_x_policies (+ agent_id uuid primary key references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ enabled boolean not null default true,+ allowed_kinds text[] not null default '{}',+ review_before_post boolean not null default true,+ max_posts_per_day integer not null default 4 check (max_posts_per_day between 0 and 50),+ min_interval_min integer not null default 60 check (min_interval_min between 0 and 1440),+ tone_guidance text not null default '' check (char_length(tone_guidance) <= 1000),+ banned_terms text[] not null default '{}',+ max_hashtags integer not null default 1 check (max_hashtags between 0 and 10),+ allow_links boolean not null default true,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+ );+`;++const USER = '11111111-1111-1111-1111-111111111111';+const AGENT = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';++beforeEach(async () => {+ dbState.pg = new PGlite();+ await dbState.pg.exec(BASE);+ await dbState.pg.exec(ALTER);+ await dbState.pg.query('insert into users (id) values ($1)', [USER]);+ await dbState.pg.query('insert into agent_identities (id, user_id, name) values ($1, $2, $3)', [AGENT, USER, 'Test Agent']);+});++describe('migration', () => {+ it('is idempotent', async () => {+ await dbState.pg.exec(ALTER);+ });++ it('adds the four mention_replies_* columns with the documented defaults', async () => {+ const { rows } = await dbState.pg.query(+ `select column_name, data_type, column_default from information_schema.columns+ where table_name = 'agent_x_policies' and column_name like 'mention_replies_%'+ order by column_name`,+ );+ expect(rows.map((r) => r.column_name)).toEqual([+ 'mention_replies_allowed_intents',+ 'mention_replies_daily_cap',+ 'mention_replies_dry_run',+ 'mention_replies_enabled',+ ]);+ });++ it('rejects a daily cap outside 0..50 at the database level', async () => {+ await dbState.pg.query(+ 'insert into agent_x_policies (agent_id, user_id) values ($1, $2)',+ [AGENT, USER],+ );+ await expect(+ dbState.pg.query(+ `update agent_x_policies set mention_replies_daily_cap = 51 where agent_id = $1`,+ [AGENT],+ ),+ ).rejects.toThrow();+ });+});++describe('getAgentPolicy / saveAgentPolicy', () => {+ it('defaults an agent with no row to mentions off, dry run, cap 10, no intents', async () => {+ const policy = await getAgentPolicy(AGENT);+ expect(policy.mention_replies_enabled).toBe(false);+ expect(policy.mention_replies_dry_run).toBe(true);+ expect(policy.mention_replies_daily_cap).toBe(10);+ expect(policy.mention_replies_allowed_intents).toEqual([]);+ });++ it('persists a mention-reply policy patch through the real column set', async () => {+ const saved = await saveAgentPolicy({+ userId: USER,+ agentId: AGENT,+ patch: {+ mention_replies_enabled: true,+ mention_replies_dry_run: false,+ mention_replies_daily_cap: 25,+ mention_replies_allowed_intents: ['chat', 'make'],+ },+ });+ expect(saved.mention_replies_enabled).toBe(true);+ expect(saved.mention_replies_dry_run).toBe(false);+ expect(saved.mention_replies_daily_cap).toBe(25);+ expect(saved.mention_replies_allowed_intents).toEqual(['chat', 'make']);++ const reloaded = await getAgentPolicy(AGENT);+ expect(reloaded.mention_replies_enabled).toBe(true);+ expect(reloaded.mention_replies_allowed_intents).toEqual(['chat', 'make']);+ });++ it('rejects an unknown intent id instead of persisting it', async () => {+ await expect(+ saveAgentPolicy({+ userId: USER,+ agentId: AGENT,+ patch: { mention_replies_allowed_intents: ['chat', 'not-a-real-intent'] },+ }),+ ).rejects.toThrow(/unknown intent/);+ });+});diff --git a/tests/x-mention-decisions-endpoint.test.js b/tests/x-mention-decisions-endpoint.test.jsnew file mode 100644index 000000000..ae64e1e46--- /dev/null+++ b/tests/x-mention-decisions-endpoint.test.js@@ -0,0 +1,138 @@+// api/x/mention-decisions.js: the owner's read of an agent's recent mention+// decisions, previewed by the "Answer mentions" panel on pages/agent-edit.html.+// The one rule worth pinning mechanically: an agent id that exists but is not+// owned by the caller must answer 404, exactly like every other agent-scoped+// route guarded by loadOwnedAgent (api/x/agents.js).++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { XPostError } from '../api/_lib/x-post.js';++const getRequestUserMock = vi.fn();+const hasScopeMock = vi.fn(() => true);+vi.mock('../api/_lib/auth.js', () => ({+ getRequestUser: (...a) => getRequestUserMock(...a),+ hasScope: (...a) => hasScopeMock(...a),+}));++const authedReadIpMock = vi.fn();+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authedReadIp: (...a) => authedReadIpMock(...a) },+ clientIp: () => '127.0.0.1',+}));++const loadOwnedAgentMock = vi.fn();+vi.mock('../api/_lib/x-agent-policy.js', () => ({+ loadOwnedAgent: (...a) => loadOwnedAgentMock(...a),+}));++const recentDecisionsMock = vi.fn();+vi.mock('../api/_lib/x-mention-store.js', () => ({+ recentDecisions: (...a) => recentDecisionsMock(...a),+}));++const { default: handler } = await import('../api/x/mention-decisions.js');++const OWNER = '11111111-1111-1111-1111-111111111111';+const AGENT = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';++function mkReq({ url }) {+ return { method: 'GET', url, headers: {} };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++beforeEach(() => {+ getRequestUserMock.mockReset().mockResolvedValue({ id: OWNER, source: 'session' });+ hasScopeMock.mockReset().mockReturnValue(true);+ authedReadIpMock.mockReset().mockResolvedValue({ success: true, limit: 60, remaining: 59, reset: 0 });+ loadOwnedAgentMock.mockReset().mockResolvedValue({ id: AGENT, name: 'Test Agent' });+ recentDecisionsMock.mockReset().mockResolvedValue([]);+});++describe('GET /api/x/mention-decisions', () => {+ it('requires a signed-in user', async () => {+ getRequestUserMock.mockResolvedValue(null);+ const res = mkRes();+ await handler(mkReq({ url: `/api/x/mention-decisions?agent_id=${AGENT}` }), res);+ expect(res.statusCode).toBe(401);+ });++ it('rejects a missing or malformed agent_id', async () => {+ const res = mkRes();+ await handler(mkReq({ url: '/api/x/mention-decisions' }), res);+ expect(res.statusCode).toBe(400);+ expect(loadOwnedAgentMock).not.toHaveBeenCalled();+ });++ it('answers 404 for an agent the caller does not own', async () => {+ loadOwnedAgentMock.mockRejectedValue(new XPostError('not_found', 'agent not found', 404));+ const res = mkRes();+ await handler(mkReq({ url: `/api/x/mention-decisions?agent_id=${AGENT}` }), res);+ expect(res.statusCode).toBe(404);+ expect(parse(res).error).toBe('not_found');+ expect(recentDecisionsMock).not.toHaveBeenCalled();+ });++ it('returns the owner-scoped decision rows, newest first, capped at the requested limit', async () => {+ recentDecisionsMock.mockResolvedValue([+ {+ tweet_id: '123',+ author_username: 'someone',+ mention_text: '@bot make me a dragon',+ intent: 'make',+ decision: 'reply',+ reason: 'intent allowed',+ reply_text: 'Done, here is your dragon.',+ reply_media_url: 'https://cdn.three.ws/forge/dragon.png',+ reply_link: null,+ dry_run: true,+ created_at: '2026-10-11T00:00:00.000Z',+ decided_at: '2026-10-11T00:00:01.000Z',+ },+ ]);+ const res = mkRes();+ await handler(mkReq({ url: `/api/x/mention-decisions?agent_id=${AGENT}&limit=5` }), res);+ expect(res.statusCode).toBe(200);+ expect(loadOwnedAgentMock).toHaveBeenCalledWith(OWNER, AGENT);+ expect(recentDecisionsMock).toHaveBeenCalledWith({ kind: 'agent', ref: AGENT }, { limit: 5 });+ const body = parse(res);+ expect(body.decisions).toHaveLength(1);+ expect(body.decisions[0].reply_text).toBe('Done, here is your dragon.');+ expect(body.decisions[0].reply_media_url).toContain('dragon.png');+ });++ it('clamps an out-of-range limit into 1..20', async () => {+ const res = mkRes();+ await handler(mkReq({ url: `/api/x/mention-decisions?agent_id=${AGENT}&limit=999` }), res);+ expect(res.statusCode).toBe(200);+ expect(recentDecisionsMock).toHaveBeenCalledWith({ kind: 'agent', ref: AGENT }, { limit: 20 });+ });++ it('requires the agents:read scope for bearer callers', async () => {+ getRequestUserMock.mockResolvedValue({ id: OWNER, source: 'bearer', scope: 'agents:write' });+ hasScopeMock.mockReturnValue(false);+ const res = mkRes();+ await handler(mkReq({ url: `/api/x/mention-decisions?agent_id=${AGENT}` }), res);+ expect(res.statusCode).toBe(403);+ expect(loadOwnedAgentMock).not.toHaveBeenCalled();+ });+});