@vellumai/assistant 0.10.11-dev.202607222029.495c516 → 0.10.11-dev.202607222226.fdf0e3d

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 (51) hide show
  1. package/ARCHITECTURE.md +30 -21
  2. package/package.json +1 -1
  3. package/src/__tests__/approval-source-link.test.ts +208 -0
  4. package/src/__tests__/channel-delivery-store.test.ts +141 -0
  5. package/src/__tests__/dynamic-skill-background-guard.test.ts +102 -13
  6. package/src/__tests__/inline-skill-load-permissions.test.ts +29 -6
  7. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -1
  8. package/src/__tests__/record-persisted-seq-lock-resilience.test.ts +95 -0
  9. package/src/__tests__/slack-notification-approval-card.test.ts +103 -20
  10. package/src/__tests__/tool-approval-handler.test.ts +25 -1
  11. package/src/__tests__/tool-approval-seed-content-blocks.test.ts +179 -96
  12. package/src/api/events/bookmark-created.ts +37 -0
  13. package/src/api/events/bookmark-deleted.ts +20 -0
  14. package/src/api/events/memory-recalled.ts +59 -0
  15. package/src/api/events/memory-status.ts +29 -0
  16. package/src/api/index.ts +30 -0
  17. package/src/calls/__tests__/voice-triage-escalate.test.ts +58 -3
  18. package/src/calls/voice-session-bridge.ts +6 -2
  19. package/src/calls/voice-triage-escalate.ts +30 -1
  20. package/src/config/feature-flag-registry.json +9 -0
  21. package/src/daemon/conversation-tool-setup.ts +7 -3
  22. package/src/daemon/message-types/bookmarks.ts +9 -14
  23. package/src/daemon/message-types/memory.ts +8 -46
  24. package/src/daemon/trust-context-types.ts +8 -0
  25. package/src/messaging/providers/slack/approval-source.ts +87 -0
  26. package/src/messaging/providers/telegram-bot/send.test.ts +88 -0
  27. package/src/messaging/providers/telegram-bot/send.ts +43 -3
  28. package/src/messaging/providers/telegram-bot/transport.ts +26 -8
  29. package/src/notifications/AGENTS.md +2 -0
  30. package/src/notifications/adapters/slack.ts +67 -13
  31. package/src/notifications/approval-card-data.ts +58 -16
  32. package/src/notifications/broadcaster.ts +41 -19
  33. package/src/notifications/guardian-question-mode.ts +81 -0
  34. package/src/notifications/types.ts +5 -0
  35. package/src/permissions/checker.ts +18 -21
  36. package/src/permissions/confirmation-guardian-request.ts +17 -1
  37. package/src/permissions/prompter.ts +3 -0
  38. package/src/persistence/conversation-crud.ts +36 -8
  39. package/src/persistence/delivery-crud.ts +61 -2
  40. package/src/persistence/external-conversation-store.ts +22 -0
  41. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +2 -2
  42. package/src/plugins/mtime-cache.ts +21 -10
  43. package/src/runtime/approval-source-link.ts +107 -0
  44. package/src/runtime/confirmation-request-guardian-bridge.ts +9 -0
  45. package/src/runtime/routes/inbound-conversation.ts +19 -3
  46. package/src/runtime/routes/inbound-message-handler.ts +12 -5
  47. package/src/runtime/tool-grant-request-helper.ts +14 -0
  48. package/src/tools/permission-checker.ts +42 -9
  49. package/src/tools/registry.ts +26 -17
  50. package/src/tools/tool-approval-handler.ts +26 -4
  51. package/src/tools/types.ts +8 -0
package/ARCHITECTURE.md CHANGED
@@ -1411,12 +1411,15 @@ Editing any file in the root skill or any included child invalidates the transit
1411
1411
 
1412
1412
  #### Permission Gating (`skill_load_dynamic:*`)
1413
1413
 
1414
- Skills containing inline command expansions use a separate permission candidate namespace (`skill_load_dynamic:*`) instead of the normal `skill_load:*` namespace. This prevents them from falling through to the permissive default `skill_load:*` allow rule. The permission checker emits candidates in specificity order:
1414
+ Inline-command skill loads are classified **High** risk — in the gateway skill risk classifier (`gateway/src/risk/skill-risk-classifier.ts`), with a defense-in-depth elevation in `check()` for the gateway-unreachable path. The standard auto-approve threshold then governs them like any other high-risk action: they run without a prompt only at **Full access** (`autoApproveUpTo: "high"`) and prompt at every level below it. There is no separate "always ask" override outside the threshold.
1415
1415
 
