Skip to content

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

feat: privacy center digital twin integration (#2147)

Adam Eivy383b7d582b37
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aebb7f6a7e..833e5e0d25 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -187,3 +187,5 @@
- **[issue-2262] Layered Intelligence Loop now files to Jira (tracker abstraction completed).** A Jira-tracked managed app previously short-circuited BEFORE reasoning (`skipped: jira-filer-not-implemented`) — only GitHub/GitLab forges and PLAN.md apps could file. The loop's "act" step now files through the PortOS Jira REST service for any app whose resolved work tracker is `jira` with an enabled `jira.instanceId`/`projectKey` (Jira is never auto-detected from the git host, matching `resolveAppWorkTracker`). A Jira app with no usable config still skips before reasoning (`jira-not-configured`) so no LLM call is burned on a result that can't land. Dedup, park, and pause reuse the same tracker-derived model as the forges: the `<!-- lil-slug: … -->` marker is embedded in the ticket description and matched via a `labels = "layered-intelligence"` JQL scan (with the `ok`/`issues` failed-vs-empty sentinel so a transient Jira blip suppresses filing rather than duplicating), closed-issue suppression uses the ticket `resolutiondate` against the shared 30-day window, and pause applies a Jira-safe `layered-intelligence-blocking` label (colons/spaces stripped) filtered by `statusCategory != Done` so a resolved blocker un-parks the app automatically. Because Jira issues are keyed strings (`PROJ-123`), `pause.blockOnIssue: "this"` resolves to the just-filed ticket's key and an integer resolves to `<projectKey>-<n>`. Adds three generic Jira service helpers (`searchIssues`, `addLabels`, exported `escapeJql`) reused by the filer. (`server/services/jira.js`, `server/services/layeredIntelligence.js`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`)
- **[issue-2277] Layered Intelligence custom sources gain `http` + `cmd` types (full-stack).** The Intelligence tab's custom-source list previously only offered `file` rows even though the design called for three source types — `http`/`cmd` sources could only be set through the API. Each row now has a type selector (File / URL / Command) that swaps in the type-appropriate value field (repo-relative `ref` / `url` / `cmd`) plus an optional `label`, and "Add source" seeds a new file row. The backend backbone the UI needs was also added in the same change (it didn't exist in `main` yet): the Zod schema is now a `type`-discriminated union (`file` keeps the repo-relative-path refine, `http` requires an http(s) URL, `cmd` is a bounded command string, all with an optional label), and `gatherSources` reads the new types via two injectable, degrade-to-omit helpers — `fetchHttpSource` (http(s)-scheme-guarded, 10s-timeout `fetch`, null on non-2xx/throw) and `runShellCommand` (shell-run in the app's repo dir, 15s timeout, null on non-zero exit). A `customSourceKey` helper namespaces the prompt map key by type so a `file` ref and an `http` url that share a string can't collide. Sanitize/diff on the client mirrors all three types + label so a blank/half-typed row still sanitizes away (no over-persist), and a type change clears the stale value field while keeping the label. (`server/lib/validation.js`, `server/services/layeredIntelligence.js`, `client/src/components/apps/LayeredIntelligenceTab.jsx`)
+
+- **[issue-2147] Privacy Center Phase 8 — Digital Twin integration (context injection + social-account cross-link).** The encrypted PII vault can now feed the Digital Twin as its authoritative identity dossier, gated opt-in TWICE: a new global twin setting `includePrivacyContext` (default **false**, toggled from the twin Overview → Settings panel) AND the existing per-record `share_with_twin` flag — with either gate off, prompts receive nothing from the vault. When both are on, `getPrivacyTwinContext()` builds a compact block of the flagged identity facts (legal name, contact details, addresses) decrypted **at injection time only** (never cached to disk or logged), plus a one-line org summary (counts by trust + category span) and, when the Phase 5/6 broker tables exist, a data-broker posture line (N confirmed removed, M pending). The block is injected by `getDigitalTwinForPrompt()` ahead of the twin documents under the same `maxContextTokens` budget, and degrades to nothing (never throws) when Privacy Center isn't provisioned — a `to_regclass` existence gate means missing vault/org/broker tables just omit their section. The org registry ↔ twin cross-link surfaces on the twin's Accounts tab: each social account shows an "in org registry" badge when a `privacy_orgs.social_account_id` references it (via a new `GET /api/privacy/social-account-links` reverse index), and unlinked accounts get an "Add to org registry" action that files a `platform`-category org linked back to the account. Additive, defaulted setting — no migration needed. (`server/services/privacyTwinContext.js`, `server/services/digital-twin-context.js`, `server/services/privacyOrgs.js`, `server/routes/privacy.js`, `server/lib/digitalTwinValidation.js`, `client/src/services/apiPrivacy.js`, `client/src/components/digital-twin/tabs/{AccountsTab,OverviewTab}.jsx`)
diff --git a/client/src/components/digital-twin/tabs/AccountsTab.jsx b/client/src/components/digital-twin/tabs/AccountsTab.jsx
index 136eabbafd..550486ab77 100644
--- a/client/src/components/digital-twin/tabs/AccountsTab.jsx
+++ b/client/src/components/digital-twin/tabs/AccountsTab.jsx
@@ -21,6 +21,7 @@ import {
Edit3,
Check,
X,
+ Building2,
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
@@ -107,6 +108,9 @@ export default function AccountsTab() {
const [form, setForm] = useState(EMPTY_FORM);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(null);
+ // Map socialAccountId → { orgId, orgName } for the "in org registry" badge (#2147).
+ const [orgLinks, setOrgLinks] = useState({});
+ const [linkingId, setLinkingId] = useState(null);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
useEffect(() => {
@@ -114,17 +118,38 @@ export default function AccountsTab() {
}, []);
const loadData = async () => {
- const [accountsData, platformsData, statsData] = await Promise.all([
+ const [accountsData, platformsData, statsData, linksData] = await Promise.all([
api.getSocialAccounts().catch(() => ({ accounts: [] })),
api.getSocialAccountPlatforms().catch(() => ({ platforms: [] })),
- api.getSocialAccountStats().catch(() => null)
+ api.getSocialAccountStats().catch(() => null),
+ // Degrades to no badges if Privacy Center isn't provisioned yet.
+ api.getSocialAccountOrgLinks({ silent: true }).catch(() => [])
]);
setAccounts(accountsData.accounts || []);
setPlatforms(platformsData.platforms || []);
setStats(statsData);
+ setOrgLinks(Object.fromEntries((linksData || []).map(l => [l.socialAccountId, l])));
setLoading(false);
};
+ // "Add to org registry": create a platform-category org linked to this account.
+ const handleAddToOrgRegistry = async (account) => {
+ setLinkingId(account.id);
+ const created = await api.createPrivacyOrg({
+ name: account.displayName || account.username,
+ category: 'platform',
+ website: account.url || '',
+ socialAccountId: account.id,
+ notes: `Linked from Digital Twin social account: ${account.platform}/${account.username}`
+ }).catch(() => null);
+ if (created) {
+ // Reactive update — no full refetch.
+ setOrgLinks(prev => ({ ...prev, [account.id]: { socialAccountId: account.id, orgId: created.id, orgName: created.name } }));
+ toast.success(`Added ${created.name} to org registry`);
+ }
+ setLinkingId(null);
+ };
+
const handleSubmit = async () => {
if (!form.platform || !form.username) {
toast.error('Platform and username are required');
@@ -470,6 +495,28 @@ export default function AccountsTab() {
<ExternalLink className="w-3 h-3" />
</a>
)}
+ {/* Org-registry cross-link (#2147) */}
+ <div className="mt-1">
+ {orgLinks[account.id] ? (
+ <span
+ className="inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 bg-port-success/15 text-port-success rounded border border-port-success/30"
+ title={`In org registry as "${orgLinks[account.id].orgName}"`}
+ >
+ <Building2 className="w-3 h-3" />
+ In org registry
+ </span>
+ ) : (
+ <button
+ onClick={() => handleAddToOrgRegistry(account)}
+ disabled={linkingId === account.id}
+ className="inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 text-gray-400 hover:text-white border border-port-border rounded hover:bg-port-bg transition-colors disabled:opacity-50"
+ title="Track this account in the Privacy Center org registry"
+ >
+ {linkingId === account.id ? <BrailleSpinner /> : <Building2 className="w-3 h-3" />}
+ Add to org registry
+ </button>
+ )}
+ </div>
</div>
{/* Actions */}
diff --git a/client/src/components/digital-twin/tabs/OverviewTab.jsx b/client/src/components/digital-twin/tabs/OverviewTab.jsx
index e306a31b9e..5379dd4f26 100644
--- a/client/src/components/digital-twin/tabs/OverviewTab.jsx
+++ b/client/src/components/digital-twin/tabs/OverviewTab.jsx
@@ -268,6 +268,23 @@ export default function OverviewTab({ status, settings, onRefresh }) {
/>
<span className="text-white">Auto-inject soul context into CoS agents</span>
</label>
+ <label className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ checked={settingsForm.includePrivacyContext || false}
+ onChange={(e) => setSettingsForm({ ...settingsForm, includePrivacyContext: e.target.checked })}
+ className="w-4 h-4 mt-1 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <span className="text-white">
+ Inject Privacy Vault identity facts
+ <span className="block text-xs text-gray-500 mt-0.5">
+ Adds vault records you marked &ldquo;share with twin&rdquo; (legal name, contact
+ details, addresses) plus a one-line org summary to twin &amp; CoS agent prompts.
+ Decrypted only at injection time, never cached. Off by default — sharing PII is
+ opt-in per-field <em>and</em> globally here.
+ </span>
+ </span>
+ </label>
<FormField labelClassName="block text-sm text-gray-400 mb-2" label="Max context tokens">
<input
type="number"
diff --git a/client/src/services/README.md b/client/src/services/README.md
index b7109aff2a..e878e254b3 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -69,6 +69,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiMemory.js` | Memory CRUD. |
| `apiNotes.js` | Notes vault. |
| `apiDigitalTwin.js` | Digital twin status + summary. |
+| `apiPrivacy.js` | Privacy Center — org registry ↔ Digital Twin social-account cross-link. |
| `apiGoals.js` | Identity / goals tracking. |
| `apiHealth.js` | Apple Health. |
| `apiMeatspace.js` | MeatSpace (genome + location). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index b517b6b6c6..6de5af3592 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -38,6 +38,7 @@ export * from './apiTimeline.js';
export * from './apiBrain.js';
export * from './apiNotes.js';
export * from './apiDigitalTwin.js';
+export * from './apiPrivacy.js';
export * from './apiMeatspace.js';
export * from './apiMortalLoom.js';
export * from './apiOpenClaw.js';
diff --git a/client/src/services/apiPrivacy.js b/client/src/services/apiPrivacy.js
new file mode 100644
index 0000000000..14ef847244
--- /dev/null
+++ b/client/src/services/apiPrivacy.js
@@ -0,0 +1,13 @@
+import { request } from './apiCore.js';
+
+// Privacy Center — Trusted Organizations registry (issues #2140, #2141, #2147).
+// Only the Digital Twin cross-link surfaces are wired today; the full vault /
+// org-registry client lands with the Privacy Center UI (Phase 3/5/6).
+
+/** Social-account → org links for the Twin's "in org registry" badges (#2147). */
+export const getSocialAccountOrgLinks = (options) =>
+ request('/privacy/social-account-links', options);
+
+/** Create a trusted-org record (used by the Twin's "Add to org registry"). */
+export const createPrivacyOrg = (data, options) =>
+ request('/privacy/orgs', { method: 'POST', body: JSON.stringify(data), ...options });
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 7e6fb05734..978a60f476 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -150,6 +150,10 @@ export const enrichmentProgressSchema = z.object({
export const digitalTwinSettingsSchema = z.object({
autoInjectToCoS: z.boolean().default(true),
maxContextTokens: z.number().int().min(1000).max(100000).default(4000),
+ // Global gate for injecting Privacy Vault identity facts into twin/CoS prompts
+ // (issue #2147). Default false — PII sharing is opt-in twice (this global
+ // toggle AND the per-record share_with_twin flag).
+ includePrivacyContext: z.boolean().default(false),
// The persona currently driving the embodied-twin context (CoS agents, etc.).
// null/absent = no persona (base twin). Tolerate the UI sentinel for "deactivate".
activePersonaId: z.string().guid().nullable().optional()
@@ -286,7 +290,7 @@ export const digitalTwinMetaSchema = z.object({
adversarialTestHistory: z.array(adversarialTestHistoryEntrySchema).default([]),
multiTurnTestHistory: z.array(multiTurnTestHistoryEntrySchema).default([]),
enrichment: enrichmentProgressSchema.default({ completedCategories: [], lastSession: null }),
- settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000 }),
+ settings: digitalTwinSettingsSchema.default({ autoInjectToCoS: true, maxContextTokens: 4000, includePrivacyContext: false }),
personas: z.array(personaSchema).default([]),
traits: traitsSchema.optional(),
confidence: confidenceSchema.optional()
diff --git a/server/lib/digitalTwinValidation.test.js b/server/lib/digitalTwinValidation.test.js
index 9edb1d9731..e219015701 100644
--- a/server/lib/digitalTwinValidation.test.js
+++ b/server/lib/digitalTwinValidation.test.js
@@ -133,6 +133,12 @@ describe('persona input schemas', () => {
expect(digitalTwinSettingsSchema.safeParse({ activePersonaId: null }).success).toBe(true);
expect(digitalTwinSettingsSchema.safeParse({}).success).toBe(true);
});
+
+ it('defaults includePrivacyContext to false and accepts an explicit boolean (#2147)', () => {
+ expect(digitalTwinSettingsSchema.parse({}).includePrivacyContext).toBe(false);
+ expect(digitalTwinSettingsSchema.safeParse({ includePrivacyContext: true }).success).toBe(true);
+ expect(digitalTwinSettingsSchema.safeParse({ includePrivacyContext: 'yes' }).success).toBe(false);
+ });
});
// Trait-blending (M34 P7) — personas may carry structured `traitAdjustments`.
diff --git a/server/routes/privacy.js b/server/routes/privacy.js
index a27c7af8b2..540604e202 100644
--- a/server/routes/privacy.js
+++ b/server/routes/privacy.js
@@ -39,6 +39,7 @@ import {
deleteOrg,
setOrgHoldings,
getHoldingsForOrg,
+ getOrgsBySocialAccounts,
} from '../services/privacyOrgs.js';
const router = Router();
@@ -92,6 +93,12 @@ router.post('/orgs', asyncHandler(async (req, res) => {
res.status(201).json(await createOrg(data));
}));
+// Digital Twin ↔ org cross-link (issue #2147): which social accounts are in
+// the org registry. Declared before `/orgs/:id` so the literal path wins.
+router.get('/social-account-links', asyncHandler(async (_req, res) => {
+ res.json(await getOrgsBySocialAccounts());
+}));
+
router.get('/orgs/:id', asyncHandler(async (req, res) => {
const { id } = validateRequest(privacyOrgIdParamsSchema, req.params);
const org = await getOrg(id);
diff --git a/server/routes/privacy.test.js b/server/routes/privacy.test.js
index e43b3e4e81..1321ebe820 100644
--- a/server/routes/privacy.test.js
+++ b/server/routes/privacy.test.js
@@ -28,6 +28,7 @@ vi.mock('../services/privacyOrgs.js', () => ({
deleteOrg: vi.fn(async () => ({ ok: true })),
setOrgHoldings: vi.fn(async (id, holdings) => holdings.map((h) => ({ orgId: id, ...h }))),
getHoldingsForOrg: vi.fn(async () => [{ orgId: 'o1', vaultRecordId: 'v1', vaultMaskedValue: 'a•••@b.com' }]),
+ getOrgsBySocialAccounts: vi.fn(async () => [{ socialAccountId: 'acct-1', orgId: 'o1', orgName: 'Acme Bank' }]),
}));
const privacyRoutes = (await import('./privacy.js')).default;
@@ -153,6 +154,22 @@ describe('POST /api/privacy/orgs', () => {
expect((await request(makeApp()).post('/api/privacy/orgs').send({ name: 'X', trust: 'nope' })).status).toBe(400);
expect((await request(makeApp()).post('/api/privacy/orgs').send({ name: 'X', extra: 1 })).status).toBe(400);
});
+
+ it('accepts the social-account cross-link on create (#2147)', async () => {
+ const res = await request(makeApp()).post('/api/privacy/orgs')
+ .send({ name: 'GitHub', category: 'platform', socialAccountId: 'acct-1' });
+ expect(res.status).toBe(201);
+ expect(orgService.createOrg).toHaveBeenCalledWith({ name: 'GitHub', category: 'platform', socialAccountId: 'acct-1' });
+ });
+});
+
+describe('GET /api/privacy/social-account-links', () => {
+ it('returns the social-account → org reverse index (#2147)', async () => {
+ const res = await request(makeApp()).get('/api/privacy/social-account-links');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ socialAccountId: 'acct-1', orgId: 'o1', orgName: 'Acme Bank' }]);
+ expect(orgService.getOrgsBySocialAccounts).toHaveBeenCalled();
+ });
});
describe('GET /api/privacy/orgs/:id', () => {
diff --git a/server/services/digital-twin-context.js b/server/services/digital-twin-context.js
index 570823a060..1c23cd03e6 100644
--- a/server/services/digital-twin-context.js
+++ b/server/services/digital-twin-context.js
@@ -4,6 +4,7 @@ import { join } from 'path';
import { DIGITAL_TWIN_DIR } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
import { renderTraitBlendDirective } from '../lib/personaTraitBlend.js';
+import { getPrivacyTwinContext } from './privacyTwinContext.js';
// Twin document markdown is re-read on every agent prompt build
// (getDigitalTwinForPrompt runs per prompt, per twin test). These files rarely
@@ -80,6 +81,22 @@ export async function getDigitalTwinForPrompt(options = {}) {
let tokenCount = preamble.length;
const maxChars = maxTokens * 4; // Rough char-to-token estimate
+ // Privacy Vault identity dossier — opt-in TWICE: the GLOBAL gate here
+ // (includePrivacyContext, default false) plus the per-field share_with_twin
+ // gate inside getPrivacyTwinContext. Injected before documents as an
+ // authoritative identity block, counting toward the same token budget. Never
+ // cached to disk — decrypted at injection time only. Failures degrade to no
+ // block rather than failing the whole prompt (this also runs outside the
+ // request lifecycle for CoS agent spawns).
+ if (meta.settings?.includePrivacyContext === true) {
+ const privacyBlock = await getPrivacyTwinContext()
+ .catch(err => { console.log(`⚠️ Privacy twin context retrieval failed: ${err.message}`); return ''; });
+ if (privacyBlock && tokenCount + privacyBlock.length + 8 <= maxChars) {
+ output += `${privacyBlock}\n\n---\n\n`;
+ tokenCount += privacyBlock.length + 8;
+ }
+ }
+
for (const doc of docs) {
const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
if (!existsSync(filePath)) continue;
diff --git a/server/services/digital-twin-context.privacy.test.js b/server/services/digital-twin-context.privacy.test.js
new file mode 100644
index 0000000000..748766d5c2
--- /dev/null
+++ b/server/services/digital-twin-context.privacy.test.js
@@ -0,0 +1,57 @@
+/**
+ * Gating tests for Privacy Vault injection into the digital twin prompt
+ * (issue #2147). Verifies the GLOBAL gate (includePrivacyContext): the block
+ * is fetched + injected only when the setting is on. loadMeta and the privacy
+ * context builder are mocked — no fs docs, no DB.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const loadMeta = vi.fn();
+const getPrivacyTwinContext = vi.fn();
+
+vi.mock('./digital-twin-meta.js', () => ({ loadMeta: (...a) => loadMeta(...a) }));
+vi.mock('./privacyTwinContext.js', () => ({ getPrivacyTwinContext: (...a) => getPrivacyTwinContext(...a) }));
+
+const { getDigitalTwinForPrompt } = await import('./digital-twin-context.js');
+
+function metaWith(settings) {
+ return { settings: { autoInjectToCoS: true, maxContextTokens: 4000, ...settings }, documents: [], personas: [], traits: {} };
+}
+
+beforeEach(() => {
+ loadMeta.mockReset();
+ getPrivacyTwinContext.mockReset();
+ getPrivacyTwinContext.mockResolvedValue('# Identity Facts (Privacy Vault)\n- Legal name — legal_name: Ada Lovelace');
+});
+
+describe('getDigitalTwinForPrompt privacy gate', () => {
+ it('does NOT fetch or inject the privacy block when includePrivacyContext is off', async () => {
+ loadMeta.mockResolvedValue(metaWith({ includePrivacyContext: false }));
+ const out = await getDigitalTwinForPrompt();
+ expect(getPrivacyTwinContext).not.toHaveBeenCalled();
+ expect(out).not.toContain('Privacy Vault');
+ });
+
+ it('injects the privacy block when includePrivacyContext is on', async () => {
+ loadMeta.mockResolvedValue(metaWith({ includePrivacyContext: true }));
+ const out = await getDigitalTwinForPrompt();
+ expect(getPrivacyTwinContext).toHaveBeenCalledTimes(1);
+ expect(out).toContain('# Identity Facts (Privacy Vault)');
+ expect(out).toContain('Ada Lovelace');
+ });
+
+ it('degrades to no block (no throw) when the privacy builder fails', async () => {
+ loadMeta.mockResolvedValue(metaWith({ includePrivacyContext: true }));
+ getPrivacyTwinContext.mockRejectedValue(new Error('db down'));
+ const out = await getDigitalTwinForPrompt();
+ expect(out).not.toContain('Privacy Vault');
+ });
+
+ it('emits nothing from the vault when autoInject is off (no injection at all)', async () => {
+ loadMeta.mockResolvedValue(metaWith({ autoInjectToCoS: false, includePrivacyContext: true }));
+ const out = await getDigitalTwinForPrompt();
+ expect(out).toBe('');
+ expect(getPrivacyTwinContext).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/digital-twin-meta.js b/server/services/digital-twin-meta.js
index 23d9377340..7c7b255add 100644
--- a/server/services/digital-twin-meta.js
+++ b/server/services/digital-twin-meta.js
@@ -35,7 +35,7 @@ export const DEFAULT_META = {
multiTurnTestHistory: [],
personas: [],
enrichment: { completedCategories: [], lastSession: null },
- settings: { autoInjectToCoS: true, maxContextTokens: 4000 }
+ settings: { autoInjectToCoS: true, maxContextTokens: 4000, includePrivacyContext: false }
};
export async function loadMeta() {
diff --git a/server/services/privacyOrgs.crosslink.test.js b/server/services/privacyOrgs.crosslink.test.js
new file mode 100644
index 0000000000..db65adfd8a
--- /dev/null
+++ b/server/services/privacyOrgs.crosslink.test.js
@@ -0,0 +1,39 @@
+/**
+ * Unit test for the Digital Twin ↔ org social-account cross-link reverse index
+ * (issue #2147). DB mocked — never touches real Postgres, not a *.db.test.js.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const query = vi.fn();
+vi.mock('../lib/db.js', () => ({
+ query: (...args) => query(...args),
+ withTransaction: vi.fn(),
+}));
+
+const { getOrgsBySocialAccounts } = await import('./privacyOrgs.js');
+
+beforeEach(() => query.mockReset());
+
+describe('getOrgsBySocialAccounts', () => {
+ it('maps only orgs that reference a social account, keyed for the twin', async () => {
+ query.mockResolvedValue({
+ rows: [
+ { id: 'org-1', name: 'GitHub', social_account_id: 'acct-1' },
+ { id: 'org-2', name: 'Acme', social_account_id: 'acct-2' },
+ ],
+ });
+ const result = await getOrgsBySocialAccounts();
+ // Filters to non-null social_account_id in SQL.
+ expect(query.mock.calls[0][0]).toContain('social_account_id IS NOT NULL');
+ expect(result).toEqual([
+ { socialAccountId: 'acct-1', orgId: 'org-1', orgName: 'GitHub' },
+ { socialAccountId: 'acct-2', orgId: 'org-2', orgName: 'Acme' },
+ ]);
+ });
+
+ it('returns an empty array when no orgs are linked', async () => {
+ query.mockResolvedValue({ rows: [] });
+ expect(await getOrgsBySocialAccounts()).toEqual([]);
+ });
+});
diff --git a/server/services/privacyOrgs.js b/server/services/privacyOrgs.js
index 364b7e9a6a..e2b08d456f 100644
--- a/server/services/privacyOrgs.js
+++ b/server/services/privacyOrgs.js
@@ -232,6 +232,26 @@ export async function setHoldingsStatus(vaultRecordId, fromStatus, toStatus) {
return { updated: rows.length };
}
+/**
+ * Reverse index for the Digital Twin ↔ org cross-link (issue #2147): every org
+ * that references one of the twin's social accounts. Keyed by the Twin's
+ * Accounts tab so it can badge "in org registry" without N per-account calls.
+ * Returns `[{ socialAccountId, orgId, orgName }]`.
+ */
+export async function getOrgsBySocialAccounts() {
+ const { rows } = await query(
+ `SELECT id, name, social_account_id
+ FROM privacy_orgs
+ WHERE social_account_id IS NOT NULL
+ ORDER BY name`,
+ );
+ return rows.map((row) => ({
+ socialAccountId: row.social_account_id,
+ orgId: row.id,
+ orgName: row.name,
+ }));
+}
+
/** Per-org holding counts + per-vault-record org counts — powers the inventory view. */
export async function getHoldingsSummary() {
const [byOrg, byRecord] = await Promise.all([
diff --git a/server/services/privacyTwinContext.js b/server/services/privacyTwinContext.js
new file mode 100644
index 0000000000..ae332847a1
--- /dev/null
+++ b/server/services/privacyTwinContext.js
@@ -0,0 +1,120 @@
+/**
+ * Privacy → Digital Twin context bridge (issue #2147, epic #2138).
+ *
+ * Builds a compact identity-dossier block from the encrypted PII vault for
+ * injection into the digital twin's agent prompts. Sharing PII with agent
+ * prompts is opt-in TWICE:
+ * - per-field: only vault records the user flagged `share_with_twin = true`
+ * (enforced here by the WHERE clause);
+ * - global: only when the twin setting `includePrivacyContext` is on
+ * (enforced by the caller in digital-twin-context.js).
+ *
+ * Vault values are decrypted AT INJECTION TIME ONLY and are NEVER cached to
+ * disk or logged — the returned string is handed straight into the in-memory
+ * prompt and discarded. Logs carry counts only, mirroring the vault's
+ * plaintext-never-logged posture (see privacyVault.js).
+ *
+ * Degrades gracefully when the privacy tables haven't been provisioned yet (a
+ * fresh install before the migrations run, or the Phase 5/6 broker tables that
+ * don't exist yet): a missing table yields an empty/omitted section via a
+ * `to_regclass` existence gate rather than throwing, so the twin prompt builder
+ * never fails just because Privacy Center isn't set up.
+ */
+
+import { query } from '../lib/db.js';
+// vaultCrypto is imported lazily (inside getPrivacyTwinContext) so merely
+// importing this module — which digital-twin-context.js does at top level —
+// doesn't eagerly evaluate vaultCrypto's install-root .env path resolution.
+// It's only needed when a context block is actually being built (which already
+// requires a live DB), and dynamic import stays subject to the same vi.mock.
+
+// Broker-case states that count as "confirmed removed" for the posture line.
+// The Phase 5/6 state machine is not built yet; treat this as a
+// forward-compatible superset — anything else is "pending".
+const REMOVED_BROKER_STATES = new Set(['removed', 'confirmed_removed', 'suppressed']);
+
+/** One-line "Organizations on file" summary (counts by trust + category span). */
+async function buildOrgSummary() {
+ const { rows } = await query(`SELECT trust, category FROM privacy_orgs`);
+ if (rows.length === 0) return '';
+ const byTrust = {};
+ const categories = new Set();
+ for (const row of rows) {
+ byTrust[row.trust] = (byTrust[row.trust] || 0) + 1;
+ if (row.category) categories.add(row.category);
+ }
+ const trustParts = Object.entries(byTrust)
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([trust, n]) => `${n} ${trust}`)
+ .join(', ');
+ const categoryWord = categories.size === 1 ? 'category' : 'categories';
+ return `Organizations on file: ${rows.length} (${trustParts}) across ${categories.size} ${categoryWord}.`;
+}
+
+/** One-line data-broker opt-out posture (only when Phase 5/6 tables exist). */
+async function buildBrokerPosture() {
+ const { rows } = await query(`SELECT state FROM privacy_broker_cases`);
+ if (rows.length === 0) return '';
+ let removed = 0;
+ for (const row of rows) if (REMOVED_BROKER_STATES.has(row.state)) removed += 1;
+ const pending = rows.length - removed;
+ return `Data-broker posture: ${removed} confirmed removed, ${pending} pending.`;
+}
+
+/**
+ * Compact identity-context block from the vault, or '' when nothing is shared
+ * (no flagged records and no orgs) or Privacy Center is not provisioned. The
+ * caller is responsible for the GLOBAL gate (`includePrivacyContext`) and for
+ * fitting the block into the twin's token budget.
+ */
+export async function getPrivacyTwinContext() {
+ // Single round-trip existence gate — a null column means the table is absent.
+ const { rows: tableRows } = await query(
+ `SELECT to_regclass('public.privacy_vault_records') AS vault,
+ to_regclass('public.privacy_orgs') AS orgs,
+ to_regclass('public.privacy_broker_cases') AS broker`,
+ );
+ const tables = tableRows[0] ?? {};
+ // No vault table ⇒ Privacy Center not provisioned; nothing to inject.
+ if (!tables.vault) return '';
+
+ const sections = [];
+
+ // Per-field gate: only records the user explicitly flagged for the twin.
+ const { rows: records } = await query(
+ `SELECT type, label, status, value_enc
+ FROM privacy_vault_records
+ WHERE share_with_twin = true
+ ORDER BY type, label`,
+ );
+ if (records.length > 0) {
+ const { decryptValue } = await import('../lib/vaultCrypto.js');
+ const lines = records.map((row) => {
+ const value = decryptValue(row.value_enc); // decrypt at injection time only
+ const suffix = row.status === 'previous' ? ' (previous)' : '';
+ return `- ${row.label} — ${row.type}${suffix}: ${value}`;
+ });
+ sections.push(
+ '# Identity Facts (Privacy Vault)\n'
+ + 'Authoritative, user-verified identity facts. Treat these as the source '
+ + "of truth for the user's legal name, contact details, and addresses.\n"
+ + lines.join('\n'),
+ );
+ }
+
+ // Org summary + broker posture only when their tables exist (graceful degrade).
+ const posture = [];
+ if (tables.orgs) {
+ const orgLine = await buildOrgSummary();
+ if (orgLine) posture.push(orgLine);
+ }
+ if (tables.broker) {
+ const brokerLine = await buildBrokerPosture();
+ if (brokerLine) posture.push(brokerLine);
+ }
+ if (posture.length > 0) sections.push(posture.join('\n'));
+
+ if (sections.length === 0) return '';
+ console.log(`🔐 Built privacy twin context (${records.length} vault fact(s))`);
+ return sections.join('\n\n');
+}
diff --git a/server/services/privacyTwinContext.test.js b/server/services/privacyTwinContext.test.js
new file mode 100644
index 0000000000..10c3b74e53
--- /dev/null
+++ b/server/services/privacyTwinContext.test.js
@@ -0,0 +1,116 @@
+/**
+ * Unit tests for getPrivacyTwinContext (issue #2147). DB + crypto are mocked —
+ * this is a pure logic test, never touches a real Postgres (see CLAUDE.md
+ * DB-test safety) and never runs as a *.db.test.js.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const query = vi.fn();
+vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));
+// decrypt is deterministic in the mock: ciphertext "enc:<v>" → "<v>".
+vi.mock('../lib/vaultCrypto.js', () => ({
+ decryptValue: vi.fn((ct) => ct.replace(/^enc:/, '')),
+}));
+
+const { getPrivacyTwinContext } = await import('./privacyTwinContext.js');
+const { decryptValue } = await import('../lib/vaultCrypto.js');
+
+// Route a query to a canned result by matching a substring of the SQL.
+function routeQueries(map) {
+ query.mockImplementation((sql) => {
+ for (const [needle, rows] of map) {
+ if (sql.includes(needle)) return Promise.resolve({ rows });
+ }
+ return Promise.resolve({ rows: [] });
+ });
+}
+
+const ALL_TABLES = [{ vault: 'privacy_vault_records', orgs: 'privacy_orgs', broker: 'privacy_broker_cases' }];
+
+beforeEach(() => {
+ query.mockReset();
+ decryptValue.mockClear();
+});
+
+describe('getPrivacyTwinContext', () => {
+ it('returns empty string when the vault table does not exist (graceful degrade)', async () => {
+ routeQueries([['to_regclass', [{ vault: null, orgs: null, broker: null }]]]);
+ expect(await getPrivacyTwinContext()).toBe('');
+ // Never queries records when the vault table is absent.
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('injects only share_with_twin records, decrypted at injection time', async () => {
+ routeQueries([
+ ['to_regclass', [{ vault: 'privacy_vault_records', orgs: null, broker: null }]],
+ ['FROM privacy_vault_records', [
+ { type: 'legal_name', label: 'Legal name', status: 'current', value_enc: 'enc:Ada Lovelace' },
+ { type: 'address', label: 'Home', status: 'previous', value_enc: 'enc:1 Old St' },
+ ]],
+ ]);
+ const out = await getPrivacyTwinContext();
+ // Per-field gate is enforced in SQL.
+ const recordCall = query.mock.calls.find(([sql]) => sql.includes('FROM privacy_vault_records'));
+ expect(recordCall[0]).toContain('share_with_twin = true');
+ // Decrypted values present; masked/ciphertext never leaks.
+ expect(out).toContain('Ada Lovelace');
+ expect(out).toContain('address (previous): 1 Old St');
+ expect(out).not.toContain('enc:');
+ expect(decryptValue).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns empty string when nothing is flagged and no orgs exist', async () => {
+ routeQueries([
+ ['to_regclass', [{ vault: 'privacy_vault_records', orgs: 'privacy_orgs', broker: null }]],
+ ['FROM privacy_vault_records', []],
+ ['FROM privacy_orgs', []],
+ ]);
+ expect(await getPrivacyTwinContext()).toBe('');
+ });
+
+ it('adds a one-line org summary grouped by trust + category span', async () => {
+ routeQueries([
+ ['to_regclass', [{ vault: 'privacy_vault_records', orgs: 'privacy_orgs', broker: null }]],
+ ['FROM privacy_vault_records', [
+ { type: 'email', label: 'Main', status: 'current', value_enc: 'enc:[email protected]' },
+ ]],
+ ['FROM privacy_orgs', [
+ { trust: 'trusted', category: 'bank' },
+ { trust: 'trusted', category: 'employer' },
+ { trust: 'unwanted', category: 'broker' },
+ ]],
+ ]);
+ const out = await getPrivacyTwinContext();
+ expect(out).toContain('Organizations on file: 3 (2 trusted, 1 unwanted) across 3 categories.');
+ });
+
+ it('omits the broker posture line when the broker table is absent', async () => {
+ routeQueries([
+ ['to_regclass', [{ vault: 'privacy_vault_records', orgs: 'privacy_orgs', broker: null }]],
+ ['FROM privacy_vault_records', [
+ { type: 'email', label: 'Main', status: 'current', value_enc: 'enc:[email protected]' },
+ ]],
+ ['FROM privacy_orgs', []],
+ ]);
+ const out = await getPrivacyTwinContext();
+ expect(out).not.toContain('Data-broker posture');
+ // Never queries privacy_broker_cases when the table doesn't exist.
+ expect(query.mock.calls.some(([sql]) => sql.includes('FROM privacy_broker_cases'))).toBe(false);
+ });
+
+ it('adds a broker posture line (removed vs pending) when the table exists', async () => {
+ routeQueries([
+ ['to_regclass', ALL_TABLES],
+ ['FROM privacy_vault_records', [
+ { type: 'email', label: 'Main', status: 'current', value_enc: 'enc:[email protected]' },
+ ]],
+ ['FROM privacy_orgs', []],
+ ['FROM privacy_broker_cases', [
+ { state: 'removed' }, { state: 'confirmed_removed' }, { state: 'found' }, { state: 'pending' },
+ ]],
+ ]);
+ const out = await getPrivacyTwinContext();
+ expect(out).toContain('Data-broker posture: 2 confirmed removed, 2 pending.');
+ });
+});