@inetafrica/open-claudia 3.2.3 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/actions.js CHANGED
@@ -753,6 +753,86 @@ async function handleAction(envelope) {
753
753
  await send(`Type the rule to apply to ${target}.\nFor example: “may share our office hours and address”, or “never discuss pricing”.\n\nOr send /cancel to skip.`);
754
754
  return;
755
755
  }
756
+ if (d.startsWith("vfy:")) {
757
+ // "Verify contact…" on an approval card for an unverified auto-added
758
+ // speaker. Owner-only (transport-gated on the callback envelope — the one
759
+ // surface the agent can't forge). Offers the same-name candidate notes as
760
+ // buttons; the actual state change happens in the vfl: pick handler via
761
+ // core/verify-contact, which re-validates everything.
762
+ if (!isChatOwner(envelope.channelId)) return send("Owner only — contact verification is restricted.");
763
+ const id = d.split(":")[1];
764
+ const approvals = require("./approvals");
765
+ const rec = approvals.read(id);
766
+ if (!rec || !rec.personId) return send("That request expired — nothing to verify from it.");
767
+ const people = require("./people");
768
+ const person = people.findById(rec.personId);
769
+ if (!person) return send("I no longer have a contact record for them.");
770
+ if (!person.autoCreated) return send(`${person.name} is already verified.`);
771
+ const candidates = require("./verify-contact").candidateEntitiesFor(person).slice(0, 6);
772
+ // Button payloads are INDEX-based: Telegram caps callback_data at 64
773
+ // bytes and slugs alone can be 60 — the picked index resolves against
774
+ // this snapshot, so a changed entity set can't shift what a tap means.
775
+ state.pendingVerify = {
776
+ aprId: rec.id,
777
+ personId: person.id,
778
+ personName: person.name,
779
+ candidates: candidates.map((c) => ({ slug: c.slug, name: c.name })),
780
+ armedAt: Date.now(),
781
+ };
782
+ saveState();
783
+ const rows = candidates.map((c, i) => ([{ text: `🔗 Link to ${c.slug}`.slice(0, 60), callback_data: `vfl:${rec.id}:${i}` }]));
784
+ rows.push([{ text: "✅ Just verify — this is a new contact", callback_data: `vfl:${rec.id}:self` }]);
785
+ rows.push([{ text: "✖️ Cancel", callback_data: `vfl:${rec.id}:x` }]);
786
+ await send(
787
+ `🪪 Verify ${person.name}?\n` +
788
+ (candidates.length
789
+ ? `They share a name with ${candidates.length === 1 ? "an existing note" : `${candidates.length} existing notes`} — link them if this is the same person, or keep them separate.\n`
790
+ : `No existing note matches their name — verifying keeps their current note as canonical.\n`) +
791
+ `Verifying settles WHO they are. It grants no permissions — use “Make a rule” or /guardrails for that.`,
792
+ { keyboard: { inline_keyboard: rows } }
793
+ );
794
+ return;
795
+ }
796
+ if (d.startsWith("vfl:")) {
797
+ // Verification pick. Owner-only; one-shot against the armed snapshot with
798
+ // the same 5-minute TTL as rule authoring. verifyContact() re-validates
799
+ // the person and target at execution time, so a stale snapshot can only
800
+ // refuse — never mislink.
801
+ if (!isChatOwner(envelope.channelId)) return send("Owner only — contact verification is restricted.");
802
+ const parts = d.split(":");
803
+ const id = parts[1];
804
+ const pick = parts[2];
805
+ const pend = state.pendingVerify;
806
+ const VERIFY_TTL_MS = 5 * 60 * 1000;
807
+ if (!pend || pend.aprId !== id || (pend.armedAt && Date.now() - pend.armedAt > VERIFY_TTL_MS)) {
808
+ state.pendingVerify = null; saveState();
809
+ return send("That verify prompt is stale — tap “Verify contact…” on the card again.");
810
+ }
811
+ state.pendingVerify = null; saveState();
812
+ if (pick === "x") return send("Okay — left unverified.");
813
+ let linkSlug = null;
814
+ if (pick !== "self") {
815
+ const chosen = pend.candidates[parseInt(pick, 10)];
816
+ if (!chosen) return send("That button is stale — tap “Verify contact…” on the card again.");
817
+ linkSlug = chosen.slug;
818
+ }
819
+ const result = require("./verify-contact").verifyContact({
820
+ personId: pend.personId,
821
+ linkSlug,
822
+ by: String(envelope.channelId),
823
+ via: "approval-card",
824
+ });
825
+ if (!result.ok) {
826
+ return send(result.already
827
+ ? `${pend.personName} is already verified.`
828
+ : `Couldn't verify: ${result.reason}`);
829
+ }
830
+ return send(
831
+ `🪪 Verified ${pend.personName}` +
832
+ (linkSlug ? ` — linked to ${result.slug}${result.superseded ? ` (auto-stub ${result.superseded} retired)` : ""}.` : ` — their note is now canonical.`) +
833
+ `\nVerification settles identity only; permissions still come from mandates and rules.`
834
+ );
835
+ }
756
836
  if (d.startsWith("grd:")) {
757
837
  // Guardrail capture buttons (Track C). Owner-only: standing rules layer
758
838
  // above lessons and are never editable by an external speaker.
package/core/enforcer.js CHANGED
@@ -360,7 +360,27 @@ async function postOwnerButtons(rec, owner, { kind, summary, reason }) {
360
360
  `<pre>${esc(String(rec.command || ""))}</pre>`,
361
361
  ];
362
362
  }
