@vellumai/assistant 0.10.11-dev.202607221913.60a3564 → 0.10.11-dev.202607222029.495c516

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.
Files changed (83) hide show
  1. package/node_modules/@vellumai/gateway-client/src/__tests__/binding-strength-contract.test.ts +122 -0
  2. package/node_modules/@vellumai/gateway-client/src/binding-strength-contract.ts +155 -0
  3. package/node_modules/@vellumai/gateway-client/src/index.ts +14 -0
  4. package/node_modules/@vellumai/slack-text/src/index.test.ts +71 -0
  5. package/node_modules/@vellumai/slack-text/src/index.ts +67 -20
  6. package/package.json +1 -1
  7. package/src/__tests__/btw-routes.test.ts +13 -2
  8. package/src/__tests__/conversation-fork-crud.test.ts +28 -22
  9. package/src/__tests__/conversation-fork-retrospective.test.ts +13 -10
  10. package/src/__tests__/conversation-store-ephemeral.test.ts +182 -0
  11. package/src/__tests__/conversation-store.test.ts +4 -0
  12. package/src/__tests__/prune-old-conversations-job.test.ts +5 -0
  13. package/src/__tests__/ui-choice-copy-surfaces.test.ts +144 -3
  14. package/src/api/events/service-group-update-complete.ts +29 -0
  15. package/src/api/events/service-group-update-progress.ts +23 -0
  16. package/src/api/events/service-group-update-starting.ts +26 -0
  17. package/src/api/index.ts +77 -0
  18. package/src/api/surfaces.ts +484 -3
  19. package/src/daemon/conversation-store.ts +14 -2
  20. package/src/daemon/conversation-surfaces.ts +78 -168
  21. package/src/daemon/handlers/shared.ts +11 -1
  22. package/src/daemon/message-types/surfaces.ts +65 -244
  23. package/src/daemon/message-types/upgrades.ts +11 -28
  24. package/src/hooks/types.ts +12 -0
  25. package/src/messaging/channel-binding-schema.ts +6 -2
  26. package/src/messaging/providers/slack/deep-link.ts +45 -8
  27. package/src/messaging/providers/slack/message-metadata.ts +16 -0
  28. package/src/notifications/access-request-copy.ts +10 -21
  29. package/src/persistence/conversation-crud.ts +9 -0
  30. package/src/persistence/job-handlers/cleanup.ts +14 -2
  31. package/src/persistence/migrations/343-move-activation-state-to-memory-db.ts +74 -0
  32. package/src/persistence/migrations/344-move-conversation-graph-memory-state-to-memory-db.ts +66 -0
  33. package/src/persistence/migrations/345-move-memory-v3-ever-injected-to-memory-db.ts +62 -0
  34. package/src/persistence/migrations/346-move-memory-retrospective-state-to-memory-db.ts +67 -0
  35. package/src/persistence/migrations/347-delete-stray-greeting-conversation.ts +46 -0
  36. package/src/persistence/migrations/__tests__/347-delete-stray-greeting-conversation.test.ts +100 -0
  37. package/src/persistence/schema/conversations.ts +7 -3
  38. package/src/persistence/schema/memory-core.ts +3 -0
  39. package/src/persistence/schema/memory-graph.ts +3 -0
  40. package/src/persistence/schema/memory-injection.ts +3 -1
  41. package/src/persistence/steps.ts +42 -0
  42. package/src/plugin-api/constants.ts +2 -0
  43. package/src/plugin-api/index.ts +1 -0
  44. package/src/plugin-api/types.ts +2 -0
  45. package/src/plugins/defaults/index.ts +2 -0
  46. package/src/plugins/defaults/memory/__tests__/conversation-memory-orphan-sweep.test.ts +91 -0
  47. package/src/plugins/defaults/memory/__tests__/conversation-memory-purge.test.ts +123 -0
  48. package/src/plugins/defaults/memory/__tests__/db-memory-attach.test.ts +8 -3
  49. package/src/plugins/defaults/memory/__tests__/memory-log-stores-degraded.test.ts +19 -39
  50. package/src/plugins/defaults/memory/__tests__/memory-retrospective-state.test.ts +55 -40
  51. package/src/plugins/defaults/memory/__tests__/memory-retrospective-trigger-check.test.ts +6 -2
  52. package/src/plugins/defaults/memory/__tests__/relocated-memory-test-rows.ts +103 -0
  53. package/src/plugins/defaults/memory/__tests__/table-relocation.test.ts +285 -0
  54. package/src/plugins/defaults/memory/conversation-memory-orphan-sweep.ts +130 -0
  55. package/src/plugins/defaults/memory/conversation-memory-purge.ts +76 -0
  56. package/src/plugins/defaults/memory/fork-conversation-memory.ts +12 -10
  57. package/src/plugins/defaults/memory/graph/__tests__/conversation-graph-memory-v2-routing.test.ts +29 -8
  58. package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +2 -4
  59. package/src/plugins/defaults/memory/graph/graph-memory-state-store.ts +13 -8
  60. package/src/plugins/defaults/memory/hooks/conversation-deleted.ts +18 -9
  61. package/src/plugins/defaults/memory/hooks/conversations-cleared.ts +25 -0
  62. package/src/plugins/defaults/memory/jobs-worker.ts +13 -0
  63. package/src/plugins/defaults/memory/memory-db.ts +18 -1
  64. package/src/plugins/defaults/memory/memory-retrospective-state.ts +93 -50
  65. package/src/plugins/defaults/memory/v2/__tests__/activation-store.test.ts +88 -20
  66. package/src/plugins/defaults/memory/v2/__tests__/backfill-jobs.test.ts +7 -6
  67. package/src/plugins/defaults/memory/v2/__tests__/injection.test.ts +28 -90
  68. package/src/plugins/defaults/memory/v2/activation-store.ts +47 -26
  69. package/src/plugins/defaults/memory/v2/backfill-jobs.ts +2 -3
  70. package/src/plugins/defaults/memory/v2/injection.ts +2 -15
  71. package/src/plugins/defaults/memory/v3/__tests__/carry-integration.test.ts +10 -6
  72. package/src/plugins/defaults/memory/v3/__tests__/injection.test.ts +6 -2
  73. package/src/plugins/defaults/memory/v3/__tests__/live-integration.test.ts +15 -2
  74. package/src/plugins/defaults/memory/v3/__tests__/shadow-plugin.test.ts +8 -6
  75. package/src/plugins/defaults/memory/v3/ever-injected-store.test.ts +74 -24
  76. package/src/plugins/defaults/memory/v3/ever-injected-store.ts +214 -115
  77. package/src/plugins/defaults/memory/v3/prune.test.ts +4 -2
  78. package/src/runtime/introduction-policy.ts +23 -54
  79. package/src/runtime/routes/btw-routes.ts +9 -2
  80. package/src/runtime/routes/inbound-message-handler.ts +1 -13
  81. package/src/runtime/routes/upgrade-broadcast-routes.ts +6 -8
  82. package/src/tools/ui-surface/definitions.ts +20 -16
  83. package/src/tools/ui-surface/surface-shape-docs.ts +21 -6
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Tests for the shared binding-strength vocabulary: the display ladder and the
3
+ * enforcement order (demotion guard — LUM-2505).
4
+ */
5
+
6
+ import { describe, expect, test } from "bun:test";
7
+
8
+ import {
9
+ bindingStrengthForVerifiedVia,
10
+ isBindingDemotion,
11
+ knownStrengthRank,
12
+ VERIFIED_VIA_CHALLENGE,
13
+ VERIFIED_VIA_CHANNEL_CLAIM,
14
+ VERIFIED_VIA_MANUAL,
15
+ } from "../binding-strength-contract.js";
16
+
17
+ describe("knownStrengthRank", () => {
18
+ test("unverified (null / undefined / empty) ranks 0", () => {
19
+ expect(knownStrengthRank(null)).toBe(0);
20
+ expect(knownStrengthRank(undefined)).toBe(0);
21
+ expect(knownStrengthRank("")).toBe(0);
22
+ });
23
+
24
+ test("inbound channel claim ranks 1", () => {
25
+ expect(knownStrengthRank(VERIFIED_VIA_CHANNEL_CLAIM)).toBe(1);
26
+ });
27
+
28
+ test("workspace-vouched (manual) ranks 2", () => {
29
+ expect(knownStrengthRank(VERIFIED_VIA_MANUAL)).toBe(2);
30
+ });
31
+
32
+ test("proven / possession values all rank 3", () => {
33
+ expect(knownStrengthRank(VERIFIED_VIA_CHALLENGE)).toBe(3);
34
+ expect(knownStrengthRank("invite")).toBe(3);
35
+ expect(knownStrengthRank("voice")).toBe(3);
36
+ expect(knownStrengthRank("bootstrap")).toBe(3);
37
+ // Guardian auto-registration bindings (createGuardianBinding writers).
38
+ expect(knownStrengthRank("platform_auto_register")).toBe(3);
39
+ expect(knownStrengthRank("webhook_registration")).toBe(3);
40
+ });
41
+
42
+ test("unrecognized non-empty provenance is unknown (null)", () => {
43
+ expect(knownStrengthRank("guardian_approval")).toBeNull();
44
+ expect(knownStrengthRank("something_new")).toBeNull();
45
+ });
46
+ });
47
+
48
+ describe("bindingStrengthForVerifiedVia (display ladder)", () => {
49
+ test("maps the three introduction-card provenances", () => {
50
+ expect(bindingStrengthForVerifiedVia(VERIFIED_VIA_CHALLENGE)).toBe(
51
+ "verified_handshake",
52
+ );
53
+ expect(bindingStrengthForVerifiedVia(VERIFIED_VIA_MANUAL)).toBe(
54
+ "internal_workspace_match",
55
+ );
56
+ expect(bindingStrengthForVerifiedVia(VERIFIED_VIA_CHANNEL_CLAIM)).toBe(
57
+ "inbound_channel_claim",
58
+ );
59
+ });
60
+
61
+ test("returns null for provenance outside the ladder (card UI relies on this)", () => {
62
+ expect(bindingStrengthForVerifiedVia("invite")).toBeNull();
63
+ expect(bindingStrengthForVerifiedVia("bootstrap")).toBeNull();
64
+ expect(bindingStrengthForVerifiedVia("voice")).toBeNull();
65
+ expect(bindingStrengthForVerifiedVia(null)).toBeNull();
66
+ expect(bindingStrengthForVerifiedVia(undefined)).toBeNull();
67
+ });
68
+ });
69
+
70
+ describe("isBindingDemotion", () => {
71
+ test("a lower-strength source demoting a higher-strength binding is refused", () => {
72
+ // challenge (3) is the strongest — nothing weaker may overwrite it.
73
+ expect(isBindingDemotion(VERIFIED_VIA_CHALLENGE, VERIFIED_VIA_MANUAL)).toBe(
74
+ true,
75
+ );
76
+ expect(
77
+ isBindingDemotion(VERIFIED_VIA_CHALLENGE, VERIFIED_VIA_CHANNEL_CLAIM),
78
+ ).toBe(true);
79
+ // manual (2) may not be demoted to an inbound claim (1).
80
+ expect(
81
+ isBindingDemotion(VERIFIED_VIA_MANUAL, VERIFIED_VIA_CHANNEL_CLAIM),
82
+ ).toBe(true);
83
+ // A proven value demoted to null/unverified is a demotion too.
84
+ expect(isBindingDemotion(VERIFIED_VIA_CHALLENGE, null)).toBe(true);
85
+ // Guardian auto-registration bindings are proven — a later manual attest
86
+ // or channel claim can never demote them.
87
+ expect(
88
+ isBindingDemotion("platform_auto_register", VERIFIED_VIA_MANUAL),
89
+ ).toBe(true);
90
+ expect(
91
+ isBindingDemotion("webhook_registration", VERIFIED_VIA_CHANNEL_CLAIM),
92
+ ).toBe(true);
93
+ });
94
+
95
+ test("equal-tier writes and lateral proven swaps are not demotions", () => {
96
+ expect(isBindingDemotion(VERIFIED_VIA_CHALLENGE, "invite")).toBe(false);
97
+ expect(isBindingDemotion("invite", VERIFIED_VIA_CHALLENGE)).toBe(false);
98
+ expect(isBindingDemotion(VERIFIED_VIA_MANUAL, VERIFIED_VIA_MANUAL)).toBe(
99
+ false,
100
+ );
101
+ });
102
+
103
+ test("upgrades are not demotions", () => {
104
+ expect(
105
+ isBindingDemotion(VERIFIED_VIA_CHANNEL_CLAIM, VERIFIED_VIA_CHALLENGE),
106
+ ).toBe(false);
107
+ expect(isBindingDemotion(null, VERIFIED_VIA_CHANNEL_CLAIM)).toBe(false);
108
+ expect(isBindingDemotion(VERIFIED_VIA_MANUAL, VERIFIED_VIA_CHALLENGE)).toBe(
109
+ false,
110
+ );
111
+ });
112
+
113
+ test("unknown provenance on either side is never a demotion (fail-open)", () => {
114
+ expect(isBindingDemotion(VERIFIED_VIA_CHALLENGE, "guardian_approval")).toBe(
115
+ false,
116
+ );
117
+ expect(
118
+ isBindingDemotion("guardian_approval", VERIFIED_VIA_CHANNEL_CLAIM),
119
+ ).toBe(false);
120
+ expect(isBindingDemotion("unknown_a", "unknown_b")).toBe(false);
121
+ });
122
+ });
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Shared binding-strength vocabulary for the contact channel `verified_via`
3
+ * provenance column.
4
+ *
5
+ * Two distinct notions live here, both keyed on the free-text `verified_via`
6
+ * audit value:
7
+ *
8
+ * 1. The 3-tier *display* ladder (`BindingStrength` +
9
+ * `bindingStrengthForVerifiedVia`) the introduction card renders from. It
10
+ * covers only the three introduction-card provenances and returns `null`
11
+ * for everything else — the card UI depends on that exact shape.
12
+ *
13
+ * 2. The *enforcement* order (`knownStrengthRank` + `isBindingDemotion`) the
14
+ * gateway ACL write path uses to refuse demotions (LUM-2505): a total,
15
+ * conservative ranking over every real `verified_via` value, so a
16
+ * lower-strength source can never silently overwrite a higher-strength
17
+ * active binding.
18
+ *
19
+ * This lives in the shared package — not `assistant/` — because the gateway
20
+ * owns the contact ACL and is where the demotion guard runs. The assistant
21
+ * re-exports the display helpers from `runtime/introduction-policy.ts`, so its
22
+ * card/provenance call sites are unchanged.
23
+ *
24
+ * No import from `assistant/` or `gateway/`: pure vocabulary.
25
+ */
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // verified_via constants
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /** `verified_via` written by the gateway when a verification code is redeemed. */
32
+ export const VERIFIED_VIA_CHALLENGE = "challenge";
33
+
34
+ /** `verified_via` written when the guardian direct-trusts a workspace-vouched identity. */
35
+ export const VERIFIED_VIA_MANUAL = "manual";
36
+
37
+ /** `verified_via` written when the guardian trusts an identity the platform is not vouching for. */
38
+ export const VERIFIED_VIA_CHANNEL_CLAIM = "manual_channel_claim";
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Display ladder (introduction card)
42
+ // ---------------------------------------------------------------------------
43
+
44
+ /**
45
+ * Binding-strength ladder the introduction card renders:
46
+ *
47
+ * verified_handshake > internal_workspace_match > inbound_channel_claim
48
+ *
49
+ * - `verified_handshake` — the contact proved control of the channel by
50
+ * returning a verification code (`verified_via: "challenge"`).
51
+ * - `internal_workspace_match` — the platform authenticated the identity inside
52
+ * the guardian's own workspace; the guardian vouches directly
53
+ * (`verified_via: "manual"`).
54
+ * - `inbound_channel_claim` — the guardian trusts an identity the platform is
55
+ * NOT vouching for (`verified_via: "manual_channel_claim"`).
56
+ */
57
+ export type BindingStrength =
58
+ | "verified_handshake"
59
+ | "internal_workspace_match"
60
+ | "inbound_channel_claim";
61
+
62
+ /**
63
+ * Derive the display binding strength for a `verified_via`. Returns `null` for
64
+ * provenance outside the introduction ladder (e.g. `invite`, `bootstrap`),
65
+ * which predate it and keep their own audit meaning — the introduction card UI
66
+ * relies on this exact shape.
67
+ *
68
+ * This is the DISPLAY ladder, not the enforcement order: use
69
+ * {@link knownStrengthRank} / {@link isBindingDemotion} for the demotion guard.
70
+ */
71
+ export function bindingStrengthForVerifiedVia(
72
+ verifiedVia: string | null | undefined,
73
+ ): BindingStrength | null {
74
+ switch (verifiedVia) {
75
+ case VERIFIED_VIA_CHALLENGE:
76
+ return "verified_handshake";
77
+ case VERIFIED_VIA_MANUAL:
78
+ return "internal_workspace_match";
79
+ case VERIFIED_VIA_CHANNEL_CLAIM:
80
+ return "inbound_channel_claim";
81
+ default:
82
+ return null;
83
+ }
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Enforcement order (demotion guard — LUM-2505)
88
+ // ---------------------------------------------------------------------------
89
+
90
+ /**
91
+ * `verified_via` values where the actor demonstrably controls the channel (a
92
+ * code/token/possession proof) or the binding is a guardian binding (bootstrap
93
+ * or platform/webhook auto-registration). They share the top enforcement rank:
94
+ * none may be silently demoted, and a lateral swap between them is not a
95
+ * demotion. Every real production writer of `verified_via` that outranks
96
+ * `manual` must appear here, or the demotion guard would treat it as unknown
97
+ * (incomparable) and let a `manual` re-attest quietly demote it.
98
+ */
99
+ const PROVEN_VERIFIED_VIA: ReadonlySet<string> = new Set([
100
+ VERIFIED_VIA_CHALLENGE, // returned a verification code
101
+ "invite", // redeemed an invite code / token
102
+ "voice", // returned a voice (DTMF) code
103
+ "bootstrap", // guardian binding (also protected by the guardian-downgrade guard)
104
+ "platform_auto_register", // guardian binding auto-registered by the platform
105
+ "webhook_registration", // guardian binding registered via a provider webhook
106
+ ]);
107
+
108
+ /**
109
+ * Total, conservative strength rank for a `verified_via`, used by the gateway
110
+ * ACL write path to refuse demotions. Higher = stronger. Grouped into coarse
111
+ * tiers that hold under ANY intra-tier ordering the pending Slack-permissions
112
+ * PRD (D4) may land on:
113
+ *
114
+ * 3 proven / possession — {@link PROVEN_VERIFIED_VIA}.
115
+ * 2 workspace-vouched — the platform authenticated the identity but the
116
+ * actor did not actively prove control here (`manual`).
117
+ * 1 inbound channel claim — nobody vouches; the guardian trusted an
118
+ * unproven claim (`manual_channel_claim`).
119
+ * 0 unverified — no verification at all (`null` / empty).
120
+ *
121
+ * Returns `null` for an unrecognized non-empty provenance ("unknown"). The
122
+ * demotion guard treats unknown as incomparable and never refuses on it, so a
123
+ * forward-compatible new `verified_via` value is never mistaken for a demotion.
124
+ */
125
+ export function knownStrengthRank(
126
+ verifiedVia: string | null | undefined,
127
+ ): number | null {
128
+ if (verifiedVia == null || verifiedVia === "") return 0;
129
+ if (PROVEN_VERIFIED_VIA.has(verifiedVia)) return 3;
130
+ if (verifiedVia === VERIFIED_VIA_MANUAL) return 2;
131
+ if (verifiedVia === VERIFIED_VIA_CHANNEL_CLAIM) return 1;
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * Whether writing `incomingVia` over an existing `existingVia` binding would
137
+ * LOWER its strength — the demotion the gateway ACL write path refuses
138
+ * (LUM-2505).
139
+ *
140
+ * True only when BOTH provenances are known and the incoming rank is strictly
141
+ * lower than the existing. Unknown provenance on either side is incomparable
142
+ * and never counts as a demotion (fail-open), so the guard blocks only provable
143
+ * downgrades and never breaks a new/unrecognized `verified_via`. Equal ranks
144
+ * (including lateral swaps within the proven tier) and upgrades are not
145
+ * demotions.
146
+ */
147
+ export function isBindingDemotion(
148
+ existingVia: string | null | undefined,
149
+ incomingVia: string | null | undefined,
150
+ ): boolean {
151
+ const existing = knownStrengthRank(existingVia);
152
+ const incoming = knownStrengthRank(incomingVia);
153
+ if (existing == null || incoming == null) return false;
154
+ return incoming < existing;
155
+ }
@@ -321,3 +321,17 @@ export type {
321
321
  ResolvedChannelPermission,
322
322
  RiskThreshold,
323
323
  } from "./channel-permission-contract.js";
324
+
325
+ // Binding-strength vocabulary for the contact `verified_via` provenance —
326
+ // display ladder (introduction card) + the enforcement order the gateway ACL
327
+ // write path uses to refuse demotions (LUM-2505).
328
+ export {
329
+ bindingStrengthForVerifiedVia,
330
+ isBindingDemotion,
331
+ knownStrengthRank,
332
+ VERIFIED_VIA_CHALLENGE,
333
+ VERIFIED_VIA_CHANNEL_CLAIM,
334
+ VERIFIED_VIA_MANUAL,
335
+ } from "./binding-strength-contract.js";
336
+
337
+ export type { BindingStrength } from "./binding-strength-contract.js";
@@ -134,6 +134,77 @@ describe("renderSlackTextForModel", () => {
134
134
  }),
135
135
  ).toBe("@missing user #missing channel");
136
136
  });