1416
- 1. `skill_load_dynamic:<skill-id>@<transitive-hash>` — version-pinned approval (most specific)
1417
- 2. `skill_load_dynamic:<skill-id>` — any-version approval
1416
+ These guarantees sit alongside the threshold:
1418
1417
 
1419
- A default ask rule at priority 200 (`default:ask-skill_load_dynamic-global`) catches these candidates, ensuring the guardian is always prompted before inline commands execute. The user can create a pinned trust rule for a specific transitive hash to auto-approve known-good versions. Non-interactive sessions (no human present) deny dynamic skill loads rather than silently auto-approving.
1418
+ - **Escape hatch (guardian).** A user trust rule that covers the load re-classifies its risk inside the gateway (arriving as matchType `user_rule`), so a guardian's own load runs without prompting at any threshold. (A trust rule does not lift the sensitive-tool capability floor, so a non-guardian actor's covered dynamic load is still escalated to the guardian — like any other sensitive tool.) Approvals are offered in a separate candidate namespace so a pinned rule can auto-approve a known-good version rather than falling through to the permissive default `skill_load:*` allow rule:
1419
+ 1. `skill_load_dynamic:<skill-id>@<transitive-hash>` — version-pinned (most specific)
1420
+ 2. `skill_load_dynamic:<skill-id>` — any-version
1421
+ - **Guardian-only self-approval (sensitive-tool gate).** An uncovered dynamic load is routed through the sensitive-tool gate (`tools/tool-approval-handler.ts`: `isSensitiveTool` → `resolveSensitiveToolDecision`). A non-guardian actor is escalated to the guardian via the capability floor — which no threshold, including Full access, can lift — while the guardian self-approves (`proceed`) and the threshold then governs (allow at Full access, prompt below). `skill_load` is otherwise not a side-effect tool, so this makes the dynamic case participate in the same capability floor as host/side-effect tools.
1422
+ - **Non-interactive denial.** An uncovered dynamic load in a session with no interactive client is denied outright — regardless of threshold, including Full access — because embedded shell must never run unattended without a covering rule. Enforced in `tools/permission-checker.ts` (lane B) via `isDynamicSkillLoadInvocation`, independent of the threshold decision.
1420
1423
 
1421
1424
  ```mermaid
1422
1425
  graph TB
@@ -1429,11 +1432,17 @@ graph TB
1429
1432
  SOURCE -->|"No (extra)"| FAIL_SOURCE["Fail closed:<br/>source not eligible"]
1430
1433
  SOURCE -->|"Yes"| HASH["Compute transitive hash"]
1431
1434
  HASH --> DYN["skill_load_dynamic:id@hash<br/>candidate emitted"]
1432
- DYN --> PERM["PermissionChecker"]
1433
- PERM --> RULE{"Trust rule?"}
1434
- RULE -->|"Pinned allow"| RENDER["Execute + render"]
1435
- RULE -->|"No rule"| PROMPT["Prompt guardian"]
1435
+ DYN --> PERM["PermissionChecker<br/>(classified High risk)"]
1436
+ PERM --> RULE{"Covering trust rule?"}
1437
+ RULE -->|"Allow"| RENDER["Execute + render"]
1436
1438
  RULE -->|"Deny"| DENY["Blocked"]
1439
+ RULE -->|"None"| SENS{"Sensitive-tool gate<br/>(lane A): can self-approve?"}
1440
+ SENS -->|"No (non-guardian)"| ESCALATE["Escalate to guardian<br/>(capability floor)"]
1441
+ SENS -->|"Yes (guardian)"| INTERACTIVE{"Interactive client?"}
1442
+ INTERACTIVE -->|"No"| DENY
1443
+ INTERACTIVE -->|"Yes"| THRESH{"autoApproveUpTo"}
1444
+ THRESH -->|"Full access"| RENDER
1445
+ THRESH -->|"Below full"| PROMPT["Prompt guardian"]
1437
1446
  ```
1438
1447
 
1439
1448
  #### Sandbox-Only Execution
@@ -1484,16 +1493,16 @@ Every layer in the pipeline defaults to rejection rather than silent degradation
1484
1493
 
1485
1494
  #### Key Source Files
1486
1495
 
