Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2158]): timeline-aware Tribe outreach — detect unanswered threads + draft replies
[._.]/ Adam Eivy50cced0d6626
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4236922deb..e93317a33c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,10 @@- **[issue-1227] Character LoRA training is validated end-to-end on Apple Silicon, and now fails fast when it can't run.** A real training run was taken all the way through on the MLX (mflux) runtime — from staging a character's images to a trained adapter, then loading that adapter back into image generation to confirm it renders — so training your own character LoRAs is a proven path on this hardware. The torch-based fallback trainer, meanwhile, can't train on a Mac's GPU (a PyTorch/Metal limitation), so instead of quietly loading gigabytes of weights and then crashing partway in, PortOS now stops you at the start with a clear message to set up the MLX trainer. Nothing changes for Linux/CUDA machines, where the fallback is the intended path.+## Tribe++- **[issue-2158] Your Tribe now nudges you about messages you never replied to — with a reply ready to draft.** Beyond the existing "you haven't talked in a while" cadence reminders, PortOS now reads your activity timeline (iMessage, Signal, email) to spot inbound messages from people in your Tribe that you never answered, and surfaces them both as a proactive alert ("You never replied to 'dinner Friday?' — 3 days ago") and in a new **Waiting on a reply** panel on the Tribe → Care Queue tab. Each one has a **Draft reply** button that writes a reply grounded in the actual conversation and files it to your Messages drafts for review — it uses your configured AI provider only when you click, and nothing is ever sent automatically. Threads you've already answered, ones too fresh to nag about, and ones too old to still be worth a reply are all filtered out, and only people in your Tribe (not every contact) can trigger a nudge.+## Added- [issue-2763] **Layered Intelligence now reasons from a proposal playbook instead of proposing blind.** Every LI run's prompt now carries a standing **Proposal Playbook** — a distilled rule set for *what* to propose that's present from the very first run, before any per-app outcome data has accumulated. It encodes a Scope Selection Guide (prioritize high-merge scopes like `loop-meta` and `app-data-gap`; only file an `app-improvement` when it clearly serves a named goal), a Success Pattern Catalog and a Rejection Pattern Catalog (a NOT_PLANNED close means a roadmap conflict, so check goals and committed backlog *first*), Task Type Selection Rules (avoid the loop's own chronically-failing self-improvement work; prefer shapes an agent reliably finishes like plan-task / test-coverage / performance), and a Goal Alignment Check against PortOS's core goals and documented non-goals. It's authored as a reviewable markdown file that ships with the code and is injected verbatim into the reasoning prompt; where a live per-app outcome report in the same prompt has real numbers that contradict a general rule, the live data wins. Applies to every app the loop reasons about.diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsxindex e412e071c1..ce69d04809 100644--- a/client/src/components/ProactiveAlertsWidget.jsx+++ b/client/src/components/ProactiveAlertsWidget.jsx@@ -10,7 +10,9 @@ import {TrendingUp,Cpu,BookOpen,- CheckCircle+ CheckCircle,+ Users,+ MessageSquareReply} from 'lucide-react';import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';@@ -41,7 +43,9 @@ const TYPE_ICONS = {cost_spike: TrendingUp,system_resource: Cpu,process_error: AlertOctagon,- learning_health: BookOpen+ learning_health: BookOpen,+ tribe_cadence: Users,+ tribe_unanswered: MessageSquareReply};const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {diff --git a/client/src/pages/Tribe.jsx b/client/src/pages/Tribe.jsxindex 7dbaad7936..92c2d2a334 100644--- a/client/src/pages/Tribe.jsx+++ b/client/src/pages/Tribe.jsx@@ -3,15 +3,18 @@ import { useSearchParams } from 'react-router-dom';import {Calendar,Clock,+ Copy,Edit3,Filter,Heart,MessageCircle,+ MessageSquareReply,Network,Orbit,Plus,Save,Search,+ Sparkles,Trash2,UserRound,Users,@@ -25,6 +28,7 @@ import PageHeader from '../components/PageHeader';import toast from '../components/ui/Toast';import TabPills from '../components/ui/TabPills';import TribeCircleMap from '../components/tribe/TribeCircleMap.jsx';+import { copyToClipboard } from '../lib/clipboard.js';import {RINGS,ENERGY,@@ -557,6 +561,134 @@ function EmptyState({ onNew }) {);}+const SOURCE_LABELS = {+ imessage: 'iMessage',+ signal: 'Signal',+ gmail: 'Gmail',+ outlook: 'Outlook',+ teams: 'Teams',+ message: 'Message',+ calendar: 'Calendar',+};+const sourceLabel = (source) => SOURCE_LABELS[source] || (source ? source[0].toUpperCase() + source.slice(1) : 'Message');+const agoLabel = (days) => (days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days} days ago`);++// Timeline-aware outreach (#2158): inbound messages from Tribe people you never+// replied to. Detection is server-side and LLM-free; the "Draft reply" button is+// the only path that calls a provider (user action, per the AI-provider policy).+// Nothing is ever auto-sent — the generated draft is filed for review.+function OutreachQueue() {+ // null = still loading; [] = loaded-empty. Distinguishing them keeps the panel+ // from flashing an empty state before the first fetch resolves.+ const [threads, setThreads] = useState(null);+ const [busyKey, setBusyKey] = useState(null);+ const [drafts, setDrafts] = useState({});+ const [copiedKey, setCopiedKey] = useState(null);++ useEffect(() => {+ let cancelled = false;+ api.getTribeOutreach({ silent: true })+ .then((result) => { if (!cancelled) setThreads(result?.threads || []); })+ .catch(() => { if (!cancelled) setThreads([]); });+ return () => { cancelled = true; };+ }, []);++ const generate = async (thread) => {+ setBusyKey(thread.conversationKey);+ const seed = {+ personId: thread.personId,+ source: thread.source,+ accountId: thread.accountId,+ threadId: thread.threadId,+ chatGuid: thread.chatGuid,+ handle: thread.handle,+ replyToExternalId: thread.replyToExternalId,+ };+ const result = await api.generateTribeOutreachDraft(seed, { silent: true }).catch((err) => {+ toast.error(err.message || 'Could not generate a draft');+ return null;+ });+ setBusyKey((prev) => (prev === thread.conversationKey ? null : prev));+ if (result?.draft) {+ setDrafts((prev) => ({ ...prev, [thread.conversationKey]: result.draft }));+ toast.success(`Draft saved for ${thread.personName} — review before sending`);+ }+ };++ const copyBody = async (key, body) => {+ const ok = await copyToClipboard(body);+ if (ok) {+ setCopiedKey(key);+ setTimeout(() => setCopiedKey((prev) => (prev === key ? null : prev)), 1500);+ } else {+ toast.error('Could not copy to clipboard');+ }+ };++ // Quiet when loading or when nothing is unanswered — the Care Queue below still+ // shows cadence nudges, so an empty outreach panel would just be noise.+ if (threads === null || !threads.length) return null;++ return (+ <section className="border border-port-border bg-port-card rounded p-4">+ <div className="flex items-center gap-2">+ <MessageSquareReply size={18} className="text-port-warning" aria-hidden="true" />+ <h2 className="text-sm font-semibold text-white">Waiting on a reply</h2>+ <span className="ml-auto rounded-full bg-port-warning/20 px-2 py-0.5 text-xs text-port-warning">{threads.length}</span>+ </div>+ <p className="mt-1 text-xs text-gray-500">+ Inbound messages from your Tribe you never replied to. Drafting a reply uses your configured AI provider; nothing is sent automatically.+ </p>+ <div className="mt-3 grid gap-3">+ {threads.map((thread) => {+ const draft = drafts[thread.conversationKey];+ const busy = busyKey === thread.conversationKey;+ return (+ <div key={thread.conversationKey} className="rounded border border-port-border bg-port-bg p-3">+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500">+ <span className="font-medium text-white">{thread.personName}</span>+ <span className="rounded border border-port-border px-1.5 py-0.5">{sourceLabel(thread.source)}</span>+ <span className="ml-auto">{agoLabel(thread.daysAgo)}</span>+ </div>+ {thread.snippet && (+ <p className="mt-2 text-sm text-gray-300 line-clamp-2">“{thread.snippet}”</p>+ )}+ {!draft ? (+ <button+ type="button"+ onClick={() => generate(thread)}+ disabled={busy}+ className="mt-3 inline-flex items-center gap-2 rounded bg-port-accent px-3 py-1.5 text-sm font-medium text-black hover:bg-port-accent/90 disabled:opacity-60"+ >+ <Sparkles size={14} aria-hidden="true" />+ {busy ? 'Drafting…' : 'Draft reply'}+ </button>+ ) : (+ <div className="mt-3 rounded border border-port-border bg-port-card p-3">+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-semibold uppercase tracking-wide text-port-success">Draft saved</span>+ <button+ type="button"+ onClick={() => copyBody(thread.conversationKey, draft.body)}+ className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:text-white"+ >+ <Copy size={12} aria-hidden="true" />+ {copiedKey === thread.conversationKey ? 'Copied' : 'Copy'}+ </button>+ </div>+ {draft.subject && <p className="mt-2 text-xs text-gray-500">Subject: {draft.subject}</p>}+ <p className="mt-2 whitespace-pre-wrap text-sm text-gray-300">{draft.body}</p>+ <p className="mt-2 text-xs text-gray-500">Filed in Messages → Drafts. Review, edit, and send it there — it is never sent automatically.</p>+ </div>+ )}+ </div>+ );+ })}+ </div>+ </section>+ );+}+function CareQueue({ contacts, onSelect, onLogTouch, onNew }) {// External people are outside the tribe — no care cadence is owed, so they// never appear in the queue (otherwise their null daysRemaining would sort@@ -1030,12 +1162,15 @@ export default function Tribe() {{activeTab === 'care' && (<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(330px,420px)]">- <CareQueue- contacts={contacts}- onSelect={(contact) => { selectContact(contact); setActiveTab('circle'); }}- onLogTouch={logTouch}- onNew={startNewRelationship}- />+ <div className="grid gap-4">+ <OutreachQueue />+ <CareQueue+ contacts={contacts}+ onSelect={(contact) => { selectContact(contact); setActiveTab('circle'); }}+ onLogTouch={logTouch}+ onNew={startNewRelationship}+ />+ </div><ContactFormdraft={draft}onChange={setDraft}diff --git a/client/src/pages/Tribe.test.jsx b/client/src/pages/Tribe.test.jsxindex 02371ddb8b..f70deda171 100644--- a/client/src/pages/Tribe.test.jsx+++ b/client/src/pages/Tribe.test.jsx@@ -4,6 +4,8 @@ import { MemoryRouter, useLocation } from 'react-router-dom';vi.mock('../services/api', () => ({getTribePeople: vi.fn(() => Promise.resolve({ people: [] })),+ // OutreachQueue (care tab) fetches unanswered threads on mount (#2158).+ getTribeOutreach: vi.fn(() => Promise.resolve({ threads: [] })),}));vi.mock('../services/socket', () => ({diff --git a/client/src/services/apiTribe.js b/client/src/services/apiTribe.jsindex fc603c44d3..c183ec5b13 100644--- a/client/src/services/apiTribe.js+++ b/client/src/services/apiTribe.js@@ -56,3 +56,21 @@ export const linkTribeMemory = (personId, data, options = {}) => request(`/tribeexport const unlinkTribeMemory = (personId, memoryId, options = {}) =>request(`/tribe/people/${personId}/memories/${memoryId}`, { method: 'DELETE', ...options });++// Unanswered inbound threads from Tribe people, detected from the activity+// timeline (#2158). Read-only, no LLM.+export const getTribeOutreach = (options = {}) => {+ const params = new URLSearchParams();+ if (options.limit) params.set('limit', String(options.limit));+ const qs = params.toString();+ return request(`/tribe/outreach${qs ? `?${qs}` : ''}`, { silent: options.silent });+};++// Generate a grounded outreach draft for one detected thread (user-action-gated+// LLM call). Never sends — returns the filed draft for review.+export const generateTribeOutreachDraft = (seed, options = {}) =>+ request('/tribe/outreach/draft', {+ method: 'POST',+ body: JSON.stringify(seed),+ ...options,+ });diff --git a/server/routes/tribe.js b/server/routes/tribe.jsindex 0370bb2456..3ba165571e 100644--- a/server/routes/tribe.js+++ b/server/routes/tribe.js@@ -5,6 +5,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { partialWithoutDefaults } from '../lib/zodCompat.js';import * as tribe from '../services/tribe.js';+import * as tribeOutreach from '../services/tribeOutreach.js';const router = Router();@@ -58,6 +59,21 @@ const memoryLinkSchema = z.object({note: z.string().max(1000).optional().default(''),});+// Outreach draft generation (#2158). The seed fields come from a detected+// unanswered thread; the LLM call happens only on this explicit POST (user action)+// per the AI-provider policy — never from the detection sweep.+const outreachDraftSchema = z.object({+ personId: z.string().guid().nullable().optional(),+ source: z.string().max(60).nullable().optional(),+ accountId: z.string().guid().nullable().optional(),+ threadId: z.string().max(500).nullable().optional(),+ chatGuid: z.string().max(500).nullable().optional(),+ handle: z.string().max(320).nullable().optional(),+ replyToExternalId: z.string().max(500).nullable().optional(),+ instructions: z.string().max(2000).optional().default(''),+ useVoice: z.boolean().optional(),+});+const listQuerySchema = z.object({search: z.string().max(200).optional(),ring: ringSchema.or(z.literal('all')).optional(),@@ -92,6 +108,25 @@ router.get('/care', asyncHandler(async (req, res) => {res.json(summary);}));+// Unanswered inbound threads from Tribe people, detected from the activity+// timeline (#2158). Detection only — NO LLM. Feeds the Tribe Outreach panel and+// mirrors the `tribe_unanswered` proactive alert.+router.get('/outreach', asyncHandler(async (req, res) => {+ const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 8, 1), 50);+ const threads = await tribeOutreach.findUnansweredTribeThreads({ limit });+ res.json({ threads });+}));++// Generate a grounded outreach draft for one unanswered thread and file it through+// the existing draft-then-approve pipeline. This is the user-action-gated LLM step+// — it never auto-sends. The client shows the returned draft for review.+router.post('/outreach/draft', asyncHandler(async (req, res) => {+ const data = validateRequest(outreachDraftSchema, req.body);+ const result = await tribeOutreach.generateOutreachDraft(data);+ req.app.get('io')?.emit('messages:draft:created', { draftId: result.draft.id });+ res.status(201).json(result);+}));+router.post('/people', asyncHandler(async (req, res) => {const data = validateRequest(personSchema, req.body);const person = await tribe.createPerson(data);diff --git a/server/routes/tribe.test.js b/server/routes/tribe.test.jsindex 8a95367b9d..f9a4932ce3 100644--- a/server/routes/tribe.test.js+++ b/server/routes/tribe.test.js@@ -24,7 +24,13 @@ vi.mock('../services/tribe.js', () => ({unlinkMemory: vi.fn(),}));+vi.mock('../services/tribeOutreach.js', () => ({+ findUnansweredTribeThreads: vi.fn(),+ generateOutreachDraft: vi.fn(),+}));+import * as tribe from '../services/tribe.js';+import * as tribeOutreach from '../services/tribeOutreach.js';const PERSON_ID = '11111111-1111-4111-8111-111111111111';const MEMORY_ID = '22222222-2222-4222-8222-222222222222';@@ -263,4 +269,43 @@ describe('Tribe Routes', () => {expect(response.status).toBe(404);expect(emit).not.toHaveBeenCalledWith('tribe:changed', expect.anything());});++ it('lists unanswered outreach threads with a clamped limit', async () => {+ tribeOutreach.findUnansweredTribeThreads.mockResolvedValue([+ { conversationKey: 'chat:1', personId: PERSON_ID, personName: 'Ada', daysAgo: 3 },+ ]);++ const response = await request(app).get('/api/tribe/outreach?limit=999');++ expect(response.status).toBe(200);+ expect(response.body.threads).toHaveLength(1);+ expect(tribeOutreach.findUnansweredTribeThreads).toHaveBeenCalledWith({ limit: 50 }); // clamped+ });++ it('generates an outreach draft and announces the new draft', async () => {+ tribeOutreach.generateOutreachDraft.mockResolvedValue({+ draft: { id: '44444444-4444-4444-8444-444444444444', body: 'Hey Ada!' },+ person: { id: PERSON_ID, name: 'Ada' },+ });++ const response = await request(app)+ .post('/api/tribe/outreach/draft')+ .send({ personId: PERSON_ID, source: 'imessage', chatGuid: 'chat-1' });++ expect(response.status).toBe(201);+ expect(response.body.draft.body).toBe('Hey Ada!');+ expect(tribeOutreach.generateOutreachDraft).toHaveBeenCalledWith(+ expect.objectContaining({ personId: PERSON_ID, source: 'imessage', chatGuid: 'chat-1' }),+ );+ expect(emit).toHaveBeenCalledWith('messages:draft:created', { draftId: '44444444-4444-4444-8444-444444444444' });+ });++ it('rejects an outreach draft request with a non-UUID accountId', async () => {+ const response = await request(app)+ .post('/api/tribe/outreach/draft')+ .send({ accountId: 'not-a-uuid' });++ expect(response.status).toBe(400);+ expect(tribeOutreach.generateOutreachDraft).not.toHaveBeenCalled();+ });});diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex e9d8b389df..8383cde3e4 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -18,6 +18,7 @@ import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';import { listProcesses } from './pm2.js';import { getUsage } from './usage.js';import { getCareSummary } from './tribe.js';+import { findUnansweredTribeThreads } from './tribeOutreach.js';import { getMemoryStats } from '../lib/memoryStats.js';const STALL_THRESHOLD_DAYS = 14;@@ -264,6 +265,43 @@ async function checkTribeCadence() {}];}+/**+ * Detect unanswered inbound threads from Tribe people via the activity timeline+ * (#2158). Cadence-only nudges (checkTribeCadence) say "you haven't talked in a+ * while"; this says "you never replied to X's message about Y" with real+ * conversational grounding. Detection only — NO LLM here (the AI-provider policy+ * forbids cold-bootstrap calls); drafting a reply is a separate user-action-gated+ * step. Quiet when nothing is unanswered. Reuses the shared detection service.+ */+async function checkUnansweredTribeThreads() {+ const threads = await findUnansweredTribeThreads().catch(() => []);+ if (!threads.length) return [];++ const ago = (days) => (days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days} days ago`);+ return threads.map((t) => {+ const snippet = t.snippet ? `“${t.snippet}”` : 'their message';+ return {+ type: 'tribe_unanswered',+ // A week-stale unanswered message from someone you care about is worth more+ // than a fresh one still within normal reply latency.+ severity: t.daysAgo >= 7 ? 'high' : 'medium',+ title: `Unanswered: ${t.personName}`,+ detail: `You never replied to ${snippet} (${ago(t.daysAgo)})`,+ link: '/tribe?tab=care',+ metadata: {+ personId: t.personId,+ source: t.source,+ accountId: t.accountId,+ threadId: t.threadId,+ chatGuid: t.chatGuid,+ handle: t.handle,+ replyToExternalId: t.replyToExternalId,+ daysAgo: t.daysAgo,+ },+ };+ });+}+/*** Generate all proactive alerts by running all checks.* Returns a sorted list with critical/high items first.@@ -271,16 +309,17 @@ async function checkTribeCadence() {export async function generateAlerts() {const startMs = Date.now();- const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts] = await Promise.all([+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts, tribeAlerts, unansweredAlerts] = await Promise.all([checkGoalStalls(),checkSuccessRates(),checkSystemHealth(),checkLearningHealth(),checkUsageSpikes(),- checkTribeCadence()+ checkTribeCadence(),+ checkUnansweredTribeThreads()]);- const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts];+ const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts, ...tribeAlerts, ...unansweredAlerts];// Sort by severity: critical > high > medium > lowconst severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };diff --git a/server/services/tribeOutreach.js b/server/services/tribeOutreach.jsnew file mode 100644index 0000000000..51dcef2278--- /dev/null+++ b/server/services/tribeOutreach.js@@ -0,0 +1,327 @@+/**+ * Tribe Outreach (#2158)+ *+ * Timeline-aware outreach for Tribe relationships — the follow-on to the+ * cadence-only nudges in `proactiveAlerts.js`. Two layers, deliberately split so+ * the AI-provider policy holds (no cold-bootstrap LLM calls):+ *+ * 1. Detection (NO LLM) — `findUnansweredTribeThreads()` scans the human-activity+ * timeline (#2150) for inbound messages from Tribe people that were never+ * replied to, grouped by conversation. Pure timeline + Tribe reads, cheap and+ * safe to run from the on-demand proactive-alerts sweep and background jobs.+ *+ * 2. Draft generation (USER-ACTION-GATED LLM) — `generateOutreachDraft()` takes+ * one detected thread, grounds a reply in the real conversation (the message+ * cache when available, else the timeline's own message summaries), runs the+ * existing reply-generation pipeline (`messageEvaluator.generateReplyBody`),+ * and files a DRAFT through `messageDrafts.createDraft`. It NEVER auto-sends —+ * the user reviews/approves/sends through the existing draft pipeline.+ *+ * The detection layer is source-agnostic: it works across every message source+ * that records `message.sent`/`message.received` activity events — Gmail/Outlook+ * (#2033), iMessage (#2151), Signal (#2154) — because it keys off the timeline,+ * not any one provider's cache.+ */++import { ServerError } from '../lib/errorHandler.js';++const DAY_MS = 86400000;+const HOUR_MS = 3600000;++// Detection window defaults. `staleAfterHours` gives the user time to reply+// naturally before we nudge; `withinDays` drops threads too old to still be+// worth a fresh reply (they read as necromancy, not attentiveness).+export const DEFAULT_WITHIN_DAYS = 14;+export const DEFAULT_STALE_HOURS = 20;+export const DEFAULT_LIMIT = 8;++// Grounding thread bodies are capped downstream (buildThreadContext slices to+// 500 chars) — this bounds how many prior turns we feed the model per draft.+const MAX_GROUNDING_EVENTS = 12;++const MESSAGE_KINDS = new Set(['message.sent', 'message.received']);++// A conversation is keyed by the most specific stable identifier available:+// chatGuid (iMessage/Signal group or 1:1), then the email threadId, then the raw+// handle. Person-scoped fallback only when an event carries none of those — it+// keeps a lone handle-less inbound groupable, but is deliberately last so that+// sent + received turns of the SAME email/iMessage thread always share a key+// (a person fallback would split them whenever one side lacks a person match).+function conversationKey(event) {+ const m = event?.metadata || {};+ if (m.chatGuid) return `chat:${m.chatGuid}`;+ if (m.threadId) return `thread:${m.threadId}`;+ if (m.handle) return `handle:${String(m.handle).toLowerCase()}`;+ if (event?.personId) return `person:${event.personId}`;+ return null;+}++function threadFields(inbound, eventCount, ageMs) {+ const m = inbound.metadata || {};+ return {+ personId: inbound.personId,+ personName: inbound.personName || 'someone',+ ring: inbound.ring || null,+ source: inbound.source || null,+ accountId: inbound.accountId || null,+ threadId: m.threadId || null,+ chatGuid: m.chatGuid || null,+ handle: m.handle || null,+ replyToExternalId: m.externalId || null,+ lastInboundAt: inbound.happenedAt,+ daysAgo: Math.floor(ageMs / DAY_MS),+ snippet: String(inbound.summary || inbound.title || '').trim(),+ eventCount,+ };+}++/**+ * Pure grouping/staleness core (unit-tested without a DB). Given message activity+ * events already tagged with the resolved Tribe person on the INBOUND side, return+ * one entry per conversation whose latest turn is an unanswered inbound from a+ * Tribe person, within the actionable window.+ *+ * Events shape (per item): {+ * kind: 'message.sent' | 'message.received',+ * happenedAt: ISO string,+ * source, accountId, summary, title, metadata: { chatGuid?, threadId?, handle?, externalId? },+ * // inbound (received) events additionally carry the resolved Tribe person:+ * personId?, personName?, ring?+ * }+ * Outbound (sent) events need NO person resolution — they only cancel the+ * unanswered flag when newer than the last inbound (iMessage sent turns carry no+ * counterpart handle, so they'd never resolve, but still count as "you replied").+ *+ * @returns {Array} unanswered-thread descriptors, most overdue first.+ */+export function groupUnansweredThreads(events, { now = Date.now(), staleAfterMs = 0, withinMs = Infinity } = {}) {+ const groups = new Map();+ for (const ev of events || []) {+ if (!ev || !MESSAGE_KINDS.has(ev.kind)) continue;+ const key = conversationKey(ev);+ if (!key) continue;+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key).push(ev);+ }++ const out = [];+ for (const [key, evs] of groups) {+ let lastInbound = null;+ let lastSentT = -Infinity;+ for (const ev of evs) {+ const t = Date.parse(ev.happenedAt);+ if (Number.isNaN(t)) continue;+ if (ev.kind === 'message.sent') {+ if (t > lastSentT) lastSentT = t;+ } else if (ev.personId && ev.ring !== 'external') {+ // Only a Tribe-resolved inbound can anchor an unanswered thread.+ if (!lastInbound || t > Date.parse(lastInbound.happenedAt)) lastInbound = ev;+ }+ }+ if (!lastInbound) continue;+ const recvT = Date.parse(lastInbound.happenedAt);+ if (lastSentT >= recvT) continue; // already replied after their last message+ const age = now - recvT;+ if (age < staleAfterMs || age > withinMs) continue;+ out.push({ conversationKey: key, ...threadFields(lastInbound, evs.length, age) });+ }++ // Most overdue first, then alphabetical for a stable order.+ out.sort((a, b) => b.daysAgo - a.daysAgo || a.personName.localeCompare(b.personName));+ return out;+}++/**+ * Detect unanswered inbound threads from Tribe people via the activity timeline.+ * No LLM — pure timeline + Tribe reads. Returns [] on any read failure (a nudge+ * source that quietly yields nothing beats one that throws into the alert sweep).+ */+export async function findUnansweredTribeThreads({+ withinDays = DEFAULT_WITHIN_DAYS,+ staleAfterHours = DEFAULT_STALE_HOURS,+ limit = DEFAULT_LIMIT,+} = {}) {+ const [{ listEvents }, { loadResolverContext, enrichActivityEvent }] = await Promise.all([+ import('./humanActivity.js'),+ import('./identityResolve.js'),+ ]);++ const ctx = await loadResolverContext().catch(() => null);+ if (!ctx) return [];+ const ringById = new Map((ctx.people || []).map((p) => [p.id, p.ring]));+ const nameById = new Map((ctx.people || []).map((p) => [p.id, p.name]));+ // No non-external Tribe people → nothing to nudge about; skip the timeline scan.+ const hasTribe = (ctx.people || []).some((p) => p.ring && p.ring !== 'external');+ if (!hasTribe) return [];++ const now = Date.now();+ const from = new Date(now - withinDays * DAY_MS).toISOString();+ const events = await listEvents({ from, limit: 2000 }).catch(() => []);++ const tagged = [];+ for (const ev of events) {+ if (!MESSAGE_KINDS.has(ev.kind)) continue;+ if (ev.kind === 'message.sent') {+ // Keep every outbound turn unresolved — it only needs to cancel the+ // unanswered flag for its conversation (grouped by chatGuid/threadId).+ tagged.push(ev);+ continue;+ }+ // Inbound: resolve the counterpart to a Tribe person (handle first, then any+ // participant with a resolved personId). Drop inbound we can't tie to Tribe.+ const enriched = enrichActivityEvent(ev, ctx);+ let personId = enriched.personId;+ if (!personId) personId = (enriched.participants || []).find((p) => p.personId)?.personId || null;+ if (!personId) continue;+ const ring = ringById.get(personId);+ if (!ring || ring === 'external') continue;+ tagged.push({ ...ev, personId, personName: nameById.get(personId) || enriched.displayName || 'someone', ring });+ }++ const threads = groupUnansweredThreads(tagged, {+ now,+ staleAfterMs: staleAfterHours * HOUR_MS,+ withinMs: withinDays * DAY_MS,+ });+ return threads.slice(0, Math.max(0, limit));+}++// Build a synthetic thread (buildThreadContext / generateReplyBody shape) from+// the conversation's own timeline events when no rich provider cache is available+// (iMessage/Signal, or an email thread pruned from cache). The message summaries+// are the actual message text (shortSummary-capped), so this still grounds the+// reply in the real conversation. `selfName` labels the user's own sent turns.+function timelineThreadMessages(events, personName) {+ return (events || [])+ .filter((ev) => MESSAGE_KINDS.has(ev.kind) && (ev.summary || ev.title))+ .sort((a, b) => Date.parse(a.happenedAt) - Date.parse(b.happenedAt))+ .slice(-MAX_GROUNDING_EVENTS)+ .map((ev) => ({+ from: { name: ev.kind === 'message.sent' ? 'You' : (personName || 'them') },+ date: ev.happenedAt,+ bodyText: String(ev.summary || ev.title || ''),+ }));+}++function replySubject(subject) {+ const s = String(subject || '').trim();+ if (!s) return '';+ return /^re:/i.test(s) ? s : `Re: ${s}`;+}++/**+ * Generate a grounded outreach draft for one unanswered thread and file it through+ * the existing draft-then-approve pipeline. USER-ACTION-GATED: only ever called+ * from an explicit request (the Tribe Outreach panel / an opt-in automation) — it+ * is the single LLM entry point here and must never be wired into a boot/sweep path.+ *+ * @returns {Promise<{ draft, person: { id, name } | null }>}+ */+export async function generateOutreachDraft({+ personId = null,+ source = null,+ accountId = null,+ threadId = null,+ chatGuid = null,+ handle = null,+ replyToExternalId = null,+ instructions = '',+ useVoice,+} = {}) {+ const [+ { getPerson },+ { getAccount },+ { getThread },+ { listEvents },+ { generateReplyBody },+ { createDraft },+ ] = await Promise.all([+ import('./tribe.js'),+ import('./messageAccounts.js'),+ import('./messageSync.js'),+ import('./humanActivity.js'),+ import('./messageEvaluator.js'),+ import('./messageDrafts.js'),+ ]);++ const person = personId ? await getPerson(personId).catch(() => null) : null;+ // accountId is optional: iMessage/Signal threads have no message account, so a+ // real messageAccounts row exists only for email sources. Absent/unknown → the+ // draft grounds off the timeline and stays review-only (no derived send channel).+ const account = accountId ? await getAccount(accountId).catch(() => null) : null;+ const selfEmail = String(account?.email || '').trim().toLowerCase();++ // Prefer the rich provider cache (full message bodies) when an email account ++ // threadId are present; otherwise ground off the conversation's timeline events.+ let cacheThread = [];+ if (account && threadId) {+ cacheThread = await getThread(accountId, threadId).catch(() => []);+ }++ let replyTo = null;+ let threadMessages = null;+ if (cacheThread.length) {+ // Last inbound = newest message NOT from the account owner.+ replyTo = [...cacheThread].reverse().find((m) => {+ const fromEmail = String(m.from?.email || '').trim().toLowerCase();+ return !(selfEmail && fromEmail === selfEmail);+ })+ || (replyToExternalId ? cacheThread.find((m) => m.externalId === replyToExternalId) : null)+ || cacheThread[cacheThread.length - 1];+ threadMessages = cacheThread;+ } else {+ // Timeline grounding: pull this conversation's message events. chatGuid is the+ // most selective key; fall back to handle, then the person's whole history.+ const convoEvents = await listEvents({+ source: source || undefined,+ chatGuid: chatGuid || undefined,+ handle: chatGuid ? undefined : (handle || undefined),+ personId: (chatGuid || handle) ? undefined : (personId || undefined),+ limit: 200,+ }).catch(() => []);+ const msgs = timelineThreadMessages(convoEvents, person?.name);+ threadMessages = msgs;+ // Reply to the last inbound turn (the person's), else the newest turn.+ replyTo = [...msgs].reverse().find((m) => m.from?.name !== 'You') || msgs[msgs.length - 1] || null;+ }++ if (!replyTo) {+ // No conversational grounding at all — refuse rather than fabricate context.+ throw new ServerError('No conversation history found to ground an outreach draft', { status: 404 });+ }++ const aiResult = await generateReplyBody(replyTo, instructions, { useVoice, threadMessages }).catch((err) => {+ console.error(`❌ Outreach draft generation failed: ${err.message}`);+ return null;+ });+ const body = aiResult?.body;+ if (!body) {+ throw new ServerError('Could not generate an outreach draft — check your reply provider in Messages > Config', { status: 502 });+ }++ // Recipient: the cached message's sender, else the person's known email/phone.+ const to = [];+ if (replyTo.from?.email || replyTo.from?.name) {+ if (replyTo.from.email) to.push({ name: replyTo.from.name, email: replyTo.from.email });+ }+ if (to.length === 0) {+ if (person?.emails?.length) to.push({ name: person.name, email: person.emails[0] });+ else if (person?.phones?.length) to.push({ name: person.name, phone: person.phones[0] });+ }++ const draft = await createDraft({+ accountId: accountId || null,+ replyToMessageId: replyTo.id || null,+ threadId: threadId || replyTo.threadId || null,+ to,+ subject: replySubject(replyTo.subject),+ body,+ // Distinct provenance so the drafts list can badge Tribe-originated outreach.+ generatedBy: 'tribe-outreach',+ // Only email accounts have a real send channel; leave others as review-only.+ sendVia: account ? (account.type === 'gmail' ? 'api' : 'playwright') : 'review',+ });++ console.log(`🤝 Outreach draft filed for ${person?.name || 'a Tribe contact'} (${source || 'timeline'})`);+ return { draft, person: person ? { id: person.id, name: person.name } : null };+}diff --git a/server/services/tribeOutreach.test.js b/server/services/tribeOutreach.test.jsnew file mode 100644index 0000000000..de352f69ac--- /dev/null+++ b/server/services/tribeOutreach.test.js@@ -0,0 +1,116 @@+import { describe, it, expect } from 'vitest';++import { groupUnansweredThreads } from './tribeOutreach.js';++// `groupUnansweredThreads` is the pure detection core — no DB, no LLM. These+// tests pin the "unanswered inbound from a Tribe person, within the actionable+// window" contract that both the /tribe/outreach route and the `tribe_unanswered`+// proactive alert depend on (#2158).++const NOW = Date.parse('2026-07-18T12:00:00Z');+const hoursAgo = (h) => new Date(NOW - h * 3600000).toISOString();+const daysAgo = (d) => new Date(NOW - d * 86400000).toISOString();++// Default window: nudge after 20h stale, drop after 14 days.+const WINDOW = { now: NOW, staleAfterMs: 20 * 3600000, withinMs: 14 * 86400000 };++const inbound = (over) => ({+ kind: 'message.received',+ source: 'imessage',+ personId: 'p1',+ personName: 'Alex',+ ring: 'tribe',+ summary: 'dinner Friday?',+ metadata: { chatGuid: 'chat-1', handle: '+15550001' },+ ...over,+});+const sent = (over) => ({+ kind: 'message.sent',+ source: 'imessage',+ summary: 'sounds good',+ metadata: { chatGuid: 'chat-1' },+ ...over,+});++describe('groupUnansweredThreads', () => {+ it('surfaces an unanswered inbound from a Tribe person within the window', () => {+ const out = groupUnansweredThreads([inbound({ happenedAt: daysAgo(3) })], WINDOW);+ expect(out).toHaveLength(1);+ expect(out[0]).toMatchObject({+ personId: 'p1',+ personName: 'Alex',+ source: 'imessage',+ chatGuid: 'chat-1',+ daysAgo: 3,+ snippet: 'dinner Friday?',+ });+ });++ it('excludes a thread you already replied to (sent after their last inbound)', () => {+ const out = groupUnansweredThreads([+ inbound({ happenedAt: daysAgo(3) }),+ sent({ happenedAt: daysAgo(2) }), // replied one day later+ ], WINDOW);+ expect(out).toHaveLength(0);+ });++ it('still surfaces when your reply predates their newest message', () => {+ const out = groupUnansweredThreads([+ sent({ happenedAt: daysAgo(5) }), // old reply+ inbound({ happenedAt: daysAgo(2) }), // they came back after+ ], WINDOW);+ expect(out).toHaveLength(1);+ expect(out[0].daysAgo).toBe(2);+ });++ it('excludes threads too fresh to nudge (within staleAfter)', () => {+ const out = groupUnansweredThreads([inbound({ happenedAt: hoursAgo(4) })], WINDOW);+ expect(out).toHaveLength(0);+ });++ it('excludes threads too old to still be actionable (beyond withinMs)', () => {+ const out = groupUnansweredThreads([inbound({ happenedAt: daysAgo(30) })], WINDOW);+ expect(out).toHaveLength(0);+ });++ it('ignores inbound from non-Tribe people (external ring / unresolved)', () => {+ const out = groupUnansweredThreads([+ inbound({ happenedAt: daysAgo(3), personId: 'p2', ring: 'external', metadata: { chatGuid: 'chat-2' } }),+ inbound({ happenedAt: daysAgo(3), personId: null, metadata: { chatGuid: 'chat-3' } }),+ ], WINDOW);+ expect(out).toHaveLength(0);+ });++ it('cancels an iMessage thread via chatGuid even when the sent turn carries no handle', () => {+ // Real iMessage `message.sent` events have no counterpart handle and never+ // resolve to a person — they must still cancel the unanswered flag by chatGuid.+ const out = groupUnansweredThreads([+ inbound({ happenedAt: daysAgo(3) }),+ { kind: 'message.sent', source: 'imessage', happenedAt: daysAgo(1), metadata: { chatGuid: 'chat-1', handle: null } },+ ], WINDOW);+ expect(out).toHaveLength(0);+ });++ it('groups separate conversations independently and sorts most-overdue first', () => {+ const out = groupUnansweredThreads([+ inbound({ happenedAt: daysAgo(2), personId: 'p1', personName: 'Alex', metadata: { chatGuid: 'chat-1' } }),+ inbound({ happenedAt: daysAgo(6), personId: 'p2', personName: 'Bo', ring: 'core', metadata: { chatGuid: 'chat-2' } }),+ ], WINDOW);+ expect(out.map((t) => t.personName)).toEqual(['Bo', 'Alex']);+ expect(out[0].daysAgo).toBe(6);+ });++ it('keys email conversations by threadId so sent + received turns unify', () => {+ const out = groupUnansweredThreads([+ { kind: 'message.received', source: 'gmail', personId: 'p1', personName: 'Alex', ring: 'tribe',+ happenedAt: daysAgo(4), summary: 'proposal attached', metadata: { threadId: 't-9' } },+ { kind: 'message.sent', source: 'gmail', happenedAt: daysAgo(3), metadata: { threadId: 't-9' } },+ ], WINDOW);+ expect(out).toHaveLength(0); // replied within the same email thread+ });++ it('drops events with unparseable timestamps without throwing', () => {+ const out = groupUnansweredThreads([inbound({ happenedAt: 'not-a-date' })], WINDOW);+ expect(out).toHaveLength(0);+ });+});