137
+
138
+ test("decodes Slack HTML entities so quote markers survive to markdown", () => {
139
+ // Slack entity-encodes every literal &, <, > in message text. `&gt; ` at
140
+ // line start must decode back to `> ` — markdown resolves entities only
141
+ // after block parsing, so an encoded marker never forms a blockquote.
142
+ expect(renderSlackTextForModel("&gt; quoted line\nreply")).toBe(
143
+ "> quoted line\nreply",
144
+ );
145
+ expect(renderSlackTextForModel("1 &lt; 2 &amp;&amp; 3 &gt; 2")).toBe(
146
+ "1 < 2 && 3 > 2",
147
+ );
148
+ });
149
+
150
+ test("decodes entities inside link URLs after token rendering", () => {
151
+ expect(
152
+ renderSlackTextForModel("<https://example.com?a=1&amp;b=2|docs>"),
153
+ ).toBe("docs (https://example.com?a=1&b=2)");
154
+ });
155
+
156
+ test("a user-typed literal entity round-trips instead of over-decoding", () => {
157
+ // Someone typing the four characters `&gt;` in Slack arrives
158
+ // double-encoded as `&amp;gt;` — one decode pass must yield `&gt;`,
159
+ // not collapse it all the way to `>`.
160
+ expect(renderSlackTextForModel("escape it as &amp;gt; in HTML")).toBe(
161
+ "escape it as &gt; in HTML",
162
+ );
163
+ });
164
+
165
+ test("decoded angle brackets do not re-enter token parsing", () => {
166
+ // `&lt;@U123&gt;` is literal text about a mention, not a mention — after
167
+ // decoding it must render as the characters `<@U123>` untouched.
168
+ expect(
169
+ renderSlackTextForModel("say &lt;@U123&gt; to mention", {
170
+ userLabels: { U123: "Alice" },
171
+ }),
172
+ ).toBe("say <@U123> to mention");
173
+ });
174
+
175
+ test("caller-resolved labels are never entity-decoded", () => {
176
+ // Labels come from the caller (resolved display names), not from Slack's
177
+ // entity-encoded message text — literal entity text in them must pass
178
+ // through verbatim.
179
+ expect(
180
+ renderSlackTextForModel("<@U123>", {
181
+ userLabels: { U123: "A &gt; B" },
182
+ }),
183
+ ).toBe("@A &gt; B");
184
+ });
185
+
186
+ test("an encoded bracket in a display name cannot bypass label sanitization", () => {
187
+ // sanitizeLabel strips raw brackets from labels; an entity-encoded
188
+ // bracket must not decode into `<`/`>` after that stripping has run.
189
+ expect(
190
+ renderSlackTextForModel("hi <@U123>", {
191
+ userLabels: { U123: "&lt;fake-token&gt;" },
192
+ }),
193
+ ).toBe("hi @&lt;fake-token&gt;");
194
+ });
195
+
196
+ test("token-embedded labels are Slack-sourced and decode before sanitization", () => {
197
+ expect(renderSlackTextForModel("<#C123|a&amp;b>")).toBe("#a&b");
198
+ expect(renderSlackTextForModel("<!subteam^S123|eng &amp; data>")).toBe(
199
+ "@eng & data",
200
+ );
201
+ });
202
+
203
+ test("unrecognized tokens stay byte-for-byte verbatim", () => {
204
+ expect(renderSlackTextForModel("<mailbox:a&amp;b>")).toBe(
205
+ "<mailbox:a&amp;b>",
206
+ );
207
+ });
137
208
  });