1487
- | File | Role |
1488
- | --------------------------------------------------- | -------------------------------------------------------------------------------- |
1489
- | `assistant/src/skills/inline-command-expansions.ts` | `parseInlineCommandExpansions()` — parser for `!`command`` tokens |
1490
- | `assistant/src/skills/inline-command-runner.ts` | `runInlineCommand()` — sandbox-only command executor |
1491
- | `assistant/src/skills/inline-command-render.ts` | `renderInlineCommands()` — token replacement and XML wrapping |
1492
- | `assistant/src/skills/transitive-version-hash.ts` | `computeTransitiveSkillVersionHash()` — hash covering root + included children |
1493
- | `assistant/src/tools/skills/load.ts` | `skill_load` execute path — feature flag check, source check, render integration |
1494
- | `assistant/src/permissions/checker.ts` | `skill_load_dynamic:*` candidate emission and allowlist options |
1495
- | `assistant/src/permissions/defaults.ts` | `default:ask-skill_load_dynamic-global` rule (priority 200) |
1496
- | `meta/feature-flags/feature-flag-registry.json` | `inline-skill-commands` flag definition |
1496
+ | File | Role |
1497
+ | --------------------------------------------------- | ---------------------------------------------------------------------------------- |
1498
+ | `assistant/src/skills/inline-command-expansions.ts` | `parseInlineCommandExpansions()` — parser for `!`command`` tokens |
1499
+ | `assistant/src/skills/inline-command-runner.ts` | `runInlineCommand()` — sandbox-only command executor |
1500
+ | `assistant/src/skills/inline-command-render.ts` | `renderInlineCommands()` — token replacement and XML wrapping |
1501
+ | `assistant/src/skills/transitive-version-hash.ts` | `computeTransitiveSkillVersionHash()` — hash covering root + included children |
1502
+ | `assistant/src/tools/skills/load.ts` | `skill_load` execute path — feature flag check, source check, render integration |
1503
+ | `assistant/src/permissions/checker.ts` | `skill_load_dynamic:*` candidate emission, allowlist options, High-risk elevation |
1504
+ | `assistant/src/tools/permission-checker.ts` | Non-interactive denial of uncovered dynamic loads (`isDynamicSkillLoadInvocation`) |
1505
+ | `meta/feature-flags/feature-flag-registry.json` | `inline-skill-commands` flag definition |
1497
1506
 
1498
1507
  ### Key Source Files
1499
1508
 
@@ -2051,10 +2060,10 @@ A parallel **client artifact** (`meta/tts-provider-catalog.json`) captures the s
2051
2060
 
2052
2061
  **Config schema (`services.tts`):** The canonical config block lives at `services.tts` in the assistant config. The set of valid provider IDs and provider-specific config objects is catalog-driven — the Zod schema reads from the catalog rather than maintaining a separate hardcoded enum. It contains:
2053
2062
 
2054
- | Field | Type | Default | Description |
2055
- | ----------------------------- | ------ | -------------- | --------------------------------------------------------- |
2063
+ | Field | Type | Default | Description |
2064
+ | ----------------------------- | ------ | -------------- | ---------------------------------------------------------------------------------------- |
2056
2065
  | `services.tts.provider` | enum | `"elevenlabs"` | Active TTS provider (must be a catalog-known provider ID); `"vellum"` = platform-managed |
2057
- | `services.tts.providers.<id>` | object | _(defaults)_ | Provider-specific settings, one block per catalog entry |
2066
+ | `services.tts.providers.<id>` | object | _(defaults)_ | Provider-specific settings, one block per catalog entry |
2058
2067
 
2059
2068
  Provider-specific config is nested under `services.tts.providers.<id>`. All legacy top-level keys (`elevenlabs.*`, `fishAudio.*`) were removed by workspace migration 032 — only canonical `services.tts` paths are supported at runtime.