363
- const lines = [head, ``, ...askBlock, ...body, reason ? `\nWhy I'm checking: ${esc(reason)}` : ``];
363
+ // Unverified auto-added speaker → the card carries a one-tap way for the
364
+ // owner to settle WHO this is (link to an existing note, or bless the stub).
365
+ // Computed live from the people record — after verification the row (and
366
+ // the warning line) disappear from subsequent cards on their own.
367
+ let unverifiedLine = "";
368
+ let verifyRow = null;
369
+ try {
370
+ if (rec.personId) {
371
+ const person = require("./people").findById(rec.personId);
372
+ if (person && person.autoCreated && !person.isOwner) {
373
+ const candidates = require("./verify-contact").candidateEntitiesFor(person);
374
+ unverifiedLine = candidates.length
375
+ ? `⚠️ Unverified auto-added contact. Possible existing note: <b>${esc(candidates[0].slug)}</b> — NOT linked until you verify.`
376
+ : `⚠️ Unverified auto-added contact — I only know them from this chat.`;
377
+ verifyRow = [{ text: "🪪 Verify contact…", callback_data: `vfy:${rec.id}` }];
378
+ }
379
+ }
380
+ } catch (e) { /* card still posts without the verify affordance */ }
381
+ const lines = [head, ``, ...askBlock, ...body,
382
+ unverifiedLine ? `\n${unverifiedLine}` : ``,
383
+ reason ? `\nWhy I'm checking: ${esc(reason)}` : ``];
364
384
  const yes = kind === "triage" ? "✅ Yes, handle it" : "✅ Approve once";
365
385
  const no = kind === "triage" ? "⛔ No, decline" : "⛔ Deny";
366
386
  const keyboard = { inline_keyboard: [
@@ -370,6 +390,7 @@ async function postOwnerButtons(rec, owner, { kind, summary, reason }) {
370
390
  ],
371
391
  [
372
392
  { text: "📝 Make a rule…", callback_data: `apr:${rec.id}:rule` },
393
+ ...(verifyRow || []),
373
394
  ],
374
395
  ] };
