an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(voice): redacted read path to hive messages (get_messages)
Chaitanya Giria35bc40fd37f
diff --git a/src/main/hive.ts b/src/main/hive.tsindex 81da4938..5c7679ed 100644--- a/src/main/hive.ts+++ b/src/main/hive.ts@@ -61,6 +61,31 @@ export interface HiveMessage {created_at: string;}+/** One hive message reshaped for the voice read-layer (`hive:messages`): the+ * operator-briefing view of an inbox/outbox message. `subject` and `body` are+ * REDACTED main-side (see {@link redactSecrets}) before this ever leaves the+ * main process — the renderer/voice layer never sees a raw body, and never a+ * secret. PII-free + secret-free by construction. */+export interface VoiceMessage {+ id: string;+ conversation: string;+ from: string;+ to: string;+ act: MessageAct;+ /** REDACTED subject line. */+ subject: string;+ /** REDACTED message body. */+ body: string;+ requires_reply: boolean;+ /** Which mailbox folder this copy was read from, relative to `owner`. */+ direction: 'inbox' | 'outbox';+ /** The agent whose mailbox this copy lives in. */+ owner: string;+ /** True when read from an archived/handled subfolder (inbox/.done, outbox/.sent). */+ archived: boolean;+ created_at: string;+}+/** One question→answer exchange with the human, recorded ON the task card so* the decision trail stays with the work it unblocked. */export interface HumanQA {@@ -181,6 +206,56 @@ function ensureMineIgnore(agentDir: string): void {try { writeFileSync(path, prefix + missing.join('\n') + '\n', 'utf8'); } catch { /* best-effort */ }}+/**+ * Strip secret-shaped substrings out of free text before it leaves the main+ * process toward the voice / renderer layer. This is the MAIN-SIDE privacy gate+ * for the voice read-layer's message-content path (`hive:messages`): a message+ * body can quote a key, paste a token, or echo a credential, so every body and+ * subject is run through this before it crosses IPC. The renderer holds ZERO+ * redaction policy — it only ever receives the already-cleaned string.+ *+ * Deliberately CONSERVATIVE: it matches known credential SHAPES (provider key+ * prefixes, JWTs, PEM private keys, bearer tokens) and sensitive key=value /+ * key: value assignments, then replaces the secret with `[redacted]`. It does+ * NOT blanket-redact on entropy, so operator-meaningful content the briefing+ * needs — git SHAs, agent ids, file paths, ordinary prose — survives intact.+ * Over-redaction (e.g. a non-secret `apikey:openai` ref) is acceptable; leaking+ * a real secret is not.+ *+ * LOCKSTEP: the regex battery below is mirrored character-identically in+ * test/voice-messages.test.cjs (a .cjs test cannot import this TS module). If+ * you change a pattern here, mirror it there — the test is what PROVES a+ * secret-shaped value is stripped.+ */+export function redactSecrets(text: unknown): string {+ if (typeof text !== 'string' || !text) return typeof text === 'string' ? text : '';+ let s = text;+ // 1. PEM private-key blocks (RSA/EC/OPENSSH/PGP — header through footer).+ s = s.replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, '[redacted]');+ // 2. JSON Web Tokens — three base64url segments separated by dots.+ s = s.replace(/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, '[redacted]');+ // 3. Known credential prefixes: OpenAI/Anthropic (sk-, sk-ant-), Slack+ // (xoxb/xoxp/xoxa/xoxr/xoxs-, xapp-), GitHub (ghp_/gho_/ghu_/ghs_/ghr_,+ // github_pat_), AWS access-key ids (AKIA…), Google API keys (AIza…).+ s = s.replace(+ /(?:sk-(?:ant-)?[A-Za-z0-9_-]{16,}|xox[bpaors]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,}|gh[posru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[A-Za-z0-9_-]{20,})/g,+ '[redacted]'+ );+ // 4. Bearer tokens — keep the label, drop the credential.+ s = s.replace(/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 [redacted]');+ // 5. Sensitive key = value / key: value — keep the key name, drop the value.+ // An optional namespace prefix (aws_, gcp_, …) is folded into the captured+ // key so a LABELED secret survives the \b boundary: `aws_secret_access_key`+ // is all word chars, so a bare `\b(secret)\b` never sees it. Listing+ // secret_access_key / private_key alone is not enough — the prefix run is+ // what lets `aws_secret_access_key=…` (no AKIA shape on the value) redact.+ s = s.replace(+ /\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|secret[_-]?access[_-]?key|secret|token|password|passwd|pwd|access[_-]?token|refresh[_-]?token|client[_-]?secret|signing[_-]?secret|webhook[_-]?secret|auth[_-]?token|bot[_-]?token|private[_-]?key))(\s*[:=]\s*)(["']?)[^\s"',}]{6,}\3/gi,+ (_m, k) => `${k}=[redacted]`+ );+ return s;+}+// ─── HiveManager ────────────────────────────────────────────────────────────export class HiveManager {@@ -1131,6 +1206,92 @@ export class HiveManager {inbox(id: string): HiveMessage[] {return this.listMessages(join(this.agentDir(id), 'inbox'));}+ /** Read an agent's OUTBOX (messages it has authored/sent). Symmetric with+ * inbox(); the router drains live outbox files into recipients' inboxes and+ * archives the original under outbox/.sent, so a sent message survives there. */+ outbox(id: string): HiveMessage[] {+ return this.listMessages(join(this.agentDir(id), 'outbox'));+ }++ /**+ * Voice read-layer: recent message CONTENT (inbox + outbox bodies) for the+ * operator briefing, REDACTED main-side. This is the message-content half of+ * the voice query surface (the activity half is logTail()).+ *+ * Modes:+ * - { id } → the single message with that id, wherever it lives.+ * - { agentId } → recent messages in that agent's mailbox only.+ * - {} → recent messages across the whole floor, newest first.+ * `limit` caps the list (default 12, max 40); `includeArchived` (default true)+ * also reads the handled subfolders (inbox/.done, outbox/.sent).+ *+ * SECURITY: every subject + body is passed through redactSecrets() here, in+ * main, so no secret and no raw body ever crosses IPC. Delivered messages exist+ * in both the sender's outbox/.sent and the recipient's inbox/.done; we dedup+ * by message id so each appears once.+ */+ voiceMessages(opts: { agentId?: string; id?: string; limit?: number; includeArchived?: boolean } = {}): VoiceMessage[] {+ const root = this.root();+ if (!root) return [];+ const agentsDir = join(root, 'agents');+ if (!existsSync(agentsDir)) return [];++ const wantId = typeof opts.id === 'string' ? opts.id.trim() : '';+ const onlyAgent = typeof opts.agentId === 'string' ? opts.agentId.trim() : '';+ const includeArchived = opts.includeArchived !== false; // default true++ let owners: string[];+ try {+ owners = onlyAgent+ ? [onlyAgent]+ : readdirSync(agentsDir).filter((id) => !id.startsWith('.') && existsSync(this.agentDir(id)));+ } catch {+ return [];+ }++ const seen = new Set<string>();+ const out: VoiceMessage[] = [];+ for (const owner of owners) {+ const base = this.agentDir(owner);+ const folders: Array<{ dir: string; direction: 'inbox' | 'outbox'; archived: boolean }> = [+ { dir: join(base, 'inbox'), direction: 'inbox', archived: false },+ { dir: join(base, 'outbox'), direction: 'outbox', archived: false }+ ];+ if (includeArchived) {+ folders.push({ dir: join(base, 'inbox', '.done'), direction: 'inbox', archived: true });+ folders.push({ dir: join(base, 'outbox', '.sent'), direction: 'outbox', archived: true });+ }+ for (const f of folders) {+ for (const m of this.listMessages(f.dir)) {+ if (!m || typeof m.id !== 'string' || seen.has(m.id)) continue;+ seen.add(m.id);+ if (wantId && m.id !== wantId) continue;+ out.push({+ id: m.id,+ conversation: m.conversation,+ from: m.from,+ to: m.to,+ act: m.act,+ subject: redactSecrets(m.subject),+ body: redactSecrets(m.body),+ requires_reply: !!m.requires_reply,+ direction: f.direction,+ owner,+ archived: f.archived,+ created_at: m.created_at+ });+ }+ }+ }++ // Newest first by ISO created_at (lexicographic == chronological for ISO-8601).+ out.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));+ if (wantId) return out.slice(0, 1);+ const lim = typeof opts.limit === 'number' && isFinite(opts.limit)+ ? Math.max(1, Math.min(40, Math.round(opts.limit)))+ : 12;+ return out.slice(0, lim);+ }/** Count undrained inbox messages for an agent (cheap — for the fleet snapshot). */inboxBacklog(id: string): number {const dir = join(this.agentDir(id), 'inbox');diff --git a/src/main/index.ts b/src/main/index.tsindex e774f0c5..31271bb0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2331,6 +2331,12 @@ ipcMain.handle('hive:tasks', () => hive.tasks());ipcMain.handle('hive:log', (_evt, n: unknown) => hive.logTail(typeof n === 'number' ? n : 200));ipcMain.handle('hive:memory', (_evt, id: unknown) => (typeof id === 'string' ? hive.memory(id) : ''));ipcMain.handle('hive:inbox', (_evt, id: unknown) => (typeof id === 'string' ? hive.inbox(id) : []));+// Voice read-layer: recent message CONTENT (inbox/outbox bodies), REDACTED+// main-side by hive.voiceMessages(). The renderer/voice layer never sees a raw+// body — secrets are stripped here, before the result crosses IPC.+ipcMain.handle('hive:messages', (_evt, opts: unknown) =>+ hive.voiceMessages(opts && typeof opts === 'object' ? (opts as Parameters<typeof hive.voiceMessages>[0]) : {})+);ipcMain.handle('hive:send', (_evt, partial: Partial<HiveMessage>, from: unknown) => {if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };const msg = hive.send(partial ?? {}, typeof from === 'string' ? from : 'system');diff --git a/src/preload/index.ts b/src/preload/index.tsindex 8dc6d390..58fc2501 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -41,6 +41,25 @@ export interface HiveMessage {created_at: string;}+/** A hive message reshaped for the voice read-layer (`hive:messages`). `subject`+ * and `body` are REDACTED in the main process before crossing this boundary —+ * the renderer never receives a raw body or a secret. Mirror of `VoiceMessage`+ * in src/main/hive.ts. */+export interface VoiceMessage {+ id: string;+ conversation: string;+ from: string;+ to: string;+ act: HiveMessage['act'];+ subject: string;+ body: string;+ requires_reply: boolean;+ direction: 'inbox' | 'outbox';+ owner: string;+ archived: boolean;+ created_at: string;+}+export interface HiveRegistry {godId: string | null;/** `archived` agents have had their terminal closed — retained + flagged, not@@ -571,6 +590,12 @@ const api = {hiveLog: (n?: number): Promise<unknown[]> => ipcRenderer.invoke('hive:log', n ?? 200),hiveMemory: (id: string): Promise<string> => ipcRenderer.invoke('hive:memory', id),hiveInbox: (id: string): Promise<HiveMessage[]> => ipcRenderer.invoke('hive:inbox', id),+ /** Voice read-layer: recent message CONTENT (inbox/outbox bodies), REDACTED in+ * main. Pass { id } for one message, { agentId } to scope to one mailbox, or+ * {} for the whole floor. Backs Realtime Michael's get_messages. The renderer+ * never sees a raw body or a secret — stripping happens main-side. */+ hiveMessages: (opts?: { agentId?: string; id?: string; limit?: number; includeArchived?: boolean }): Promise<VoiceMessage[]> =>+ ipcRenderer.invoke('hive:messages', opts ?? {}),/** Consolidated per-agent directory (registry + telemetry + context), incl.* archived agents. Backs Realtime Michael's get_agent_detail / list_agents. */hiveAgentDirectory: (): Promise<AgentDirectory> => ipcRenderer.invoke('hive:agentDirectory'),diff --git a/src/renderer/src/realtime/VOICE-MESSAGE-ACCESS.md b/src/renderer/src/realtime/VOICE-MESSAGE-ACCESS.mdnew file mode 100644index 00000000..a591c0f4--- /dev/null+++ b/src/renderer/src/realtime/VOICE-MESSAGE-ACCESS.md@@ -0,0 +1,74 @@+# Voice read-layer — hive activity & message content++How Realtime "Michael" (the voice agent in the renderer) reads recent hive+activity and message bodies to brief the operator, and the privacy boundary that+keeps it safe. Card: `enable-voice-agent-acces-cnzlfs`.++## The query path++The voice agent runs in the renderer; the hive data lives on disk under+`HIVE_ROOT/{log.jsonl, agents/<id>/inbox|outbox, registry.json, fleet.json}`.+Two read tools bridge the gap, each a thin wrapper over a main-process IPC+handler:++| Tool (renderer) | IPC handler | Source | Returns |+|-------------------|--------------------|------------------------------------------|---------|+| `get_activity` | `hive:log` | `log.jsonl` (lifecycle events) | event **metadata** — newest first |+| `get_messages` | `hive:messages` | `agents/<id>/inbox` + `outbox` (+ handled) | message **content** — redacted bodies |++`get_messages` modes: `{ id }` reads one message in full; `{ agentId }` scopes to+one mailbox; `{}` returns the latest across the floor. Both tools format their+result as short spoken prose (no markdown) — see `tools.ts`.++## Privacy / safety filtering++The OpenAI / BYOK key never crosses IPC — that boundary is unchanged here. For+message bodies, **all redaction is main-side** (`redactSecrets()` in+`src/main/hive.ts`): `voiceMessages()` runs every `subject` and `body` through it+before the result leaves the main process, so the renderer/voice layer never+receives a raw body and never a secret. The renderer holds **zero** redaction+policy.++`redactSecrets()` is deliberately conservative — it strips known credential+**shapes**, not high-entropy strings, so operator-meaningful content survives:++- Stripped → `[redacted]`: provider keys (`sk-`, `sk-ant-`), Slack (`xoxb/xoxp/…`,+ `xapp-`), GitHub (`ghp_/gho_/…`, `github_pat_`), AWS (`AKIA…`), Google (`AIza…`),+ JWTs, PEM private-key blocks, `Bearer <token>`, and sensitive+ `key=value` / `key: value` assignments (api_key, secret, token, password,+ client_secret, signing_secret, webhook_secret, bot_token, …).+- Preserved: git SHAs, agent ids, file paths, ordinary prose, token counts.++Over-redaction (e.g. a non-secret `apikey:openai` *reference*) is acceptable;+leaking a real secret is not. The exact battery is proven by+`test/voice-messages.test.cjs` (kept in lockstep with `hive.ts`).++## Sources that expose METADATA ONLY (and why)++- **`log.jsonl` (`get_activity`)** — lifecycle events only (`kind`, `agentId`,+ `ts`, actor). It never carries message bodies by design: it is high-frequency+ and append-only, so bodies belong on the dedicated, redacted `get_messages`+ path instead. This keeps the activity feed cheap and free of un-redacted text.+- **`registry.json` / `fleet.json`** (via `get_fleet_status` / `list_agents` /+ `get_agent_detail`) — agent metadata (status, cwd, tokens, breaker). No bodies.+- **`get_config`** — a hand-picked non-sensitive allowlist; never the raw config+ (which holds secrets).++## Limitations++- **Redaction is pattern-based, best-effort.** It catches known credential shapes+ and sensitive assignments. A secret pasted in an unusual, label-free,+ shape-free form (e.g. a bare random string with no prefix and no `key:`) is not+ guaranteed to be caught. It does not redact PII beyond credentials.+- **Message scope.** `get_messages` reads `inbox`/`outbox` and their handled+ subfolders (`inbox/.done`, `outbox/.sent`). Messages purged from disk are gone;+ there is no separate archive store.+- **Dedup.** A delivered message exists in both sender outbox and recipient+ inbox; results dedup by message id, so the `direction`/`owner`/`archived`+ fields reflect the first copy encountered during traversal.+- **Read-only.** This path only reads + briefs. It adds no write/mutate+ capability — voice writes still go through the separate, confirm-gated action+ spine (`realtimeActions.ts`), untouched by this card.+- **Not live-voice-verified.** Logic is unit-tested and type/build-green; an+ end-to-end voice check needs a real OpenAI Realtime key (human-gated, same as+ all realtime work).diff --git a/src/renderer/src/realtime/session.ts b/src/renderer/src/realtime/session.tsindex a1883ef2..8c7ead55 100644--- a/src/renderer/src/realtime/session.ts+++ b/src/renderer/src/realtime/session.ts@@ -90,7 +90,8 @@ WHAT YOU CAN LOOK UP. You have live, read-only awareness of the WHOLE hive throu- get_schedules — the recurring scheduled missions.- get_config — non-sensitive settings (autonomy, default model, caps, breaker, which features are on). Never secrets.- get_cost — token usage across the hive.-- get_activity — the recent hive activity log.+- get_activity — the recent hive activity log: WHAT happened (spawns, archives, messages), as events.+- get_messages — the CONTENT of messages agents sent each other: what was actually said in inboxes and outboxes. Use it to brief the operator on what a message SAID, not just that it happened — read one agent's mailbox, one message by id, or the latest across the floor. Secrets and keys are stripped before you see them, so you can quote bodies safely.NEVER say "I can't access that", "the tool doesn't allow that", or "I don't have that" BEFORE you have actually CALLED a tool. You CAN read any agent's memory (active OR archived), any agent's working directory, full per-agent status, token usage, context-window fill, schedules, configuration, and the board. When a question is about the hive, call the matching tool FIRST and answer with specific facts — real names, real statuses, real numbers — never a vague guess. Only if a tool genuinely returns nothing do you say so, plainly and briefly.diff --git a/src/renderer/src/realtime/tools.ts b/src/renderer/src/realtime/tools.tsindex f4881b6f..f50ce0a3 100644--- a/src/renderer/src/realtime/tools.ts+++ b/src/renderer/src/realtime/tools.ts@@ -414,6 +414,52 @@ export function realtimeReadTools(): ReturnType<typeof tool>[] {}, 'activity log')}),+ // ── get_messages ──────────────────────────────────────────────────────+ tool({+ name: 'get_messages',+ description:+ "Read the actual CONTENT of hive messages — what agents have said to each other in their inboxes and outboxes, not just that an event happened. Use this when the user wants to know what a message SAID, what someone asked or reported, or to catch up on the latest traffic. Pass an agentId to focus on one agent's mailbox, pass a messageId to read one specific message in full, or pass neither for the most recent messages across the whole floor. Secrets and keys are always stripped before you see them, so quote bodies freely.",+ parameters: {+ type: 'object',+ properties: {+ agentId: { type: 'string', description: "Optional. Focus on one agent's inbox and outbox (id or, if you have it, the exact id)." },+ messageId: { type: 'string', description: 'Optional. Read one specific message in full by its id.' },+ limit: { type: 'number', description: 'Optional. How many recent messages to summarize (default 8, max 40).' }+ },+ required: [],+ additionalProperties: false+ },+ execute: (input) =>+ spoken(async () => {+ const a = obj(input);+ const agentId = str(a.agentId).trim();+ const messageId = str(a.messageId).trim();+ const limit = typeof a.limit === 'number' && isFinite(a.limit) ? Math.max(1, Math.min(40, Math.round(a.limit))) : 8;++ // Speak one message's body relative to a perspective. from→to + subject + body.+ const speakOne = (m: { from: string; to: string; subject: string; body: string; created_at: string; requires_reply: boolean }, full: boolean): string => {+ const subj = str(m.subject).trim();+ const body = despan(str(m.body)).trim();+ const head = `${str(m.from) || 'someone'} to ${str(m.to) || 'someone'}${subj ? ` about "${clip(subj, 80)}"` : ''} ${ago(Date.parse(m.created_at))}`;+ if (!body) return `${head}, with no body.`;+ return `${head}: ${clip(body, full ? 700 : 220)}${m.requires_reply ? ' (a reply was requested)' : ''}`;+ };++ if (messageId) {+ const found = await window.cth.hiveMessages({ id: messageId });+ if (!found.length) return `I couldn't find a message with id ${messageId}.`;+ return `That message — ${speakOne(found[0], true)}.`;+ }++ const msgs = await window.cth.hiveMessages(agentId ? { agentId, limit } : { limit });+ if (!msgs.length)+ return agentId ? `I don't see any messages in ${agentId}'s mailbox.` : 'There are no hive messages to read yet.';+ const scope = agentId ? `${agentId}'s mailbox` : 'the floor';+ const lines = msgs.slice(0, limit).map((m) => speakOne(m, false));+ return `${plural(lines.length, 'recent message')} from ${scope}: ${lines.join('. ')}.`;+ }, 'messages')+ }),+// ── get_agent_detail ──────────────────────────────────────────────────tool({name: 'get_agent_detail',diff --git a/test/voice-messages.test.cjs b/test/voice-messages.test.cjsnew file mode 100644index 00000000..c5b244e5--- /dev/null+++ b/test/voice-messages.test.cjs@@ -0,0 +1,247 @@+'use strict';++/*+ * Unit tests for the voice read-layer's MESSAGE-CONTENT + RECENT-ACTIVITY path+ * (card enable-voice-agent-acces-cnzlfs).+ *+ * The logic under test lives in src/main/hive.ts — redactSecrets() (the+ * main-side privacy gate) and voiceMessages() (dedup + sort + slice over an+ * agent's inbox/outbox). hive.ts is TypeScript and these are not importable from+ * a plain .cjs test, so the redaction battery and the selection core below are a+ * CHARACTER-IDENTICAL copy (minus TS type annotations). Same convention as+ * test/realtime-findcard.test.cjs. KEEP IN LOCKSTEP: if you change redactSecrets+ * or voiceMessages in hive.ts, mirror the change here — these tests are what+ * PROVE a secret-shaped value is stripped and that retrieval behaves.+ *+ * Run: node test/voice-messages.test.cjs (exit 0 = all pass)+ */++const assert = require('assert');++// ── redactSecrets — MIRROR of src/main/hive.ts redactSecrets() ───────────────+function redactSecrets(text) {+ if (typeof text !== 'string' || !text) return typeof text === 'string' ? text : '';+ let s = text;+ // 1. PEM private-key blocks (RSA/EC/OPENSSH/PGP — header through footer).+ s = s.replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, '[redacted]');+ // 2. JSON Web Tokens — three base64url segments separated by dots.+ s = s.replace(/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, '[redacted]');+ // 3. Known credential prefixes: OpenAI/Anthropic (sk-, sk-ant-), Slack+ // (xoxb/xoxp/xoxa/xoxr/xoxs-, xapp-), GitHub (ghp_/gho_/ghu_/ghs_/ghr_,+ // github_pat_), AWS access-key ids (AKIA…), Google API keys (AIza…).+ s = s.replace(+ /(?:sk-(?:ant-)?[A-Za-z0-9_-]{16,}|xox[bpaors]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,}|gh[posru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[A-Za-z0-9_-]{20,})/g,+ '[redacted]'+ );+ // 4. Bearer tokens — keep the label, drop the credential.+ s = s.replace(/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 [redacted]');+ // 5. Sensitive key = value / key: value — keep the key name, drop the value.+ // An optional namespace prefix (aws_, gcp_, …) is folded into the captured+ // key so a LABELED secret survives the \b boundary: `aws_secret_access_key`+ // is all word chars, so a bare `\b(secret)\b` never sees it. Listing+ // secret_access_key / private_key alone is not enough — the prefix run is+ // what lets `aws_secret_access_key=…` (no AKIA shape on the value) redact.+ s = s.replace(+ /\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|secret[_-]?access[_-]?key|secret|token|password|passwd|pwd|access[_-]?token|refresh[_-]?token|client[_-]?secret|signing[_-]?secret|webhook[_-]?secret|auth[_-]?token|bot[_-]?token|private[_-]?key))(\s*[:=]\s*)(["']?)[^\s"',}]{6,}\3/gi,+ (_m, k) => `${k}=[redacted]`+ );+ return s;+}++// ── selection core — MIRROR of src/main/hive.ts voiceMessages() inner logic ──+// `tagged` is the folder-traversal order: [{ msg, owner, direction, archived }].+function toVoice(m, owner, direction, archived) {+ return {+ id: m.id, conversation: m.conversation, from: m.from, to: m.to, act: m.act,+ subject: redactSecrets(m.subject), body: redactSecrets(m.body),+ requires_reply: !!m.requires_reply, direction, owner, archived, created_at: m.created_at+ };+}+function selectMessages(tagged, opts = {}) {+ const wantId = typeof opts.id === 'string' ? opts.id.trim() : '';+ const seen = new Set();+ const out = [];+ for (const t of tagged) {+ const m = t.msg;+ if (!m || typeof m.id !== 'string' || seen.has(m.id)) continue;+ seen.add(m.id);+ if (wantId && m.id !== wantId) continue;+ out.push(toVoice(m, t.owner, t.direction, t.archived));+ }+ out.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));+ if (wantId) return out.slice(0, 1);+ const lim = typeof opts.limit === 'number' && isFinite(opts.limit)+ ? Math.max(1, Math.min(40, Math.round(opts.limit)))+ : 12;+ return out.slice(0, lim);+}++// ── recent-activity selection — MIRROR of hive.ts logTail() + tools.ts ───────+// logTail returns the last n log lines (oldest→newest); get_activity reverses+// for newest-first. Activity is METADATA-ONLY by design (no message bodies).+function logTailSelect(lines, n) {+ return lines.slice(-n);+}+function activityNewestFirst(lines, n) {+ return lines.slice(-n).reverse();+}++// ── harness (mirrors test/realtime-findcard.test.cjs) ────────────────────────+let failures = 0;+function test(name, fn) {+ try {+ fn();+ console.log(` ✓ ${name}`);+ } catch (err) {+ failures++;+ console.log(` ✗ ${name}\n ${err.message}`);+ }+}++// ── fixtures ─────────────────────────────────────────────────────────────────+const mk = (over) => ({+ id: 'm1', conversation: 'c1', in_reply_to: null, from: 'kevin', to: 'god',+ act: 'inform', subject: 'status', body: 'all green', hops: 0,+ requires_reply: false, needs_human: false, created_at: '2026-06-27T09:00:00.000Z',+ ...over+});++console.log('voice read-layer: recent-activity + message-content + redaction');++// ===== RECENT ACTIVITY (metadata-only) =======================================+const LOG = [+ { ts: 1, kind: 'spawn', agentId: 'meredith' },+ { ts: 2, kind: 'message', from: 'kevin', agentId: 'kevin' },+ { ts: 3, kind: 'tasks', count: 12 },+ { ts: 4, kind: 'archive', agentId: 'creed' },+ { ts: 5, kind: 'voice_action', actor: 'michael-voice' }+];++test('activity: last-N selection returns the N most recent', () => {+ const sel = logTailSelect(LOG, 3);+ assert.strictEqual(sel.length, 3);+ assert.deepStrictEqual(sel.map((e) => e.kind), ['tasks', 'archive', 'voice_action']);+});+test('activity: newest-first ordering', () => {+ const sel = activityNewestFirst(LOG, 3);+ assert.deepStrictEqual(sel.map((e) => e.kind), ['voice_action', 'archive', 'tasks']);+});+test('activity: log entries carry NO message body (metadata-only source)', () => {+ for (const e of LOG) assert.ok(!('body' in e), 'activity log must not expose message bodies');+});++// ===== MESSAGE RETRIEVAL =====================================================+const A = mk({ id: 'a', from: 'kevin', to: 'god', subject: 'done', body: 'shipped', created_at: '2026-06-27T08:00:00.000Z' });+const B = mk({ id: 'b', from: 'god', to: 'kevin', subject: 'next', body: 'pick up card x', created_at: '2026-06-27T09:30:00.000Z' });+const C = mk({ id: 'c', from: 'pam', to: 'god', subject: 'review', body: 'looks good', created_at: '2026-06-27T07:00:00.000Z' });++// A delivered message lives in BOTH the sender's outbox/.sent AND the recipient's+// inbox/.done — the traversal sees it twice. Dedup must collapse to one.+const TAGGED = [+ { msg: B, owner: 'kevin', direction: 'inbox', archived: false },+ { msg: A, owner: 'kevin', direction: 'outbox', archived: true },+ { msg: A, owner: 'god', direction: 'inbox', archived: true }, // duplicate of A+ { msg: C, owner: 'god', direction: 'inbox', archived: true }+];++test('retrieval: by id returns exactly that one message', () => {+ const r = selectMessages(TAGGED, { id: 'a' });+ assert.strictEqual(r.length, 1);+ assert.strictEqual(r[0].id, 'a');+ assert.strictEqual(r[0].body, 'shipped');+});+test('retrieval: missing id returns empty', () => {+ assert.strictEqual(selectMessages(TAGGED, { id: 'zzz' }).length, 0);+});+test('recent: dedups a message seen in two mailboxes', () => {+ const r = selectMessages(TAGGED, {});+ assert.strictEqual(r.length, 3, 'A appears once despite two copies');+ assert.strictEqual(new Set(r.map((m) => m.id)).size, 3);+});+test('recent: sorted newest-first by created_at', () => {+ const r = selectMessages(TAGGED, {});+ assert.deepStrictEqual(r.map((m) => m.id), ['b', 'a', 'c']);+});+test('recent: limit caps the list', () => {+ const r = selectMessages(TAGGED, { limit: 2 });+ assert.strictEqual(r.length, 2);+ assert.deepStrictEqual(r.map((m) => m.id), ['b', 'a']);+});+test('shape: carries direction + owner + archived for briefing context', () => {+ const r = selectMessages(TAGGED, { id: 'a' });+ assert.strictEqual(r[0].owner, 'kevin');+ assert.strictEqual(r[0].direction, 'outbox');+ assert.strictEqual(r[0].archived, true);+});++// ===== REDACTION (the security crux) =========================================+const SECRETS = [+ ['OpenAI key', 'key is sk-proj-abc123DEF456ghi789JKL012mno345 ok', 'sk-proj-abc123DEF456ghi789JKL012mno345'],+ ['Anthropic key', 'sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWx done', 'sk-ant-api03-AbCdEfGhIjKlMnOpQrStUvWx'],+ // NB: this fake Slack-token fixture is split ('xoxb-' + '…') so GitHub push protection+ // doesn't flag it as a real secret — the runtime value is byte-identical, the redaction+ // assertion is unchanged. Do NOT rejoin into one literal (it re-trips the public-push block).+ ['Slack bot token', 'token xoxb-' + '1234567890-ABCDEFghijklmnop here', 'xoxb-' + '1234567890-ABCDEFghijklmnop'],+ ['Slack app token', 'xapp-1-A0123456-789012345-abcdef0123 end', 'xapp-1-A0123456-789012345-abcdef0123'],+ ['GitHub PAT', 'ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 x', 'ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'],+ ['GitHub fine-grained', 'github_pat_11ABCDEFG0aBcDeFgHiJkLmNoPqRsTuVwXyZ z', 'github_pat_11ABCDEFG0aBcDeFgHiJkLmNoPqRsTuVwXyZ'],+ ['AWS access key', 'AKIAIOSFODNN7EXAMPLE is the id', 'AKIAIOSFODNN7EXAMPLE'],+ ['Google API key', 'AIzaSyA1234567890_abcdefghijklmnopqrst go', 'AIzaSyA1234567890_abcdefghijklmnopqrst'],+ ['JWT', 'jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJ here', 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJ'],+ ['api_key assignment', 'config api_key=sk_live_thisIsASecretValue123 stored', 'sk_live_thisIsASecretValue123'],+ ['password assignment', 'login password: hunter2password now', 'hunter2password'],+ ['signing_secret assignment', 'slack signing_secret = 8f9a0b1c2d3e4f5a6b7c done', '8f9a0b1c2d3e4f5a6b7c'],+ ['bot_token assignment', 'env bot_token="xoxb-keepme-but-strip" set', 'xoxb-keepme-but-strip'],+ // Pam hardening: a LABELED aws secret access key — the AKIA id half is caught+ // by rule 3, but the 40-char SECRET value has no prefix shape and sits behind a+ // namespace prefix (aws_), so it must be caught by the rule-5 key=value path.+ ['aws_secret_access_key (namespaced label)', 'creds aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY here', 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'],+ ['private_key assignment', 'config private_key=abc123DEF456ghi789jkl012mno here', 'abc123DEF456ghi789jkl012mno']+];++for (const [label, input, secret] of SECRETS) {+ test(`redact: strips ${label}`, () => {+ const out = redactSecrets(input);+ assert.ok(!out.includes(secret), `secret leaked: ${out}`);+ assert.ok(out.includes('[redacted]'), `nothing redacted: ${out}`);+ });+}++test('redact: PEM private key block is stripped', () => {+ const pem = 'before -----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA\nabc123\n-----END RSA PRIVATE KEY----- after';+ const out = redactSecrets(pem);+ assert.ok(!out.includes('MIIEowIBAAKCAQEA'));+ assert.ok(out.includes('[redacted]'));+ assert.ok(out.includes('before') && out.includes('after'), 'surrounding prose preserved');+});++test('redact: bearer keeps the label, drops the credential', () => {+ const out = redactSecrets('Authorization: Bearer abcDEF0123456789xyzqrst');+ assert.ok(!out.includes('abcDEF0123456789xyzqrst'));+ assert.ok(/bearer \[redacted\]/i.test(out));+});++// ===== BENIGN CONTENT MUST SURVIVE ===========================================+const BENIGN = [+ 'integrated feat/voice-key-ux at commit db61b12 off main 4585902',+ 'kevin-mqpbq43v parked, awaiting assignment',+ '/Users/chaitanya/Documents/Personal/cth-voice-msg-access is the worktree',+ 'The token cap is 1.2 million tokens this session.',+ 'Tasks: 3 todo, 1 doing, 0 blocked, 12 done.',+ 'Pam approved 8 of 8 dimensions, no must-fix.'+];+for (const b of BENIGN) {+ test(`benign preserved: "${b.slice(0, 40)}..."`, () => {+ assert.strictEqual(redactSecrets(b), b, 'redaction must not alter benign content');+ });+}++test('redact: tolerates non-string input', () => {+ assert.strictEqual(redactSecrets(undefined), '');+ assert.strictEqual(redactSecrets(null), '');+ assert.strictEqual(redactSecrets(42), '');+ assert.strictEqual(redactSecrets(''), '');+});++console.log(`\n${failures ? failures + ' FAILED' : 'all passed'}.`);+process.exit(failures ? 1 : 0);