2060
2069
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.11-dev.202607222029.495c516",
3
+ "version": "0.10.11-dev.202607222226.fdf0e3d",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,208 @@
1
+ import { beforeEach, describe, expect, test } from "bun:test";
2
+
3
+ import { getDb } from "../persistence/db-connection.js";
4
+ import { initializeDb } from "../persistence/db-init.js";
5
+ import { recordInbound } from "../persistence/delivery-crud.js";
6
+ import { upsertBinding } from "../persistence/external-conversation-store.js";
7
+ import { resolveApprovalSourceReference } from "../runtime/approval-source-link.js";
8
+
9
+ await initializeDb();
10
+
11
+ function resetTables() {
12
+ const db = getDb();
13
+ db.run("DELETE FROM channel_inbound_events");
14
+ db.run("DELETE FROM conversation_keys");
15
+ db.run("DELETE FROM external_conversation_bindings");
16
+ db.run("DELETE FROM conversations");
17
+ }
18
+
19
+ describe("resolveApprovalSourceReference", () => {
20
+ beforeEach(resetTables);
21
+
22
+ test("returns null for channels without a registered resolver", () => {
23
+ const result = recordInbound("telegram", "12345", "evt-1", {
24
+ sourceMessageId: "678",
25
+ });
26
+ expect(
27
+ resolveApprovalSourceReference("telegram", result.conversationId),
28
+ ).toBeNull();
29
+ });
30
+
31
+ test("returns null for a conversation with no Slack provenance", () => {
32
+ expect(resolveApprovalSourceReference("slack", "conv-none")).toBeNull();
33
+ });
34
+
35
+ test("resolves chat id and message permalink from the latest inbound event (DM)", () => {
36
+ const result = recordInbound("slack", "D01XYZ", "evt-1", {
37
+ sourceMessageId: "1700000000.000100",
38
+ });
39
+
40
+ expect(
41
+ resolveApprovalSourceReference("slack", result.conversationId),
42
+ ).toEqual({
43
+ sourceChatId: "D01XYZ",
44
+ sourceLink: {
45
+ webUrl: "https://slack.com/archives/D01XYZ/p1700000000000100",
46
+ },
47
+ });
48
+ });
49
+
50
+ test("uses the most recent inbound event when several exist", () => {
51
+ const first = recordInbound("slack", "D01XYZ", "evt-1", {
52
+ sourceMessageId: "1699999900.000001",
53
+ });
54
+ recordInbound("slack", "D01XYZ", "evt-2", {
55
+ sourceMessageId: "1700000000.000100",
56
+ });
57
+
58
+ expect(
59
+ resolveApprovalSourceReference("slack", first.conversationId),
60
+ ).toEqual({
61
+ sourceChatId: "D01XYZ",
62
+ sourceLink: {
63
+ webUrl: "https://slack.com/archives/D01XYZ/p1700000000000100",
64
+ },
65
+ });
66
+ });
67
+
68
+ test("threaded conversations link the message inside its thread", () => {
69
+ const result = recordInbound("slack", "C01ABC", "evt-1", {
70
+ sourceMessageId: "1700000001.000200",
71
+ sourceThreadId: "1700000000.000100",
72
+ });
73
+ upsertBinding({
74
+ conversationId: result.conversationId,
75
+ sourceChannel: "slack",
76
+ externalChatId: "C01ABC",
77
+ externalThreadId: "1700000000.000100",
78
+ });
79
+
80
+ expect(
81
+ resolveApprovalSourceReference("slack", result.conversationId),
82
+ ).toEqual({
83
+ sourceChatId: "C01ABC",
84
+ sourceLink: {
85
+ webUrl:
86
+ "https://slack.com/archives/C01ABC/p1700000001000200?thread_ts=1700000000.000100&cid=C01ABC",
87
+ },
88
+ });
89
+ });
90
+
91
+ test("a thread-root message carries no thread params", () => {
92
+ const result = recordInbound("slack", "C01ABC", "evt-1", {
93
+ sourceMessageId: "1700000000.000100",
94
+ sourceThreadId: "1700000000.000100",
95
+ });
96
+ upsertBinding({
97
+ conversationId: result.conversationId,
98
+ sourceChannel: "slack",
99
+ externalChatId: "C01ABC",
100
+ externalThreadId: "1700000000.000100",
101
+ });
102
+
103
+ expect(
104
+ resolveApprovalSourceReference("slack", result.conversationId),
105
+ ).toEqual({
106
+ sourceChatId: "C01ABC",
107
+ sourceLink: {
108
+ webUrl: "https://slack.com/archives/C01ABC/p1700000000000100",
109
+ },
110
+ });
111
+ });
112
+
113
+ test("falls back to a ts-shaped externalMessageId when sourceMessageId is absent", () => {
114
+ const result = recordInbound("slack", "D01XYZ", "1700000000.000100");
115
+
116
+ expect(
117
+ resolveApprovalSourceReference("slack", result.conversationId),
118
+ ).toEqual({
119
+ sourceChatId: "D01XYZ",
120
+ sourceLink: {
121
+ webUrl: "https://slack.com/archives/D01XYZ/p1700000000000100",
122
+ },
123
+ });
124
+ });
125
+
126
+ test("omits the link when no id is ts-shaped", () => {
127
+ const result = recordInbound("slack", "D01XYZ", "evt-opaque");
128
+
129
+ expect(
130
+ resolveApprovalSourceReference("slack", result.conversationId),
131
+ ).toEqual({
132
+ sourceChatId: "D01XYZ",
133
+ });
134
+ });
135
+
136
+ test("an ingress-stamped hint identifies the exact message, immune to later inbound rows", () => {
137
+ // A second message lands while the first message's turn is still
138
+ // escalating — the hint pins the card to the actual triggering message.
139
+ const result = recordInbound("slack", "D01XYZ", "evt-1", {
140
+ sourceMessageId: "1699999900.000001",
141
+ });
142
+ recordInbound("slack", "D01XYZ", "evt-2", {
143
+ sourceMessageId: "1700000000.000100",
144
+ });
145
+
146
+ expect(
147
+ resolveApprovalSourceReference("slack", result.conversationId, {
148
+ requesterChatId: "D01XYZ",
149
+ sourceMessageId: "1699999900.000001",
150
+ }),
151
+ ).toEqual({
152
+ sourceChatId: "D01XYZ",
153
+ sourceLink: {
154
+ webUrl: "https://slack.com/archives/D01XYZ/p1699999900000001",
155
+ },
156
+ });
157
+ });
158
+
159
+ test("a threaded hint links the message inside its thread without a DB row", () => {
160
+ expect(
161
+ resolveApprovalSourceReference("slack", "conv-unpersisted", {
162
+ requesterChatId: "C01ABC",
163
+ sourceMessageId: "1700000001.000200",
164
+ sourceThreadId: "1700000000.000100",
165
+ }),
166
+ ).toEqual({
167
+ sourceChatId: "C01ABC",
168
+ sourceLink: {
169
+ webUrl:
170
+ "https://slack.com/archives/C01ABC/p1700000001000200?thread_ts=1700000000.000100&cid=C01ABC",
171
+ },
172
+ });
173
+ });
174
+
175
+ test("a hint without a ts-shaped message id falls back to persisted reconstruction", () => {
176
+ const result = recordInbound("slack", "D01XYZ", "evt-1", {
177
+ sourceMessageId: "1700000000.000100",
178
+ });
179
+
180
+ expect(
181
+ resolveApprovalSourceReference("slack", result.conversationId, {
182
+ requesterChatId: "D01XYZ",
183
+ sourceMessageId: "not-a-ts",
184
+ }),
185
+ ).toEqual({
186
+ sourceChatId: "D01XYZ",
187
+ sourceLink: {
188
+ webUrl: "https://slack.com/archives/D01XYZ/p1700000000000100",
189
+ },
190
+ });
191
+ });
192
+
193
+ test("ignores bindings from other channels", () => {
194
+ const result = recordInbound("slack", "D01XYZ", "evt-opaque");
195
+ upsertBinding({
196
+ conversationId: result.conversationId,
197
+ sourceChannel: "telegram",
198
+ externalChatId: "12345",
199
+ externalThreadId: "1700000000.000100",
200
+ });
201
+
202
+ expect(
203
+ resolveApprovalSourceReference("slack", result.conversationId),
204
+ ).toEqual({
205
+ sourceChatId: "D01XYZ",
206
+ });
207
+ });
208
+ });
@@ -151,6 +151,147 @@ describe("channel-delivery-store", () => {
151
151
  expect(r1.conversationId).not.toBe(r2.conversationId);
152
152
  });