375
396
  try {
package/core/handlers.js CHANGED
@@ -2466,7 +2466,7 @@ function formatPersonShort(p) {
2466
2466
  }
2467
2467
 
2468
2468
  register({
2469
- name: "people", description: "Manage team members", args: "[show|note|link|unlink|set-primary|add|remove ...]",
2469
+ name: "people", description: "Manage team members", args: "[show|note|link|unlink|set-primary|add|remove|verify ...]",
2470
2470
  handler: async (env, { tail }) => {
2471
2471
  if (!authorized(env)) return;
2472
2472
  if (!tail || tail === "list") {
@@ -2552,7 +2552,51 @@ register({
2552
2552
  for (const h of handles) { const r = accessStore.revokeChat(h.channelId); if (r.ok) revokedCount += 1; }
2553
2553
  return send(`Removed ${person.name}. Deauthed ${revokedCount} chat${revokedCount === 1 ? "" : "s"}.`);
2554
2554
  }
2555
- send("Usage: /people | /people show <name> | /people note <name> <text> | /people add|link|unlink|set-primary|remove ... (owner)");
2555
+ // Verify an auto-added contact: settle their identity, optionally binding
2556
+ // them to an existing note. Owner-only and chat-surface-only by design —
2557
+ // there is deliberately no CLI/loopback equivalent, so identity decisions
2558
+ // can never ride agent-forgeable input. Grants no permissions.
2559
+ const verifyMatch = tail.match(/^verify\s+(.+?)(?:\s+link\s+(\S+))?$/i);
2560
+ if (verifyMatch) {
2561
+ const person = peopleStore.findById(verifyMatch[1].trim()) || peopleStore.findByName(verifyMatch[1].trim());
2562
+ if (!person) return send(`Not found: ${verifyMatch[1].trim()}`);
2563
+ const vc = require("./verify-contact");
2564
+ if (person.autoCreated && !verifyMatch[2]) {
2565
+ const candidates = vc.candidateEntitiesFor(person);
2566
+ if (candidates.length) {
2567
+ return send(
2568
+ `${person.name} shares a name with ${candidates.length === 1 ? "an existing note" : `${candidates.length} existing notes`}:\n` +
2569
+ candidates.map((c) => ` ${c.slug}`).join("\n") +
2570
+ `\n\nLink with /people verify ${person.name} link <slug>, or /people verify-new ${person.name} to keep them separate.`
2571
+ );
2572
+ }
2573
+ }
2574
+ const result = vc.verifyContact({
2575
+ personId: person.id,
2576
+ linkSlug: verifyMatch[2] || null,
2577
+ by: env.canonicalUserId || String(env.channelId),
2578
+ via: "slash-command",
2579
+ });
2580
+ if (!result.ok) return send(result.already ? `${person.name} is already verified.` : `Couldn't verify: ${result.reason}`);
2581
+ return send(
2582
+ `🪪 Verified ${person.name}` +
2583
+ (verifyMatch[2] ? ` — linked to ${result.slug}${result.superseded ? ` (auto-stub ${result.superseded} retired)` : ""}.` : ` — their note is now canonical.`) +
2584
+ `\nVerification settles identity only; permissions still come from mandates and rules.`
2585
+ );
2586
+ }
2587
+ const verifyNewMatch = tail.match(/^verify-new\s+(.+)$/i);
2588
+ if (verifyNewMatch) {
2589
+ const person = peopleStore.findById(verifyNewMatch[1].trim()) || peopleStore.findByName(verifyNewMatch[1].trim());
2590
+ if (!person) return send(`Not found: ${verifyNewMatch[1].trim()}`);
2591
+ const result = require("./verify-contact").verifyContact({
2592
+ personId: person.id,
2593
+ by: env.canonicalUserId || String(env.channelId),
2594
+ via: "slash-command",
2595
+ });
2596
+ if (!result.ok) return send(result.already ? `${person.name} is already verified.` : `Couldn't verify: ${result.reason}`);
2597
+ return send(`🪪 Verified ${person.name} — their note is now canonical.\nVerification settles identity only; permissions still come from mandates and rules.`);
2598
+ }
2599
+ send("Usage: /people | /people show <name> | /people note <name> <text> | /people add|link|unlink|set-primary|remove|verify ... (owner)");
2556
2600
  },
2557
2601
  });
2558
2602
 
package/core/loopback.js CHANGED
@@ -25,6 +25,7 @@ const introFlow = require("./intro-flow");
25
25
  const relay = require("./relay");
26
26
  const audit = require("./audit");
27
27
  const access = require("./access");
28
+ const speakerAttest = require("./speaker-attest");
28
29
  const fs2 = require("fs");
29
30
  const path2 = require("path");
30
31
  const { TRANSCRIPTS_DIR } = require("./config");
@@ -85,9 +86,17 @@ const JSON_KINDS = new Set([
85
86
  "say", "call", "tts", "transcribe",
86
87
  ]);
87
88
 
89
+ // Owner gate for identity-sensitive kinds. The claimed canonicalUserId comes
90
+ // from the CLI's env, which the agent's shell can rewrite — so the claim only
91
+ // counts when it carries the runner-minted attestation (an HMAC over the id
92
+ // with a per-boot, memory-only secret; see core/speaker-attest). No attest,
93
+ // a wrong attest, or an attest for a different id all fail closed: forging
94
+ // `OC_CANONICAL_USER_ID=<owner-id>` from a guarded external turn no longer
95
+ // reaches the people/auth/intros mutations the relationship guard depends on.
88
96
  function callerIsOwner(payload) {
89
97
  const caller = payload?.canonicalUserId;
90
98
  if (!caller) return false;
99
+ if (!speakerAttest.verify(caller, payload?.speakerAttest)) return false;
91
100
  const person = peopleStore.findByCanonicalUserId(caller);
92
101
  return !!(person && person.isOwner);
93
102
  }
@@ -602,6 +611,24 @@ async function handleJson(req, res, url, kind) {
602
611
 
603
612
  if (kind === "relay-send") {
604
613
  if (!payload.text) return reply(res, 400, { error: "missing text" });
614
+ // A guarded (external) requester may pass a message TO THE OWNER — that is
615
+ // the "tell them for me" flow — but never use the bot as a relay to third
616
+ // parties: sending as the bot to anyone else is impersonation surface.
617
+ try {
618
+ const relationship = require("./relationship");
619
+ const speaker = relationship.speakerFor(adapter.type, channelId, userId);
620
+ if (relationship.guardActive(speaker)) {
621
+ const target =
622
+ (payload.targetPersonId && peopleStore.findById(payload.targetPersonId)) ||
623
+ (payload.targetPersonName && peopleStore.findByName(payload.targetPersonName)) ||
624
+ (payload.targetCanonicalUserId && peopleStore.findByCanonicalUserId(payload.targetCanonicalUserId)) ||
625
+ (payload.targetAdapter && payload.targetChannelId && peopleStore.findByHandle(payload.targetAdapter, payload.targetChannelId)) ||
626
+ null;
627
+ if (!target || !target.isOwner) {
628
+ return reply(res, 403, { error: "relay from an external contact can only go to the owner — messages to anyone else are owner-only" });
629
+ }
630
+ }
631
+ } catch (e) { /* classification failure → fall through; owner-scoped in practice */ }
605
632
  try {
606
633
  const result = await relay.send({
607
634
  text: payload.text,
@@ -620,6 +647,16 @@ async function handleJson(req, res, url, kind) {
620
647
  }
621
648
 
622
649
  if (kind === "recent-fetch") {
650
+ // Transcript reads are owner-side memory. A guarded (external, non-owner)
651
+ // requester must not pull other channels' conversations through the CLI —
652
+ // same default-deny as file/voice egress, same fail direction.
653
+ try {
654
+ const relationship = require("./relationship");
655
+ const speaker = relationship.speakerFor(adapter.type, channelId, userId);
656
+ if (relationship.guardActive(speaker)) {
657
+ return reply(res, 403, { error: "transcript access is owner-only — an external contact cannot read other conversations" });
658
+ }
659
+ } catch (e) { /* classification failure → fall through; owner-scoped in practice */ }
623
660
  const limit = Math.max(1, Math.min(parseInt(payload.limit || 20, 10) || 20, 200));
624
661
  try {
625
662
  let targetAdapter = payload.adapter;
package/core/media.js CHANGED
@@ -99,34 +99,87 @@ async function elevenLabsToVoice(clean) {
99
99
  }
100
100
  }
101
101
 
102
+ // Pack already-cleaned text into gateway-sized pieces. Long inputs used to go
103
+ // to the gateway as ONE request and blow its synthesis window (the abort was
104
+ // the binding limit, not any transport) — sentence-packed chunks keep every
105
+ // request comfortably inside it. Oversized single sentences are hard-split at
106
+ // word boundaries so one run-on sentence can't recreate the timeout.
107
+ const TTS_CHUNK_MAX = 450;
108
+ function chunkForTTS(clean, maxLen = TTS_CHUNK_MAX) {
109
+ if (clean.length <= maxLen) return [clean];
110
+ const sentences = clean.match(/[^.!?]+[.!?]+|\S[^.!?]*$/g) || [clean];
111
+ const chunks = [];
112
+ let buf = "";
113
+ const flush = () => { if (buf) { chunks.push(buf); buf = ""; } };
114
+ for (let piece of sentences) {
115
+ piece = piece.trim();
116
+ if (!piece) continue;
117
+ while (piece.length > maxLen) {
118
+ flush();
119
+ let cut = piece.lastIndexOf(" ", maxLen);
120
+ if (cut < maxLen / 2) cut = maxLen;
121
+ chunks.push(piece.slice(0, cut).trim());
122
+ piece = piece.slice(cut).trim();
123
+ }
124
+ if (buf && buf.length + piece.length + 1 > maxLen) flush();
125
+ buf = buf ? `${buf} ${piece}` : piece;
126
+ }
127
+ flush();
128
+ return chunks.filter(Boolean);
129
+ }
130
+
131
+ async function pocketFetchWav(input, voice, token) {
132
+ const res = await fetch(`${SPEECH_SERVICE_URL.replace(/\/$/, "")}/v1/audio/speech`, {
133
+ method: "POST",
134
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
135
+ body: JSON.stringify({ input, voice, response_format: "wav" }),
136
+ signal: AbortSignal.timeout(120000),
137
+ });
138
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
139
+ return Buffer.from(await res.arrayBuffer());
140
+ }
141
+
102
142
  // Pocket TTS through the Agent Space speech gateway. The gateway returns WAV;
103
- // Telegram and voice transports receive a compact Ogg/Opus file.
143
+ // Telegram and voice transports receive a compact Ogg/Opus file. Long text is
144
+ // synthesized chunk-by-chunk and concatenated, so message length can no longer
145
+ // abort the request mid-synthesis.
104
146
  async function pocketToVoice(clean, voiceOverride) {
105
147
  const token = speechBearerToken();
106
148
  if (TTS_PROVIDER === "elevenlabs" || !token || !SPEECH_SERVICE_URL || !FFMPEG) return null;
107
- let wavPath = null;
149
+ const voice = voiceOverride || ttsVoice.getVoice();
150
+ const stem = `tts-pocket-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
151
+ const oggPath = path.join(TEMP_DIR, `${stem}.ogg`);
152
+ const wavPaths = [];
153
+ let listPath = null;
108
154
  try {
109
- const res = await fetch(`${SPEECH_SERVICE_URL.replace(/\/$/, "")}/v1/audio/speech`, {
110
- method: "POST",
111
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
112
- body: JSON.stringify({ input: clean, voice: voiceOverride || ttsVoice.getVoice(), response_format: "wav" }),
113
- signal: AbortSignal.timeout(60000),
114
- });
115
- if (!res.ok) {
116
- console.error(`Pocket TTS failed: HTTP ${res.status}`);
117
- return null;
155
+ const chunks = chunkForTTS(clean);
156
+ for (let i = 0; i < chunks.length; i++) {
157
+ let buf;
158
+ try {
159
+ buf = await pocketFetchWav(chunks[i], voice, token);
160
+ } catch (e) {
161
+ // one retry: a transient gateway blip shouldn't waste the chunks
162
+ // already synthesized before it
163
+ buf = await pocketFetchWav(chunks[i], voice, token);
164
+ }
165
+ const wavPath = path.join(TEMP_DIR, `${stem}-${i}.wav`);
166
+ fs.writeFileSync(wavPath, buf);
167
+ wavPaths.push(wavPath);
168
+ }
169
+ if (wavPaths.length === 1) {
170
+ execSync(`"${FFMPEG}" -i "${wavPaths[0]}" -c:a libopus -y "${oggPath}" 2>/dev/null`, { timeout: 30000 });
171
+ } else {
172
+ listPath = path.join(TEMP_DIR, `${stem}-list.txt`);
173
+ fs.writeFileSync(listPath, wavPaths.map((p) => `file '${p}'`).join("\n"));
174
+ execSync(`"${FFMPEG}" -f concat -safe 0 -i "${listPath}" -c:a libopus -y "${oggPath}" 2>/dev/null`, { timeout: 120000 });
118
175
  }
119
- const stem = `tts-pocket-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
120
- wavPath = path.join(TEMP_DIR, `${stem}.wav`);
121
- const oggPath = path.join(TEMP_DIR, `${stem}.ogg`);
122
- fs.writeFileSync(wavPath, Buffer.from(await res.arrayBuffer()));
123
- execSync(`"${FFMPEG}" -i "${wavPath}" -c:a libopus -y "${oggPath}" 2>/dev/null`, { timeout: 30000 });
124
176
  return oggPath;
125
177
  } catch (e) {
126
178
  console.error("Pocket TTS error:", e.message);
127
179
  return null;
128
180
  } finally {
129
- if (wavPath) { try { fs.unlinkSync(wavPath); } catch (e) {} }
181
+ for (const p of wavPaths) { try { fs.unlinkSync(p); } catch (e) {} }
182
+ if (listPath) { try { fs.unlinkSync(listPath); } catch (e) {} }
130
183
  }
131
184
  }
132
185
 
@@ -303,4 +356,4 @@ async function synthSentenceMp3(text) {
303
356
  }
304
357
  }
305
358
 
306
- module.exports = { transcribeAudio, transcribeAudioLocal, transcribeMedia, canTranscribe, textToVoice, textToVoiceFile, splitSentences, synthSentenceMp3, pocketToVoice, cloneVoiceFromClip, speechBearerToken, canSpeak, TTS_CMD };
359
+ module.exports = { transcribeAudio, transcribeAudioLocal, transcribeMedia, canTranscribe, textToVoice, textToVoiceFile, splitSentences, synthSentenceMp3, pocketToVoice, chunkForTTS, cloneVoiceFromClip, speechBearerToken, canSpeak, TTS_CMD };
@@ -388,7 +388,25 @@ function applyAction(a, activeSet = null) {
388
388
 
389
389
  function applyEntityAction(e) {
390
390
  if (!e || typeof e !== "object" || !String(e.name || "").trim()) return null;
391
+ // Slug-key through the people roster: name-keyed upserts land on the
392
+ // alphabetically-first same-named entity, but the relationship guard reads
393
+ // the file the person RECORD points at (auto-added contacts get a suffixed
394
+ // stub precisely so they can't shadow an existing note). A unique name
395
+ // match routes the write to the guard-read file; an ambiguous one (two
396
+ // tracked people sharing a name) is skipped outright — enriching the wrong
397
+ // identity's note is worse than writing nothing.
398
+ let slug = "";
399
+ try {
400
+ const people = require("./people");
401
+ const wanted = String(e.name || "").trim().toLowerCase();
402
+ const matches = people.list().filter((p) => (p.name || "").trim().toLowerCase() === wanted);
403
+ if (matches.length === 1) slug = people.resolveEntitySlug(matches[0]) || "";
404
+ else if (matches.length > 1) {
405
+ return { kind: "skip", slug: "", name: e.name, type: e.type || "", note: "ambiguous: multiple tracked people share this name — not writing to either note" };
406
+ }
407
+ } catch (err) { /* roster unavailable → name-keyed fallback below */ }
391
408
  const { entity, created } = entities.upsertEntity({
409
+ slug: slug || undefined,
392
410
  name: e.name,
393
411
  type: e.type,
394
412
  aliases: Array.isArray(e.aliases) ? e.aliases.slice(0, 5) : [],
@@ -253,10 +253,26 @@ function ensureContact(envelope) {
253
253
  const suffix = crypto.createHash("sha1").update(`${adapterType}:${userId}`).digest("hex").slice(0, 6);
254
254
  const slug = `${entities.slugify(displayName).slice(0, 48) || "contact"}-${suffix}`;
255
255
  people.setEntitySlug(person.id, slug);
256
+
257
+ // If a same-named person note already exists, surface it as a HINT only.
258
+ // Deliberately not linked (see invariants above): a name is spoofable, so
259
+ // absorbing the note here would hand the speaker that identity's history.
260
+ // Only the owner can link, via the approval card or /people verify.
261
+ let hint = "";
262
+ try {
263
+ const fresh = people.findById(person.id) || person;
264
+ const candidates = require("./verify-contact").candidateEntitiesFor(fresh);
265
+ if (candidates.length) hint = candidates.map((c) => c.slug).slice(0, 3).join(", ");
266
+ } catch (e) { /* hint is best-effort — the stub is safe without it */ }
267
+
256
268
  entities.upsertEntity({
257
269
  slug, name: displayName, type: "person", relationship: "external",
258
- description: `Auto-added contact (unverified) — first seen in ${label}`,
259
- log: `auto-added as a contact from ${label}`,
270
+ description: hint
271
+ ? `Auto-added contact (unverified) — first seen in ${label}. Possible existing note: ${hint} — NOT linked; only the owner can verify.`
272
+ : `Auto-added contact (unverified) — first seen in ${label}`,
273
+ log: hint
274
+ ? `auto-added as a contact from ${label}; same-named note detected (${hint}) — not linked pending owner verification`
275
+ : `auto-added as a contact from ${label}`,
260
276
  });
261
277
 
262
278
  try { require("./audit").log("auto-contact", { personId: person.id, name: displayName, adapter: adapterType, userId, channelId, entitySlug: slug }); } catch (e) {}
package/core/runner.js CHANGED
@@ -1707,7 +1707,13 @@ function decorateForegroundInvocation(invocation, runContext, bundle) {
1707
1707
  if (runContext.origin?.adapterId) env.OC_CHANNEL_ADAPTER = runContext.origin.adapterId;
1708
1708
  if (runContext.channelId) env.OC_CHANNEL_ID = String(runContext.channelId);
1709
1709
  if (runContext.origin?.userId) env.OC_CHANNEL_USER_ID = String(runContext.origin.userId);
1710
- if (runContext.canonicalUserId) env.OC_CANONICAL_USER_ID = String(runContext.canonicalUserId);
1710
+ if (runContext.canonicalUserId) {
1711
+ env.OC_CANONICAL_USER_ID = String(runContext.canonicalUserId);
1712
+ // Server-side attestation of the id above: the loopback's owner-gated
1713
+ // kinds only honor a canonicalUserId whose attest verifies, so a shell
1714
+ // that rewrites OC_CANONICAL_USER_ID cannot impersonate the owner.
1715
+ try { env.OC_SPEAKER_ATTEST = require("./speaker-attest").mint(runContext.canonicalUserId); } catch (e) {}
1716
+ }
1711
1717
  if (runContext.sessionId) env.OC_LAST_SESSION_ID = String(runContext.sessionId);
1712
1718
  if (lb?.url) env.OC_SEND_URL = lb.url;
1713
1719
  }
@@ -0,0 +1,56 @@
1
+ // Speaker attestation: lets the loopback server trust OC_CANONICAL_USER_ID.
2
+ //
3
+ // The problem: the loopback's owner-gated kinds (people mutations, auth,
4
+ // intros) identified the caller by payload.canonicalUserId, which the CLI read
5
+ // from env — and env is writable by the agent's shell, so a guarded external
6
+ // turn could forge `OC_CANONICAL_USER_ID=<owner-id> open-claudia people link …`
7
+ // and rewrite the identity map the relationship guard depends on.
8
+ //
9
+ // The fix: the RUNNER (which knows the turn's true speaker from the inbound
10
+ // envelope, server-side) mints an HMAC over the canonical user id with a
11
+ // per-boot secret that lives ONLY in bot-process memory — never on disk, never
12
+ // in the loopback info file, stripped from provider env like all control-plane
13
+ // keys would be (it is simply never exported). The provider spawn env carries
14
+ // OC_SPEAKER_ATTEST next to OC_CANONICAL_USER_ID; the CLI forwards both; the
15
+ // loopback verifies the pair before honoring an owner claim. An agent can
16
+ // still LIE about OC_CANONICAL_USER_ID, but it cannot mint a matching
17
+ // signature for any id other than the one the runner stamped for its turn.
18
+ //
19
+ // Scope and honesty: this authenticates "the runner said this turn speaks as
20
+ // X". It is per-boot (a restart invalidates in-flight attests — same blast
21
+ // radius as the loopback port/token rotating) and deliberately unforgeable
22
+ // rather than merely obscure: no attest, wrong attest, or an attest for a
23
+ // different id all fail closed. It does NOT bind adapter/channel — those stay
24
+ // best-effort inputs to the guarded-speaker checks, whose spoof failure modes
25
+ // are self-limiting (buttons/files land on the spoofed channel, i.e. the
26
+ // owner's own chat, never silently on the attacker's).
27
+
28
+ const crypto = require("crypto");
29
+
30
+ // Lazily created so tests get a fresh secret per process, like production.
31
+ let SECRET = null;
32
+
33
+ function secret() {
34
+ if (!SECRET) SECRET = crypto.randomBytes(32);
35
+ return SECRET;
36
+ }
37
+
38
+ function mint(canonicalUserId) {
39
+ const id = String(canonicalUserId || "");
40
+ if (!id) return "";
41
+ return crypto.createHmac("sha256", secret()).update(id).digest("hex");
42
+ }
43
+
44
+ // Constant-time compare; every malformed shape is a plain false (fail closed).
45
+ function verify(canonicalUserId, attest) {
46
+ const id = String(canonicalUserId || "");
47
+ const sig = String(attest || "");
48
+ if (!id || !sig) return false;
49
+ const expected = mint(id);
50
+ const a = Buffer.from(sig, "utf-8");
51
+ const b = Buffer.from(expected, "utf-8");
52
+ if (a.length !== b.length) return false;
53
+ try { return crypto.timingSafeEqual(a, b); } catch (e) { return false; }
54
+ }
55
+
56
+ module.exports = { mint, verify };
@@ -865,20 +865,29 @@ function buildSpeakerPersonaBlock(opts = {}) {
865
865
  if (!speaker.isOwner && (s.Mandate || "").trim()) {
866
866
  rows.push(`Mandate — what you may do/discuss with them: ${s.Mandate.trim()}`);
867
867
  }
868
- if (rows.length === 0) return "";
868
+ // A bare note used to render nothing — which hid the guard's policy source
869
+ // exactly when it mattered most (auto-added stubs are born bare, so the
870
+ // agent couldn't see WHICH file governs the speaker, or that a same-named
871
+ // note elsewhere is a different identity). For non-owners the block always
872
+ // renders; an owner with an empty note still gets the quiet no-op.
873
+ if (rows.length === 0 && speaker.isOwner) return "";
869
874
  const runIdentity = promptDedupeIdentity(opts);
870
875
  const key = `${adapter.id || "?"}:${channelId}`;
871
876
  const stamp = `${runIdentity}:${slug}:${ent.updated}`;
872
877
  if (speakerPersonaInjectedFor.get(key) === stamp) return "";
873
878
  speakerPersonaInjectedFor.set(key, stamp);
874
879
  const rel = ent.relationship || (speaker.isOwner ? "owner" : "");
880
+ const unverified = !speaker.isOwner && !!speaker.autoCreated;
875
881
  const clip = (str) => (str.length > SPEAKER_PERSONA_MAX_CHARS ? str.slice(0, SPEAKER_PERSONA_MAX_CHARS) + "\n…[truncated — `open-claudia entity show " + slug + "`]" : str);
876
882
  return clip([
877
- `\n\n## Who you're speaking with: ${speaker.name}${rel ? ` (${rel})` : ""}`,
883
+ `\n\n## Who you're speaking with: ${speaker.name}${rel ? ` (${rel})` : ""}${unverified ? " — UNVERIFIED auto-added contact" : ""}`,
878
884
  `Their persona pack (source: ${entitiesLib.ENTITIES_DIR}/${slug}.md) — adapt your voice and scope to it. Edit that file to refine how you treat them.`,
885
+ ...(speaker.isOwner ? [] : [
886
+ `That file is the ONLY note the relationship guard reads for them — a same-named note anywhere else belongs to a DIFFERENT identity and grants nothing here.${unverified ? " The owner has not yet confirmed who they are (verification happens on the owner's approval card or /people verify)." : ""}`,
887
+ ]),
879
888
  "",
880
889
  rows.join("\n"),
881
- ].join("\n"));
890
+ ].join("\n")).trimEnd();
882
891
  }
883
892
 
884
893
  // External-mode posture block (Phase 3). For a non-owner (guarded) speaker,
@@ -896,9 +905,17 @@ function buildExternalModeBlock() {
896
905
  const who = speaker.name || "this person";
897
906
  const mandate = (speaker.mandate || "").trim();
898
907
  const unverified = !!(speaker.person && speaker.person.autoCreated);
908
+ let sourceLine = "";
909
+ if (speaker.slug) {
910
+ try {
911
+ const entitiesLib = require("./entities");
912
+ sourceLine = `Guard policy source: ${entitiesLib.ENTITIES_DIR}/${speaker.slug}.md — the ONLY note the guard reads for ${who}. A same-named note elsewhere is a different identity and grants nothing here.`;
913
+ } catch (e) {}
914
+ }
899
915
  const lines = [
900
916
  `\n\n## External speaker — restricted mode`,
901
- `You are talking to ${who}, who is NOT the owner. You are operating under a strict, owner-defined scope.`,
917
+ `You are talking to ${who}, who is NOT the owner. You are operating under a strict, owner-defined scope.${unverified ? ` Their identity is UNVERIFIED (auto-added on first contact — only the owner can verify them, via the approval card or /people verify).` : ""}`,
918
+ ...(sourceLine ? [sourceLine] : []),
902
919
  "",
903
920
  mandate
904
921
  ? `Mandate — the ONLY things you are cleared to do or discuss with ${who}:\n${mandate}`