138
209
 
139
210
  describe("buildSlackUserLabelMap", () => {
@@ -42,25 +42,60 @@ export function renderSlackTextForModel(
42
42
  text: string,
43
43
  options: RenderSlackTextOptions = {},
44
44
  ): string {
45
- return text.replace(/<([^<>\s][^<>]*)>/g, (token, content: string) => {
46
- if (content.startsWith("@")) {
47
- return renderUserMention(content, options);
48
- }
45
+ // Decode entities per Slack-sourced segment, never on the combined output:
46
+ // caller-resolved labels (display names, channel names) must pass through
47
+ // verbatim, so a label containing literal entity text is preserved and an
48
+ // encoded bracket in a display name cannot decode into `<`/`>` after
49
+ // sanitizeLabel() has already stripped raw brackets.
50
+ let result = "";
51
+ let cursor = 0;
52
+ for (const match of text.matchAll(/<([^<>\s][^<>]*)>/g)) {
53
+ result += decodeSlackHtmlEntities(text.slice(cursor, match.index));
54
+ result += renderSlackToken(match[0], match[1] as string, options);
55
+ cursor = match.index + match[0].length;
56
+ }
57
+ result += decodeSlackHtmlEntities(text.slice(cursor));
58
+ return result;
59
+ }
49
60
 
50
- if (content.startsWith("#")) {
51
- return renderChannelReference(content, options);
52
- }
61
+ function renderSlackToken(
62
+ token: string,
63
+ content: string,
64
+ options: RenderSlackTextOptions,
65
+ ): string {
66
+ if (content.startsWith("@")) {
67
+ return renderUserMention(content, options);
68
+ }
53
69
 
54
- if (content.startsWith("!")) {
55
- return renderSpecialReference(content);
56
- }
70
+ if (content.startsWith("#")) {
71
+ return renderChannelReference(content, options);
72
+ }
57
73
 
58
- if (looksLikeUrl(content)) {
59
- return renderLink(content);
60
- }
74
+ if (content.startsWith("!")) {
75
+ return renderSpecialReference(content);
76
+ }
77
+
78
+ if (looksLikeUrl(content)) {
79
+ return renderLink(content);
80
+ }
81
+
82
+ return token;
83
+ }
61
84
 
62
- return token;
63
- });
85
+ /**
86
+ * Slack entity-encodes every literal `&`, `<`, and `>` in message text so its
87
+ * own `<...>` control tokens stay unambiguous. Decode them back on the
88
+ * Slack-sourced segments — leaving them encoded breaks downstream markdown
89
+ * (`&gt; quote` at line start never forms a blockquote, since entities resolve
90
+ * only after block parsing) and shows raw entities to the model. `&lt;`/`&gt;`
91
+ * are decoded before `&amp;` so a user-typed literal `&gt;` (double-encoded by
92
+ * Slack as `&amp;gt;`) round-trips to `&gt;`, not `>`.
93
+ */
94
+ function decodeSlackHtmlEntities(text: string): string {
95
+ return text
96
+ .replace(/&lt;/g, "<")
97
+ .replace(/&gt;/g, ">")
98
+ .replace(/&amp;/g, "&");
64
99
  }
65
100
 
66
101
  export async function buildSlackUserLabelMap(
@@ -163,7 +198,11 @@ function renderChannelReference(
163
198
  options.channelFallbackLabel,
164
199
  "unknown-channel",
165
200
  );
166
- const embeddedLabel = sanitizeOptionalLabel(label);
201
+ // The embedded label is Slack-sourced (part of the token), so entities
202
+ // decode before sanitization; the caller-resolved label below is not.
203
+ const embeddedLabel = sanitizeOptionalLabel(
204
+ label === undefined ? undefined : decodeSlackHtmlEntities(label),
205
+ );
167
206
  if (embeddedLabel && embeddedLabel !== channelId) {
168
207
  return `#${embeddedLabel}`;
169
208
  }
@@ -189,19 +228,27 @@ function renderSpecialReference(content: string): string {
189
228
 
190
229
  const subteam = /^!subteam\^[^|>]+(?:\|(.+))?$/.exec(content);
191
230
  if (subteam) {
192
- return `@${sanitizeLabel(subteam[1], "usergroup")}`;
231
+ const embedded = subteam[1];
232
+ return `@${sanitizeLabel(
233
+ embedded === undefined ? undefined : decodeSlackHtmlEntities(embedded),
234
+ "usergroup",
235
+ )}`;
193
236
  }
194
237
 
195
238
  return `<${content}>`;
196
239
  }
197
240
 
198
241
  function renderLink(content: string): string {
199
- const [url, label] = splitSlackLabel(content);
200
- if (!label) {
242
+ // Both halves of a link token are Slack-sourced, so entities decode here
243
+ // (e.g. `&amp;` in URL query strings); sanitizeLabel runs after the decode
244
+ // so it strips any bracket the decode reintroduced.
245
+ const [rawUrl, rawLabel] = splitSlackLabel(content);
246
+ const url = decodeSlackHtmlEntities(rawUrl);
247
+ if (!rawLabel) {
201
248
  return url;
202
249
  }
203
250
 
204
- return `${sanitizeLabel(label, url)} (${url})`;
251
+ return `${sanitizeLabel(decodeSlackHtmlEntities(rawLabel), url)} (${url})`;
205
252
  }
206
253
 
207
254
  function splitSlackLabel(content: string): [string, string | undefined] {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.11-dev.202607221913.60a3564",
3
+ "version": "0.10.11-dev.202607222029.495c516",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -463,10 +463,18 @@ describe("POST /v1/btw", () => {
463
463
  await readStream(result as ReadableStream<Uint8Array>);
464
464
 
465
465
  expect(mockGetConversationByKey).toHaveBeenCalledWith("greeting-abc123");
466
- expect(mockGetOrCreateConversation).toHaveBeenCalledWith("greeting-abc123");
466
+ // An unmapped key has no real conversation, so the side-chain runs against
467
+ // an ephemeral in-memory conversation with no persisted (sidebar-visible)
468
+ // row.
469
+ expect(mockGetOrCreateConversation).toHaveBeenCalledWith(
470
+ "greeting-abc123",
471
+ {
472
+ ephemeral: true,
473
+ },
474
+ );
467
475
  });
468
476
 
469
- test("known conversationKey resolves to existing conversation ID", async () => {
477
+ test("known conversationKey resolves to existing conversation ID without the ephemeral flag", async () => {
470
478
  mockGetConversationByKey.mockReturnValueOnce({
471
479
  conversationId: "existing-conv-id",
472
480
  });
@@ -479,8 +487,11 @@ describe("POST /v1/btw", () => {
479
487
  });
480
488
  await readStream(result as ReadableStream<Uint8Array>);
481
489
 
490
+ // A mapped key targets a real conversation, so its persisted row is reused
491
+ // — no ephemeral options.
482
492
  expect(mockGetOrCreateConversation).toHaveBeenCalledWith(
483
493
  "existing-conv-id",
494
+ undefined,
484
495
  );
485
496
  });
486
497
  });