153
153
 
154
+ // ── Telegram private-chat topics ──────────────────────────────────
155
+
156
+ test("same Telegram topic reuses the same conversation", () => {
157
+ const r1 = recordInbound("telegram", "chat-9", "msg-1", {
158
+ sourceThreadId: "777",
159
+ });
160
+ const r2 = recordInbound("telegram", "chat-9", "msg-2", {
161
+ sourceThreadId: "777",
162
+ });
163
+
164
+ expect(r1.conversationId).toBe(r2.conversationId);
165
+ expect(
166
+ getConversationByKey("asst:self:telegram:chat-9:thread:777")
167
+ ?.conversationId,
168
+ ).toBe(r1.conversationId);
169
+ });
170
+
171
+ test("different Telegram topics in one chat get different conversations", () => {
172
+ const r1 = recordInbound("telegram", "chat-9", "msg-1", {
173
+ sourceThreadId: "777",
174
+ });
175
+ const r2 = recordInbound("telegram", "chat-9", "msg-2", {
176
+ sourceThreadId: "888",
177
+ });
178
+
179
+ expect(r1.conversationId).not.toBe(r2.conversationId);
180
+ });
181
+
182
+ test("a Telegram message without a topic keeps the chat-level base key", () => {
183
+ const result = recordInbound("telegram", "chat-9", "msg-1");
184
+
185
+ expect(
186
+ getConversationByKey("asst:self:telegram:chat-9")?.conversationId,
187
+ ).toBe(result.conversationId);
188
+ });
189
+
190
+ test("a Telegram topic starts a fresh conversation; the chat's main conversation stays on the base key", () => {
191
+ const main = recordInbound("telegram", "chat-9", "msg-1");
192
+ const topic = recordInbound("telegram", "chat-9", "msg-2", {
193
+ sourceThreadId: "777",
194
+ });
195
+
196
+ expect(topic.conversationId).not.toBe(main.conversationId);
197
+ expect(
198
+ getConversationByKey("asst:self:telegram:chat-9")?.conversationId,
199
+ ).toBe(main.conversationId);
200
+ expect(
201
+ getConversationByKey("asst:self:telegram:chat-9:thread:777")
202
+ ?.conversationId,
203
+ ).toBe(topic.conversationId);
204
+ });
205
+
206
+ test("thread-less Slack reset clears only the channel-level binding, keeping thread bindings", async () => {
207
+ // Pins the channel-agnostic reset contract for Slack: a channel-root
208
+ // /new must not unbind the channel's thread conversations.
209
+ const db = getDb();
210
+ const now = Date.now();
211
+ for (const id of ["conv-slack-root", "conv-slack-thread"]) {
212
+ db.insert(conversations)
213
+ .values({ id, title: "test", createdAt: now, updatedAt: now })
214
+ .run();
215
+ }
216
+ upsertBinding({
217
+ conversationId: "conv-slack-root",
218
+ sourceChannel: "slack",
219
+ externalChatId: "C0123ABCDEF",
220
+ });
221
+ upsertBinding({
222
+ conversationId: "conv-slack-thread",
223
+ sourceChannel: "slack",
224
+ externalChatId: "C0123ABCDEF",
225
+ externalThreadId: "1710000000.000100",
226
+ });
227
+
228
+ const req = new Request("http://localhost/channels/conversation", {
229
+ method: "DELETE",
230
+ headers: { "Content-Type": "application/json" },
231
+ body: JSON.stringify({
232
+ sourceChannel: "slack",
233
+ conversationExternalId: "C0123ABCDEF",
234
+ }),
235
+ });
236
+ const res = await handleDeleteConversation(req);
237
+ expect(res.status).toBe(200);
238
+
239
+ expect(getBindingByChannelChat("slack", "C0123ABCDEF")).toBeNull();
240
+ expect(
241
+ getBindingByChannelChatThread("slack", "C0123ABCDEF", "1710000000.000100")
242
+ ?.conversationId,
243
+ ).toBe("conv-slack-thread");
244
+ });
245
+
246
+ test("thread-less Telegram reset clears only the main-chat binding, keeping topic bindings", async () => {
247
+ const db = getDb();
248
+ const now = Date.now();
249
+ for (const id of ["conv-main", "conv-topic"]) {
250
+ db.insert(conversations)
251
+ .values({ id, title: "test", createdAt: now, updatedAt: now })
252
+ .run();
253
+ }
254
+ setConversationKey("asst:self:telegram:chat-9", "conv-main");
255
+ setConversationKey("telegram:chat-9", "conv-main");
256
+ setConversationKey("asst:self:telegram:chat-9:thread:777", "conv-topic");
257
+ upsertBinding({
258
+ conversationId: "conv-main",
259
+ sourceChannel: "telegram",
260
+ externalChatId: "chat-9",
261
+ });
262
+ upsertBinding({
263
+ conversationId: "conv-topic",
264
+ sourceChannel: "telegram",
265
+ externalChatId: "chat-9",
266
+ externalThreadId: "777",
267
+ });
268
+
269
+ const req = new Request("http://localhost/channels/conversation", {
270
+ method: "DELETE",
271
+ headers: { "Content-Type": "application/json" },
272
+ body: JSON.stringify({
273
+ sourceChannel: "telegram",
274
+ conversationExternalId: "chat-9",
275
+ }),
276
+ });
277
+ const res = await handleDeleteConversation(req);
278
+ expect(res.status).toBe(200);
279
+
280
+ // The main-chat keys and binding are gone…
281
+ expect(getConversationByKey("asst:self:telegram:chat-9")).toBeNull();
282
+ expect(getConversationByKey("telegram:chat-9")).toBeNull();
283
+ expect(getBindingByChannelChat("telegram", "chat-9")).toBeNull();
284
+ // …while the topic conversation keeps its key and binding.
285
+ expect(
286
+ getConversationByKey("asst:self:telegram:chat-9:thread:777")
287
+ ?.conversationId,
288
+ ).toBe("conv-topic");
289
+ expect(
290
+ getBindingByChannelChatThread("telegram", "chat-9", "777")
291
+ ?.conversationId,
292
+ ).toBe("conv-topic");
293
+ });
294
+
154
295
  test("legacy Slack channel key with matching inbound root ts gets aliased to the threaded key", () => {
155
296
  const channelId = "C0123ABCDEF";
156
297
  const threadTs = "1710000000.000100";
@@ -1,14 +1,18 @@
1
1
  /**
2
- * Non-interactive guardian sessions auto-approve prompted tools within the
3
- * background threshold — but inline-command ("dynamic") skill loads must
4
- * never ride that path. They execute embedded shell commands at load time,
5
- * so a prompted (i.e. not covered by a trust rule) dynamic load requires a
6
- * human: in a session with no interactive client it is denied, not
7
- * silently approved.
2
+ * Inline-command ("dynamic") skill loads execute embedded shell at load time,
3
+ * so an uncovered one (no covering trust rule) is gated before it can run. The
4
+ * non-guardian escalation lives in the sensitive-tool gate (lane A) and is
5
+ * covered by tool-approval-handler.test.ts. This suite covers what the
6
+ * permission checker (lane B) still owns for such loads:
8
7
  *
9
- * The gate lives in tools/permission-checker.ts and keys off
10
- * `isDynamicSkillLoadInvocation` from permissions/checker.js (resolved
11
- * skill metadata), not off any matched-rule pattern.
8
+ * - A guardian background session auto-approves ordinary prompted tools within
9
+ * the background threshold, but an uncovered dynamic load is denied — no
10
+ * human is present to review embedded shell — at any threshold.
11
+ * - A guardian interactive session self-approves within its threshold (allow at
12
+ * Full access); a plain (non-dynamic) load is untouched by the gate.
13
+ *
14
+ * The gate keys off `isDynamicSkillLoadInvocation` from permissions/checker.js
15
+ * (resolved skill metadata).
12
16
  */
13
17
 
14
18
  import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
@@ -25,17 +29,26 @@ const fakeToolResult: ToolExecutionResult = { content: "ok", isError: false };
25
29
  /** Controls what isDynamicSkillLoadInvocation reports for the invocation. */
26
30
  let dynamicSkillLoad = false;
27
31
 
32
+ /**
33
+ * Controls the decision check() returns. The non-interactive dynamic-load guard
34
+ * is orthogonal to the threshold, so it must deny whether check() resolved to a
35
+ * "prompt" (background threshold below High) or an "allow" (background threshold
36
+ * at Full access).
37
+ */
38
+ let checkDecision = "prompt";
39
+
28
40
  mock.module("../permissions/channel-permission-query.js", () => ({
29
41
  buildChannelPermissionCellQuery: () => undefined,
30
42
  }));
31
43
 
32
- // check() always prompts: the scenario under test is "no trust rule covers
33
- // this load" (a covering rule lowers the classified risk upstream, so the
34
- // covered case resolves to "allow" before the background gate is reached).
44
+ // The scenario under test is "no trust rule covers this load" (a covering rule
45
+ // lowers the classified risk upstream and arrives as matchType "user_rule",
46
+ // which the guard exempts). check()'s decision is variable so both the
47
+ // below-Full (prompt) and Full-access (allow) background cases are exercised.
35
48
  mock.module("../permissions/checker.js", () => ({
36
49
  isDynamicSkillLoadInvocation: () => dynamicSkillLoad,
37
50
  classifyRisk: async () => ({ level: "medium" }),
38
- check: async () => ({ decision: "prompt", reason: "medium risk" }),
51
+ check: async () => ({ decision: checkDecision, reason: "medium risk" }),
39
52
  generateAllowlistOptions: () => [],
40
53
  generateScopeOptions: () => [],
41
54
  getCachedAssessment: () => undefined,
@@ -115,8 +128,48 @@ async function checkSkillLoad(skill: string) {
115
128
  );
116
129
  }
117
130
 
131
+ function makeInteractiveContext(
132
+ trustClass: ToolContext["trustClass"],
133
+ ): ToolContext {
134
+ return {
135
+ workingDir: "/tmp/project",
136
+ conversationId: "conversation-1",
137
+ trustClass,
138
+ isInteractive: true,
139
+ };
140
+ }
141
+
142
+ /** A prompter that records whether it was reached and resolves to `decision`. */
143
+ function makeRecordingPrompter(decision: "allow" | "deny") {
144
+ let called = false;
145
+ const prompter = {
146
+ prompt: async () => {
147
+ called = true;
148
+ return { decision };
149
+ },
150
+ } as unknown as PermissionPrompter;
151
+ return { prompter, wasCalled: () => called };
152
+ }
153
+
154
+ async function checkSkillLoadWith(
155
+ prompter: PermissionPrompter,
156
+ context: ToolContext,
157
+ skill: string,
158
+ ) {
159
+ const checker = new PermissionChecker(prompter);
160
+ return checker.checkPermission(
161
+ "skill_load",
162
+ { skill },
163
+ skillLoadTool,
164
+ context,
165
+ Date.now(),
166
+ () => undefined,
167
+ );
168
+ }
169
+
118
170
  beforeEach(() => {
119
171
  dynamicSkillLoad = false;
172
+ checkDecision = "prompt";
120
173
  });
121
174
 
122
175
  afterAll(() => {
@@ -136,4 +189,40 @@ describe("non-interactive guardian background auto-approve", () => {
136
189
  expect(decision.allowed).toBe(false);
137
190
  expect(decision.decision).toBe("denied");
138
191
  });
192
+
193
+ test("a dynamic skill load is denied even when check() allows it (Full-access background)", async () => {
194
+ dynamicSkillLoad = true;
195
+ checkDecision = "allow";
196
+ const decision = await checkSkillLoad("inline-command-skill");
197
+ expect(decision.allowed).toBe(false);
198
+ expect(decision.decision).toBe("denied");
199
+ });
200
+ });
201
+
202
+ describe("interactive self-approval gate", () => {
203
+ test("a guardian at Full access self-approves an uncovered dynamic load without prompting", async () => {
204
+ dynamicSkillLoad = true;
205
+ checkDecision = "allow"; // Full access → check() allows
206
+ const { prompter, wasCalled } = makeRecordingPrompter("deny");
207
+ const decision = await checkSkillLoadWith(
208
+ prompter,
209
+ makeInteractiveContext("guardian"),
210
+ "inline-command-skill",
211
+ );
212
+ expect(decision.allowed).toBe(true);
213
+ expect(wasCalled()).toBe(false); // no escalation — the guardian self-approves
214
+ });
215
+
216
+ test("a non-guardian plain (non-dynamic) skill load is unaffected by the gate", async () => {
217
+ dynamicSkillLoad = false;
218
+ checkDecision = "allow";
219
+ const { prompter, wasCalled } = makeRecordingPrompter("deny");
220
+ const decision = await checkSkillLoadWith(
221
+ prompter,
222
+ makeInteractiveContext("trusted_contact"),
223
+ "plain-skill",
224
+ );
225
+ expect(decision.allowed).toBe(true); // check()'s allow stands; gate skipped
226
+ expect(wasCalled()).toBe(false);
227
+ });
139
228
  });
@@ -6,9 +6,10 @@
6
6
  *
7
7
  * 1. Emit skill_load_dynamic:<id>@<hash> / skill_load_dynamic:<id> candidates
8
8
  * instead of skill_load:<id>@<hash> / skill_load:<id>.
9
- * 2. Prompt by default: a threshold-based allow is downgraded to a prompt
10
- * unless a user trust rule covers the load (gateway classification
11
- * matchType "user_rule" — the rule re-classifies the risk).
9
+ * 2. Classify the load as High risk so the auto-approve threshold governs it
10
+ * like any other high-risk action: it prompts below Full access and runs at
11
+ * Full access — unless a user trust rule covers it (gateway matchType
12
+ * "user_rule" lowers the risk, restoring the escape hatch).
12
13
  * 3. Continue matching the existing skill_load:* flow for non-dynamic skills.
13
14
  */
14
15
 
@@ -111,18 +112,40 @@ describe("inline-command skill_load permissions", () => {
111
112
 
112
113
  // ── Default behavior ─────────────────────────────────────────────────
113
114
 
114
- describe("default behavior", () => {
115
- test("an uncovered dynamic skill prompts even when the threshold covers its risk", async () => {
115
+ describe("threshold-governed prompting", () => {
116
+ test("an uncovered dynamic skill prompts below Full access", async () => {
116
117
  ensureSkillsDir();
117
118
  writeDynamicSkill("dynamic-prompt", "Dynamic Prompt Skill");
118
119
 
120
+ // interactive threshold "low" (beforeEach) is below the High risk of an
121
+ // inline-command load, so it prompts.
119
122
  const result = await check(
120
123
  "skill_load",
121
124
  { skill: "dynamic-prompt" },
122
125
  "/tmp",
123
126
  );
124
127
  expect(result.decision).toBe("prompt");
125
- expect(result.reason).toContain("Inline-command skill load");
128
+ expect(result.reason).toContain("above auto-approve threshold");
129
+ });
130
+
131
+ test("an uncovered dynamic skill runs at Full access (high threshold)", async () => {
132
+ ensureSkillsDir();
133
+ writeDynamicSkill("dynamic-full", "Dynamic Full Access Skill");
134
+ mockIpcResponse("get_global_thresholds", {
135
+ interactive: "high",
136
+ autonomous: "high",
137
+ headless: "high",
138
+ });
139
+ _clearGlobalCacheForTesting();
140
+
141
+ // Full access auto-approves High-risk actions — inline-command skill
142
+ // loads included. No special-case override forces a prompt.
143
+ const result = await check(
144
+ "skill_load",
145
+ { skill: "dynamic-full" },
146
+ "/tmp",
147
+ );
148
+ expect(result.decision).toBe("allow");
126
149
  });
127
150
 
128
151
  test("a dynamic skill covered by a user trust rule is allowed", async () => {