@vellumai/assistant 0.9.0-dev.202606170320.545830c → 0.9.0-dev.202606170806.f7bee44

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/openapi.yaml CHANGED
@@ -7041,6 +7041,71 @@ paths:
7041
7041
  responses:
7042
7042
  "202":
7043
7043
  description: Successful response
7044
+ /v1/conversations/{id}/slash:
7045
+ post:
7046
+ operationId: conversations_by_id_slash_post
7047
+ summary: Resolve a local meta slash command
7048
+ description:
7049
+ "Run a local meta slash command (/clean, /status, /commands, /models) without starting a turn: no messages
7050
+ are persisted and no turn events are emitted. /clean also strips runtime injections from the history. Returns
7051
+ the text to render and, for /clean, the post-strip context usage."
7052
+ tags:
7053
+ - conversations
7054
+ parameters:
7055
+ - name: id
7056
+ in: path
7057
+ required: true
7058
+ schema:
7059
+ type: string
7060
+ requestBody:
7061
+ required: true
7062
+ content:
7063
+ application/json:
7064
+ schema:
7065
+ type: object
7066
+ properties:
7067
+ command:
7068
+ type: string
7069
+ description: The slash command text, e.g. `/clean` or `/status`.
7070
+ required:
7071
+ - command
7072
+ responses:
7073
+ "200":
7074
+ description: Successful response
7075
+ content:
7076
+ application/json:
7077
+ schema:
7078
+ type: object
7079
+ properties:
7080
+ kind:
7081
+ type: string
7082
+ enum:
7083
+ - clean
7084
+ - info
7085
+ text:
7086
+ type: string
7087
+ contextUsage:
7088
+ type: object
7089
+ properties:
7090
+ tokens:
7091
+ type: number
7092
+ maxTokens:
7093
+ anyOf:
7094
+ - type: number
7095
+ - type: "null"
7096
+ fillRatio:
7097
+ anyOf:
7098
+ - type: number
7099
+ - type: "null"
7100
+ required:
7101
+ - tokens
7102
+ - maxTokens
7103
+ - fillRatio
7104
+ additionalProperties: false
7105
+ required:
7106
+ - kind
7107
+ - text
7108
+ additionalProperties: false
7044
7109
  /v1/conversations/{id}/surface:
7045
7110
  post:
7046
7111
  operationId: conversations_by_id_surface_post
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.9.0-dev.202606170320.545830c",
3
+ "version": "0.9.0-dev.202606170806.f7bee44",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -691,6 +691,57 @@ describe("category frontmatter parsing", () => {
691
691
  });
692
692
  });
693
693
 
694
+ describe("always-candidate frontmatter parsing", () => {
695
+ beforeEach(() => {
696
+ mkdirSync(join(TEST_DIR, "skills"), { recursive: true });
697
+ });
698
+
699
+ afterEach(() => {
700
+ const skillsDir = join(TEST_DIR, "skills");
701
+ if (existsSync(skillsDir))
702
+ rmSync(skillsDir, { recursive: true, force: true });
703
+ });
704
+
705
+ function writeSkillWithAlwaysCandidate(skillId: string, value: string): void {
706
+ const skillDir = join(TEST_DIR, "skills", skillId);
707
+ mkdirSync(skillDir, { recursive: true });
708
+ const metadata = `{"vellum":{"always-candidate":${value}}}`;
709
+ writeFileSync(
710
+ join(skillDir, "SKILL.md"),
711
+ `---\nname: "${skillId}"\ndescription: "test"\nmetadata: ${metadata}\n---\n\nBody.\n`,
712
+ );
713
+ }
714
+
715
+ test("parses always-candidate: true from metadata.vellum", () => {
716
+ writeSkillWithAlwaysCandidate("pinned", "true");
717
+ const skill = loadUserSkillCatalog().find((s) => s.id === "pinned");
718
+ expect(skill!.alwaysCandidate).toBe(true);
719
+ });
720
+
721
+ test("parses always-candidate: false", () => {
722
+ writeSkillWithAlwaysCandidate("unpinned", "false");
723
+ const skill = loadUserSkillCatalog().find((s) => s.id === "unpinned");
724
+ expect(skill!.alwaysCandidate).toBe(false);
725
+ });
726
+
727
+ test("returns undefined for a non-boolean always-candidate", () => {
728
+ writeSkillWithAlwaysCandidate("bad", '"yes"');
729
+ const skill = loadUserSkillCatalog().find((s) => s.id === "bad");
730
+ expect(skill!.alwaysCandidate).toBeUndefined();
731
+ });
732
+
733
+ test("skill without always-candidate has undefined", () => {
734
+ writeSkill("plain", "Plain", "Test");
735
+ const skill = loadUserSkillCatalog().find((s) => s.id === "plain");
736
+ expect(skill!.alwaysCandidate).toBeUndefined();
737
+ });
738
+
739
+ test("the bundled workflows skill is flagged always-candidate", () => {
740
+ const wf = loadSkillCatalog().find((s) => s.id === "workflows");
741
+ expect(wf?.alwaysCandidate).toBe(true);
742
+ });
743
+ });
744
+
694
745
  describe("bundled skill categories", () => {
695
746
  test("every bundled skill declares a valid category slug", () => {
696
747
  const yamlPath = join(
@@ -1,18 +1,22 @@
1
1
  ---
2
2
  name: workflows
3
- description: Author and run autonomous multi-agent workflows that fan work across parallel leaf agents
3
+ description: Delegate a big or high-stakes job to a fleet of parallel subagents, orchestrated deterministically; runs unattended and reports back
4
4
  compatibility: "Designed for Vellum personal assistants"
5
5
  metadata:
6
6
  emoji: "⚙️"
7
7
  vellum:
8
8
  display-name: "Workflows"
9
9
  category: "system"
10
+ always-candidate: true
10
11
  activation-hints:
11
- - "A task decomposes into many similar sub-tasks that can run concurrently (score every item, extract a field from each of many documents, draft-then-verify a batch)"
12
- - "You want fan-out orchestrated deterministically and the result reported back when the whole run finishes"
12
+ - "Batch — apply one operation to each of MANY items (score / rate / rank / classify / extract / summarize each of a large set)"
13
+ - "Comprehensive coverage — exhaustively sweep, audit, or find EVERY instance across a large surface"
14
+ - "Research & synthesize — gather across many sources or pages and combine into one answer"
15
+ - "Confidence — generate several independent attempts and judge them, or adversarially verify findings before trusting the result"
16
+ - "Scale — work too large to finish well in one inline pass"
13
17
  avoid-when:
14
- - "The task is a single tool call or a quick lookup — do it inline"
15
- - "The work needs interactive, conversational back-and-forth rather than unattended fan-out"
18
+ - "A single inline answer, a quick lookup, or a small one-off"
19
+ - "Interactive, conversational back-and-forth rather than unattended fan-out"
16
20
  ---
17
21
 
18
22
  A workflow is a short JS/TS script you author that runs in a sandbox and fans work
@@ -21,8 +25,11 @@ one with `run_workflow` (inline `script` OR saved `name`, exactly one). It retur
21
25
  `runId` immediately; the run is asynchronous and you are notified in this
22
26
  conversation when it completes — **do NOT poll**.
23
27
 
24
- Reach for one when a task decomposes into many similar small sub-tasks that can run
25
- concurrently. For a single task or a quick lookup, do it inline.
28
+ Reach for one when a job is too big, too parallel, or too important for one inline
29
+ pass. That is more than batch/map-reduce over many items — it also covers exhaustively
30
+ sweeping or auditing a large surface, researching across many sources and synthesizing,
31
+ and generating several independent attempts to judge or adversarially verify before
32
+ trusting the result. For a single task or a quick lookup, do it inline.
26
33
 
27
34
  ## The script model
28
35
 
@@ -47,6 +47,7 @@ const VellumMetadataSchema = z
47
47
  "activation-hints": z.array(z.string()).optional(),
48
48
  "avoid-when": z.array(z.string()).optional(),
49
49
  category: z.string().optional(),
50
+ "always-candidate": z.boolean().optional(),
50
51
  })
51
52
  .passthrough();
52
53
 
@@ -109,6 +110,13 @@ export interface SkillSummary {
109
110
  avoidWhen?: string[];
110
111
  /** Category slug declared in frontmatter, used as a fallback when the skill is not in the Vellum catalog. */
111
112
  category?: string;
113
+ /**
114
+ * When true, this skill is pinned into the memory-v3 selector's stable-prefix
115
+ * candidate pool every turn (so the selector can choose it even when no
116
+ * retrieval lane surfaces it). For cross-cutting capabilities whose relevance
117
+ * the model must judge, not embedding similarity.
118
+ */
119
+ alwaysCandidate?: boolean;
112
120
  /** Parsed inline command expansion descriptors (`!\`command\``) found in the skill body. */
113
121
  inlineCommandExpansions?: InlineCommandExpansion[];
114
122
  }
@@ -227,6 +235,7 @@ interface ParsedFrontmatter {
227
235
  activationHints?: string[];
228
236
  avoidWhen?: string[];
229
237
  category?: string;
238
+ alwaysCandidate?: boolean;
230
239
  inlineCommandExpansions?: InlineCommandExpansion[];
231
240
  }
232
241
 
@@ -342,6 +351,11 @@ function parseFrontmatter(
342
351
  ? vellum.category.trim()
343
352
  : undefined;
344
353
 
354
+ const alwaysCandidate =
355
+ typeof vellum?.["always-candidate"] === "boolean"
356
+ ? vellum["always-candidate"]
357
+ : undefined;
358
+
345
359
  const strippedBody = stripCommentLines(body);
346
360
 
347
361
  // Parse inline command expansions from the body (after frontmatter/comment stripping)
@@ -366,6 +380,7 @@ function parseFrontmatter(
366
380
  activationHints,
367
381
  avoidWhen,
368
382
  category,
383
+ alwaysCandidate,
369
384
  inlineCommandExpansions,
370
385
  };
371
386
  }
@@ -523,6 +538,7 @@ function readSkillFromDirectory(
523
538
  activationHints: parsed.activationHints,
524
539
  avoidWhen: parsed.avoidWhen,
525
540
  category: parsed.category,
541
+ alwaysCandidate: parsed.alwaysCandidate,
526
542
  inlineCommandExpansions: parsed.inlineCommandExpansions,
527
543
  };
528
544
  } catch (err) {
@@ -576,6 +592,7 @@ function readBundledSkillFromDirectory(
576
592
  activationHints: parsed.activationHints,
577
593
  avoidWhen: parsed.avoidWhen,
578
594
  category: parsed.category,
595
+ alwaysCandidate: parsed.alwaysCandidate,
579
596
  inlineCommandExpansions: parsed.inlineCommandExpansions,
580
597
  };
581
598
  } catch (err) {
@@ -637,6 +654,7 @@ function loadBundledSkills(): SkillSummary[] {
637
654
  activationHints: skill.activationHints,
638
655
  avoidWhen: skill.avoidWhen,
639
656
  category: skill.category,
657
+ alwaysCandidate: skill.alwaysCandidate,
640
658
  inlineCommandExpansions: skill.inlineCommandExpansions,
641
659
  });
642
660
  }
@@ -764,6 +782,7 @@ function skillSummaryFromDefinition(
764
782
  activationHints: skill.activationHints,
765
783
  avoidWhen: skill.avoidWhen,
766
784
  category: skill.category,
785
+ alwaysCandidate: skill.alwaysCandidate,
767
786
  inlineCommandExpansions: skill.inlineCommandExpansions,
768
787
  };
769
788
  }
@@ -818,6 +837,7 @@ export function loadSkillCatalog(
818
837
  activationHints: parsed.activationHints,
819
838
  avoidWhen: parsed.avoidWhen,
820
839
  category: parsed.category,
840
+ alwaysCandidate: parsed.alwaysCandidate,
821
841
  inlineCommandExpansions: parsed.inlineCommandExpansions,
822
842
  });
823
843
  } catch (err) {
@@ -954,6 +974,7 @@ export function loadSkillCatalog(
954
974
  activationHints: parsed.activationHints,
955
975
  avoidWhen: parsed.avoidWhen,
956
976
  category: parsed.category,
977
+ alwaysCandidate: parsed.alwaysCandidate,
957
978
  inlineCommandExpansions: parsed.inlineCommandExpansions,
958
979
  };
959
980
 
@@ -153,7 +153,7 @@ function resolveQueuedTurnInterfaceContext(
153
153
  }
154
154
 
155
155
  /** Build a SlashContext from the current conversation state and config. */
156
- function buildSlashContext(
156
+ export function buildSlashContext(
157
157
  content: string,
158
158
  conversation: Conversation,
159
159
  ): SlashContext | undefined {
@@ -2,15 +2,22 @@ import { v4 as uuid } from "uuid";
2
2
 
3
3
  import { clearAll, getConversation } from "../../memory/conversation-crud.js";
4
4
  import { resolveConversationId } from "../../memory/conversation-key-store.js";
5
+ import { isUntrustedTrustClass } from "../../runtime/actor-trust-resolver.js";
5
6
  import { broadcastMessage } from "../../runtime/assistant-event-hub.js";
6
7
  import { getSubagentManager } from "../../subagent/index.js";
7
8
  import { createAbortReason } from "../../util/abort-reasons.js";
9
+ import { UserError } from "../../util/errors.js";
8
10
  import { truncate } from "../../util/truncate.js";
9
11
  import { regenerate } from "../conversation-history.js";
12
+ import {
13
+ buildSlashContext,
14
+ formatCleanResult,
15
+ } from "../conversation-process.js";
10
16
  import {
11
17
  conversationEntries,
12
18
  findConversation,
13
19
  } from "../conversation-registry.js";
20
+ import { resolveSlash } from "../conversation-slash.js";
14
21
  import {
15
22
  clearAllActiveConversations,
16
23
  getOrCreateConversation,
@@ -18,6 +25,7 @@ import {
18
25
  } from "../conversation-store.js";
19
26
  import type { ConfirmationResponse } from "../message-protocol.js";
20
27
  import { normalizeConversationType } from "../message-protocol.js";
28
+ import { INTERNAL_GUARDIAN_TRUST_CONTEXT } from "../trust-context.js";
21
29
  import { log } from "./shared.js";
22
30
 
23
31
  export function handleConfirmationResponse(msg: ConfirmationResponse): void {
@@ -118,6 +126,78 @@ export async function undoLastMessage(
118
126
  const removedCount = conversation.undo();
119
127
  return { removedCount };
120
128
  }
129
+
130
+ export interface MetaSlashCommandResult {
131
+ kind: "clean" | "info";
132
+ /** User-facing text to render (clean stats card or info listing). */
133
+ text: string;
134
+ /** Present for `/clean`: the post-strip context-window usage. */
135
+ contextUsage?: {
136
+ tokens: number;
137
+ maxTokens: number | null;
138
+ fillRatio: number | null;
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Resolve a local meta slash command (`/clean`, `/status`, `/commands`,
144
+ * `/models`) for a conversation without running a turn: no user/assistant
145
+ * messages are persisted and no streaming/turn events are emitted. `/clean`
146
+ * additionally strips runtime injections via `forceClean`.
147
+ *
148
+ * Returns null if the conversation cannot be resolved. Throws `UserError` for
149
+ * commands that are not local meta commands (`/compact`, passthrough) — those
150
+ * must be sent as a normal message so they run a real turn.
151
+ */
152
+ export async function resolveMetaSlashCommand(
153
+ conversationId: string,
154
+ command: string,
155
+ ): Promise<MetaSlashCommandResult | null> {
156
+ const resolvedId = resolveConversationId(conversationId);
157
+ if (!resolvedId) {
158
+ return null;
159
+ }
160
+ const conversation = await getOrCreateConversation(resolvedId);
161
+ touchConversation(resolvedId);
162
+ // Local meta commands are owner-initiated self-maintenance. Without a trusted
163
+ // context, `loadFromDb` filters history to non-guardian provenance — so for a
164
+ // guardian-authored conversation `/clean` reports 0 preserved and `/status` 0
165
+ // messages. Apply the guardian context before hydrating so the owner operates
166
+ // on the full history. A real turn re-resolves trust per-actor afterward.
167
+ if (isUntrustedTrustClass(conversation.trustContext?.trustClass)) {
168
+ conversation.setTrustContext(INTERNAL_GUARDIAN_TRUST_CONTEXT);
169
+ }
170
+ await conversation.ensureActorScopedHistory();
171
+
172
+ const slashResult = await resolveSlash(
173
+ command,
174
+ buildSlashContext(command, conversation),
175
+ );
176
+
177
+ if (slashResult.kind === "clean") {
178
+ const result = await conversation.forceClean();
179
+ return {
180
+ kind: "clean",
181
+ text: formatCleanResult(result),
182
+ contextUsage: {
183
+ tokens: result.estimatedInputTokens,
184
+ maxTokens: result.maxInputTokens,
185
+ fillRatio:
186
+ result.maxInputTokens > 0
187
+ ? result.estimatedInputTokens / result.maxInputTokens
188
+ : null,
189
+ },
190
+ };
191
+ }
192
+
193
+ if (slashResult.kind === "unknown") {
194
+ return { kind: "info", text: slashResult.message };
195
+ }
196
+
197
+ // `compact` / `passthrough` are real turns, not local meta commands.
198
+ throw new UserError(`\`${command.trim()}\` is not a local meta command.`);
199
+ }
200
+
121
201
  /**
122
202
  * Regenerate the last assistant response for a conversation. The caller provides
123
203
  * a `sendEvent` callback for delivering streaming events via HTTP/SSE.
@@ -45,6 +45,36 @@ describe("buildSkillContent", () => {
45
45
  const out = buildSkillContent(input);
46
46
  expect(out.length).toBeLessThanOrEqual(500);
47
47
  });
48
+
49
+ test("respects a larger maxChars budget", async () => {
50
+ const { buildSkillContent } = await import("../skill-content.js");
51
+ const input: SkillCapabilityInput = {
52
+ id: "example-skill",
53
+ displayName: "Example Skill",
54
+ description: "x".repeat(1000),
55
+ };
56
+ const out = buildSkillContent(input, 900);
57
+ expect(out.length).toBeLessThanOrEqual(900);
58
+ expect(out.length).toBeGreaterThan(500);
59
+ });
60
+
61
+ test("renders hints as a bulleted list when the budget is enlarged", async () => {
62
+ const { buildSkillContent } = await import("../skill-content.js");
63
+ const input: SkillCapabilityInput = {
64
+ id: "wf",
65
+ displayName: "Workflows",
66
+ description: "Delegate a big job",
67
+ activationHints: ["Batch many items", "Exhaustive sweep"],
68
+ avoidWhen: ["A single lookup"],
69
+ };
70
+ const rich = buildSkillContent(input, 900);
71
+ expect(rich).toContain("Use when:\n- Batch many items\n- Exhaustive sweep");
72
+ expect(rich).toContain("Avoid when:\n- A single lookup");
73
+ // The default (500) budget keeps the compact inline form.
74
+ expect(buildSkillContent(input)).toContain(
75
+ "Use when: Batch many items; Exhaustive sweep.",
76
+ );
77
+ });
48
78
  });
49
79
 
50
80
  describe("augmentMcpSetupDescription", () => {
@@ -1,22 +1,40 @@
1
1
  import { getConfig } from "../../config/loader.js";
2
2
  import type { SkillCapabilityInput } from "../../skills/skill-memory.js";
3
3
 
4
+ /**
5
+ * Character budget for an always-candidate skill's capability statement. Larger
6
+ * than the default so a cross-cutting skill (pinned into the selector pool every
7
+ * turn) can describe its full range of uses rather than a single mode — see
8
+ * `buildSkillContent`'s `maxChars` and `skill-store.ts`'s seeding loop.
9
+ */
10
+ export const ALWAYS_CANDIDATE_CARD_CHARS = 900;
11
+
4
12
  /**
5
13
  * Render the prose-style capability statement embedded into the unified
6
14
  * `memory_v2_concept_pages` Qdrant collection (under the `skills/<id>` slug
7
- * prefix) and rendered in `### Skills You Can Use`. Capped at 500 chars to
8
- * match v1's behavior.
15
+ * prefix) and rendered in `### Skills You Can Use` / the memory-v3 selector
16
+ * card. Capped at `maxChars` (default 500). A larger budget switches the hints
17
+ * to a bulleted list — easier for the selector to parse one mode per line — so
18
+ * always-candidate skills can carry a fuller, multi-mode description.
9
19
  */
10
- export function buildSkillContent(input: SkillCapabilityInput): string {
20
+ export function buildSkillContent(
21
+ input: SkillCapabilityInput,
22
+ maxChars = 500,
23
+ ): string {
24
+ const list = maxChars > 500;
11
25
  let content = `The "${input.displayName}" skill (${input.id}) is available. ${input.description}.`;
12
26
  if (input.activationHints && input.activationHints.length > 0) {
13
- content += ` Use when: ${input.activationHints.join("; ")}.`;
27
+ content += list
28
+ ? `\nUse when:\n${input.activationHints.map((h) => `- ${h}`).join("\n")}`
29
+ : ` Use when: ${input.activationHints.join("; ")}.`;
14
30
  }
15
31
  if (input.avoidWhen && input.avoidWhen.length > 0) {
16
- content += ` Avoid when: ${input.avoidWhen.join("; ")}.`;
32
+ content += list
33
+ ? `\nAvoid when:\n${input.avoidWhen.map((a) => `- ${a}`).join("\n")}`
34
+ : ` Avoid when: ${input.avoidWhen.join("; ")}.`;
17
35
  }
18
- if (content.length > 500) {
19
- content = content.slice(0, 500);
36
+ if (content.length > maxChars) {
37
+ content = content.slice(0, maxChars);
20
38
  }
21
39
  return content;
22
40
  }
@@ -41,6 +41,7 @@ import {
41
41
  upsertConceptPageEmbedding,
42
42
  } from "./qdrant.js";
43
43
  import {
44
+ ALWAYS_CANDIDATE_CARD_CHARS,
44
45
  augmentMcpSetupDescription,
45
46
  buildSkillContent,
46
47
  } from "./skill-content.js";
@@ -188,7 +189,12 @@ async function runSeedV2SkillEntries(generation: number): Promise<void> {
188
189
  if (flagKey && !isAssistantFeatureFlagEnabled(flagKey, config)) continue;
189
190
 
190
191
  const augmented = augmentMcpSetupDescription(fromSkillSummary(summary));
191
- const content = buildSkillContent(augmented);
192
+ // Always-candidate skills are pinned into the selector pool every turn, so
193
+ // they get a larger budget for a fuller, multi-mode capability statement.
194
+ const content = buildSkillContent(
195
+ augmented,
196
+ summary.alwaysCandidate ? ALWAYS_CANDIDATE_CARD_CHARS : undefined,
197
+ );
192
198
  seeds.push({ id: summary.id, content });
193
199
  }
194
200
 
@@ -128,11 +128,11 @@ function depsOf(
128
128
  const coreSlugs = overrides.coreSlugs ?? [];
129
129
  const hotSlugs = overrides.hotSlugs ?? [];
130
130
  const freshSlugs = overrides.freshSlugs ?? [];
131
+ const alwaysCandidateSlugs = overrides.alwaysCandidateSlugs ?? [];
131
132
  const prefixCards = new Map<Slug, string>(
132
- [...coreSlugs, ...hotSlugs, ...freshSlugs].map((slug) => [
133
- slug,
134
- renderCard(slug, RAW[slug] ?? ""),
135
- ]),
133
+ [...coreSlugs, ...hotSlugs, ...freshSlugs, ...alwaysCandidateSlugs].map(
134
+ (slug) => [slug, renderCard(slug, RAW[slug] ?? "")],
135
+ ),
136
136
  );
137
137
  return {
138
138
  sectionIndex: lanes.sectionIndex,
@@ -307,6 +307,33 @@ describe("orchestrate — candidate pool composition", () => {
307
307
  expect(lastPool).toContain(CAP);
308
308
  });
309
309
 
310
+ test("always-candidate slugs are pinned into the stable prefix and are selectable", async () => {
311
+ const lanes = await buildLanes();
312
+ const WF: Slug = "skills/workflows";
313
+ // No retrieval lane surfaces WF for "apple" (hits topic-a/b/d) — it reaches
314
+ // the selector ONLY because it is an always-candidate.
315
+ providerStub = selectProvider([WF]);
316
+ const result = await orchestrate(
317
+ makeTurn(1, "apple"),
318
+ depsOf(lanes, { alwaysCandidateSlugs: [WF] }),
319
+ );
320
+
321
+ expect(lastPool).toContain(WF);
322
+ expect(result.selections.map((s) => s.slug)).toContain(WF);
323
+ });
324
+
325
+ test("an always-candidate slug already in core is not double-listed", async () => {
326
+ const lanes = await buildLanes();
327
+ const WF: Slug = "skills/workflows";
328
+ providerStub = selectProvider([]);
329
+ await orchestrate(
330
+ makeTurn(1, "apple"),
331
+ depsOf(lanes, { coreSlugs: [WF], alwaysCandidateSlugs: [WF] }),
332
+ );
333
+
334
+ expect(lastPool.filter((s) => s === WF)).toHaveLength(1);
335
+ });
336
+
310
337
  test("edge curated link description becomes the edge candidate's descriptor", async () => {
311
338
  const lanes = await buildLanes();
312
339
  providerStub = selectProvider([]);
@@ -7,7 +7,9 @@
7
7
  * is robust against v2/v3 turn-counter drift and does not match rows that
8
8
  * predate the message-id backfill;
9
9
  * - null for a null turn, empty message ids, or no matching rows;
10
- * - NO fallback to another turn/message;
10
+ * - NO blind fallback to a neighbouring turn/message;
11
+ * - the fork fallback: a turn inherited from a fork resolves to the parent's
12
+ * rows via the message's `forkSourceMessageId` back-pointer;
11
13
  * - source/pinned/section mapping and the rendered `<memory>` block;
12
14
  * - `live` / `shadow` reflect the flag resolver.
13
15
  *
@@ -45,6 +47,9 @@ function makeDb() {
45
47
  const db = drizzle(testSqlite, { schema });
46
48
  migrateAddMemoryV3Selections(db);
47
49
  migrateMemoryV3SelectionsMessageIdAndSections(db);
50
+ // The fork-source fallback reads `messages.metadata.forkSourceMessageId`; the
51
+ // inspector store touches only these two columns, so a minimal table suffices.
52
+ testSqlite.exec(`CREATE TABLE messages (id TEXT PRIMARY KEY, metadata TEXT)`);
48
53
  return db;
49
54
  }
50
55
 
@@ -81,6 +86,15 @@ function seed(
81
86
  }
82
87
  }
83
88
 
89
+ function seedMessage(id: string, forkSourceMessageId?: string): void {
90
+ const metadata = JSON.stringify(
91
+ forkSourceMessageId != null ? { forkSourceMessageId } : {},
92
+ );
93
+ testSqlite
94
+ .query(`INSERT INTO messages (id, metadata) VALUES (?, ?)`)
95
+ .run(id, metadata);
96
+ }
97
+
84
98
  mock.module("../../../../config/assistant-feature-flags.js", () => ({
85
99
  ...realFlags,
86
100
  isAssistantFeatureFlagEnabled: (key: string, config: unknown) =>
@@ -281,6 +295,64 @@ describe("getMemoryV3SelectionForInspectorByMessageIds", () => {
281
295
  await getMemoryV3SelectionForInspectorByMessageIds(["any"]),
282
296
  ).toBeNull();
283
297
  });
298
+
299
+ test("falls back to the parent's selection for a forked (inherited) turn", async () => {
300
+ // The parent logged its selection under the parent assistant message id.
301
+ seed(
302
+ "conv-parent",
303
+ 4,
304
+ [{ slug: "domain-a/page-1", source: "needle" }],
305
+ "parent-msg",
306
+ );
307
+ // The fork copied that message under a fresh id with a back-pointer and has
308
+ // no selection rows of its own.
309
+ seedMessage("fork-msg", "parent-msg");
310
+
311
+ const log = await getMemoryV3SelectionForInspectorByMessageIds([
312
+ "fork-msg",
313
+ ]);
314
+ expect(log?.selections.map((s) => s.slug)).toEqual(["domain-a/page-1"]);
315
+ });
316
+
317
+ test("walks a fork-of-a-fork chain to the original selection", async () => {
318
+ seed(
319
+ "conv-orig",
320
+ 2,
321
+ [{ slug: "domain-b/page-2", source: "core" }],
322
+ "orig-msg",
323
+ );
324
+ // The mid fork copied orig; the second fork copied mid. Neither carries its
325
+ // own rows, so resolution must hop twice to reach orig.
326
+ seedMessage("mid-msg", "orig-msg");
327
+ seedMessage("fork2-msg", "mid-msg");
328
+
329
+ const log = await getMemoryV3SelectionForInspectorByMessageIds([
330
+ "fork2-msg",
331
+ ]);
332
+ expect(log?.selections.map((s) => s.slug)).toEqual(["domain-b/page-2"]);
333
+ });
334
+
335
+ test("prefers the message's own rows over the fork-source fallback", async () => {
336
+ // A post-fork native turn has its own rows AND a back-pointer; the direct
337
+ // rows must win so a native turn is never misattributed to the parent.
338
+ seed("conv-parent", 4, [{ slug: "parent/page", source: "needle" }], "src");
339
+ seed("conv-fork", 0, [{ slug: "own/page", source: "core" }], "native-msg");
340
+ seedMessage("native-msg", "src");
341
+
342
+ const log = await getMemoryV3SelectionForInspectorByMessageIds([
343
+ "native-msg",
344
+ ]);
345
+ expect(log?.selections.map((s) => s.slug)).toEqual(["own/page"]);
346
+ });
347
+
348
+ test("returns null for a fork copy whose ancestors logged nothing", async () => {
349
+ // A fork copy (has a back-pointer) where neither it nor its source ever
350
+ // logged a v3 selection.
351
+ seedMessage("fork-msg", "parent-msg");
352
+ expect(
353
+ await getMemoryV3SelectionForInspectorByMessageIds(["fork-msg"]),
354
+ ).toBeNull();
355
+ });
284
356
  });
285
357
 
286
358
  describe("summarizeSelections", () => {
@@ -18,9 +18,10 @@
18
18
  * Each lane only ever ADDS candidates, so the pool is recall-safe by
19
19
  * construction.
20
20
  * 2. Build the candidate pool in CACHE ORDER: the stable prefix —
21
- * `[...core (file order), ...hot (score order), ...fresh (recency
22
- * order)]`, all computed at lane init — followed by the finder
23
- * candidates (needle → dense → edge surfacing order). The stable prefix
21
+ * `[...core (file order), ...hot (score order), ...fresh (recency order),
22
+ * ...always-candidate (skills pinned every turn)]`, all computed at lane
23
+ * init — followed by the finder candidates (needle → dense → edge
24
+ * surfacing order). The stable prefix
24
25
  * is identical across consecutive turns while the lanes are unchanged
25
26
  * (lane invalidation at consolidation is the recompute cadence), so the
26
27
  * selector input's leading segment rides the provider KV cache (the
@@ -82,6 +83,10 @@ export interface OrchestrateDeps {
82
83
  /** The modification-recency fresh set in recency order (computed at lane
83
84
  * init with core and hot excluded). Follows hot in the stable prefix. */
84
85
  freshSlugs: Slug[];
86
+ /** Skills pinned into the candidate pool every turn regardless of retrieval
87
+ * (existence-filtered and core/hot/fresh-excluded at lane init). Follow fresh
88
+ * in the stable prefix so the selector always sees them. */
89
+ alwaysCandidateSlugs?: Slug[];
85
90
  /** Pre-rendered FULL cards for the stable-prefix slugs, keyed by slug.
86
91
  * Rendered ONCE at lane init so the selector's stable prefix is
87
92
  * byte-identical across turns (the cache contract). Every core/hot/fresh
@@ -172,14 +177,19 @@ export async function orchestrate(
172
177
  const { sections } = deps.sectionIndex;
173
178
 
174
179
  // The stable prefix: core (file order), hot (score order), fresh (recency
175
- // order). Hot is computed with core excluded at lane init, fresh with both
176
- // excluded; the filters here are a cheap defensive dedup so a misbehaving
177
- // lane can never double-list a slug.
180
+ // order), then always-candidate skills. Hot is computed with core excluded at
181
+ // lane init, fresh with both excluded, always-candidate with all three
182
+ // excluded; the filters here are a cheap defensive dedup so a misbehaving lane
183
+ // can never double-list a slug.
178
184
  const core = deps.coreSlugs;
179
185
  const hot = deps.hotSlugs.filter((slug) => !core.includes(slug));
180
186
  const coreHot = new Set<Slug>([...core, ...hot]);
181
187
  const fresh = deps.freshSlugs.filter((slug) => !coreHot.has(slug));
182
- const stablePrefix = new Set<Slug>([...coreHot, ...fresh]);
188
+ const coreHotFresh = new Set<Slug>([...coreHot, ...fresh]);
189
+ const always = (deps.alwaysCandidateSlugs ?? []).filter(
190
+ (slug) => !coreHotFresh.has(slug),
191
+ );
192
+ const stablePrefix = new Set<Slug>([...coreHotFresh, ...always]);
183
193
 
184
194
  // Step 1: needle (sync BM25) and dense (async embed + Qdrant) lanes run in
185
195
  // parallel. Both return distinct articles each tagged with their best-scoring
@@ -342,19 +352,21 @@ export async function orchestrate(
342
352
  // its own snippet line so its CURRENT relevance stays visible; `selectPool`
343
353
  // dedupes selections by slug. Finder candidates with no match text fall
344
354
  // back to the page's lead-section snippet.
345
- const stable: StableCandidate[] = [...core, ...hot, ...fresh].map((slug) => {
346
- const card = deps.prefixCards.get(slug);
347
- if (card === undefined) {
348
- // Lane init renders a card for every core/hot slug; a hole here means
349
- // the lanes and the card map are out of sync. Throw rather than render
350
- // a degraded card — the caller (observeTurn) logs and skips the turn,
351
- // which is better than silently breaking the byte-stable prefix.
352
- throw new Error(
353
- `memory-v3: no pre-rendered card for stable-prefix slug "${slug}"`,
354
- );
355
- }
356
- return { slug, card };
357
- });
355
+ const stable: StableCandidate[] = [...core, ...hot, ...fresh, ...always].map(
356
+ (slug) => {
357
+ const card = deps.prefixCards.get(slug);
358
+ if (card === undefined) {
359
+ // Lane init renders a card for every core/hot slug; a hole here means
360
+ // the lanes and the card map are out of sync. Throw rather than render
361
+ // a degraded card — the caller (observeTurn) logs and skips the turn,
362
+ // which is better than silently breaking the byte-stable prefix.
363
+ throw new Error(
364
+ `memory-v3: no pre-rendered card for stable-prefix slug "${slug}"`,
365
+ );
366
+ }
367
+ return { slug, card };
368
+ },
369
+ );
358
370
  const finderTail: PoolCandidate[] = finder.map((c) => ({
359
371
  slug: c.slug,
360
372
  lane: c.lane,
@@ -74,6 +74,52 @@ function rowsForMessageIds(messageIds: string[]): SelectionRow[] {
74
74
  .all(...messageIds) as SelectionRow[];
75
75
  }
76
76
 
77
+ const MAX_FORK_HOPS = 64;
78
+
79
+ /**
80
+ * Read the `forkSourceMessageId` back-pointer that `cloneForkMessageMetadata`
81
+ * stamps onto every message a fork copies, for the given message ids.
82
+ */
83
+ function forkSourceIdsOf(messageIds: string[]): string[] {
84
+ if (messageIds.length === 0) return [];
85
+ const placeholders = messageIds.map(() => "?").join(", ");
86
+ const rows = getSqliteFrom(getDb())
87
+ .query(
88
+ /*sql*/ `
89
+ SELECT json_extract(metadata, '$.forkSourceMessageId') AS src
90
+ FROM messages
91
+ WHERE id IN (${placeholders})
92
+ `,
93
+ )
94
+ .all(...messageIds) as Array<{ src: string | null }>;
95
+ return rows
96
+ .map((r) => r.src)
97
+ .filter((src): src is string => typeof src === "string" && src.length > 0);
98
+ }
99
+
100
+ /**
101
+ * A fork copies the parent's messages under fresh ids but does not copy their
102
+ * `memory_v3_selections` rows, so an inherited turn has no rows under its own
103
+ * message ids. Each copied message preserves a `forkSourceMessageId` pointer to
104
+ * the message it was cloned from; walk that chain (a fork of a fork chains it
105
+ * again) to the nearest ancestor generation that logged selections and return
106
+ * those rows. Returns `[]` when no ancestor has v3 rows (or the ids aren't fork
107
+ * copies).
108
+ */
109
+ function rowsViaForkSource(messageIds: string[]): SelectionRow[] {
110
+ let frontier = messageIds;
111
+ const visited = new Set(messageIds);
112
+ for (let hop = 0; hop < MAX_FORK_HOPS; hop++) {
113
+ const sources = forkSourceIdsOf(frontier).filter((id) => !visited.has(id));
114
+ if (sources.length === 0) return [];
115
+ for (const id of sources) visited.add(id);
116
+ const rows = rowsForMessageIds(sources);
117
+ if (rows.length > 0) return rows;
118
+ frontier = sources;
119
+ }
120
+ return [];
121
+ }
122
+
77
123
  /**
78
124
  * Resolve each selection's persisted matched section `(slug, ordinal)` to the
79
125
  * concrete `Section` in the CURRENT page, so the injected block renders the
@@ -150,13 +196,20 @@ async function buildSelectionLog(
150
196
  * conversation with no v3 data). Message ids are globally unique, so no
151
197
  * conversation scope is needed.
152
198
  *
199
+ * For turns inherited from a fork, the copied messages carry fresh ids with no
200
+ * selection rows of their own, so the lookup falls back to the parent's rows by
201
+ * following each message's `forkSourceMessageId` back-pointer.
202
+ *
153
203
  * Selection rows are stored in selection order, so rendering them in row order
154
204
  * reproduces the block v3 would inject.
155
205
  */
156
206
  export async function getMemoryV3SelectionForInspectorByMessageIds(
157
207
  messageIds: string[],
158
208
  ): Promise<MemoryV3SelectionLog | null> {
159
- return buildSelectionLog(rowsForMessageIds(messageIds));
209
+ const rows = rowsForMessageIds(messageIds);
210
+ return buildSelectionLog(
211
+ rows.length > 0 ? rows : rowsViaForkSource(messageIds),
212
+ );
160
213
  }
161
214
 
162
215
  /**
@@ -34,6 +34,7 @@ import { existsSync, readFileSync } from "node:fs";
34
34
  import { isAssistantFeatureFlagEnabled } from "../../../config/assistant-feature-flags.js";
35
35
  import { getConfig } from "../../../config/loader.js";
36
36
  import type { AssistantConfig } from "../../../config/schema.js";
37
+ import { loadSkillCatalog } from "../../../config/skills.js";
37
38
  import { getMessages } from "../../../memory/conversation-crud.js";
38
39
  import { getDb, getSqliteFrom } from "../../../memory/db-connection.js";
39
40
  import { stringifyMessageContent } from "../../../memory/message-content.js";
@@ -107,6 +108,9 @@ export interface ShadowLanes {
107
108
  /** Modification-recency fresh set in recency order: core and hot excluded,
108
109
  * filtered to pages in the section index. */
109
110
  freshSlugs: string[];
111
+ /** Skills pinned into the stable prefix every turn (`always-candidate: true`
112
+ * in SKILL.md), existence-filtered and core/hot/fresh-excluded. */
113
+ alwaysCandidateSlugs: string[];
110
114
  /** Learned-edge graph: co-selection NPMI associations over the selection
111
115
  * log, rebuilt with the lanes (the consolidation cadence). */
112
116
  learnedGraph: EdgeGraph;
@@ -216,6 +220,18 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
216
220
  excludeSlugs: new Set([...coreSlugs, ...hotSlugs]),
217
221
  }).filter((slug) => sectionIndex.byArticle.has(slug));
218
222
 
223
+ // Always-candidate skills are pinned into the stable prefix every turn so the
224
+ // selector can choose a cross-cutting capability (e.g. workflows) even when no
225
+ // retrieval lane surfaces it — its relevance is a judgment the model makes,
226
+ // not something embedding similarity finds. Filtered to skills present in the
227
+ // section index and excluded from core/hot/fresh so the prefix never
228
+ // double-lists a slug.
229
+ const prefixSet = new Set([...coreSlugs, ...hotSlugs, ...freshSlugs]);
230
+ const alwaysCandidateSlugs = loadSkillCatalog()
231
+ .filter((summary) => summary.alwaysCandidate === true)
232
+ .map((summary) => `skills/${summary.id}`)
233
+ .filter((slug) => sectionIndex.byArticle.has(slug) && !prefixSet.has(slug));
234
+
219
235
  // Pre-render the stable-prefix cards ONCE per lane build: the selector's
220
236
  // stable prefix must be byte-identical across turns to ride the provider KV
221
237
  // cache, so the cards are frozen here (lane invalidation at consolidation is
@@ -228,7 +244,10 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
228
244
  const modifiedAtBySlug = new Map(
229
245
  pageIndex.entries.map((entry) => [entry.slug, entry.modifiedAt]),
230
246
  );
231
- const laneAnnotation = (slug: Slug, lane: "core" | "hot" | "fresh") => {
247
+ const laneAnnotation = (
248
+ slug: Slug,
249
+ lane: "core" | "hot" | "fresh" | "always",
250
+ ) => {
232
251
  if (lane !== "fresh") return `[lane: ${lane}]`;
233
252
  const modifiedAt = modifiedAtBySlug.get(slug);
234
253
  if (
@@ -249,6 +268,7 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
249
268
  ["core", coreSlugs],
250
269
  ["hot", hotSlugs],
251
270
  ["fresh", freshSlugs],
271
+ ["always", alwaysCandidateSlugs],
252
272
  ] as const) {
253
273
  for (const slug of slugs) {
254
274
  const raw = await capabilityOrDiskBody(
@@ -303,6 +323,7 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
303
323
  coreSlugs,
304
324
  hotSlugs,
305
325
  freshSlugs,
326
+ alwaysCandidateSlugs,
306
327
  prefixCards,
307
328
  };
308
329
  }
@@ -545,6 +566,7 @@ export async function observeTurn(
545
566
  coreSlugs: lanes.coreSlugs,
546
567
  hotSlugs: lanes.hotSlugs,
547
568
  freshSlugs: lanes.freshSlugs,
569
+ alwaysCandidateSlugs: lanes.alwaysCandidateSlugs,
548
570
  prefixCards: lanes.prefixCards,
549
571
  needleK: v3.needleK,
550
572
  denseK: v3.denseK,
@@ -26,6 +26,7 @@ import {
26
26
  cancelGeneration,
27
27
  clearAllConversations,
28
28
  regenerateResponse,
29
+ resolveMetaSlashCommand,
29
30
  switchConversation,
30
31
  undoLastMessage,
31
32
  } from "../../daemon/handlers/conversations.js";
@@ -452,6 +453,29 @@ async function handleUndoLastMessage({ pathParams = {} }: RouteHandlerArgs) {
452
453
  };
453
454
  }
454
455
 
456
+ async function handleResolveMetaSlashCommand({
457
+ pathParams = {},
458
+ body = {},
459
+ }: RouteHandlerArgs) {
460
+ const command = body.command as string | undefined;
461
+ if (!command || typeof command !== "string") {
462
+ throw new BadRequestError("Missing command");
463
+ }
464
+ let result: Awaited<ReturnType<typeof resolveMetaSlashCommand>>;
465
+ try {
466
+ result = await resolveMetaSlashCommand(pathParams.id!, command);
467
+ } catch (err) {
468
+ if (err instanceof UserError) {
469
+ throw new BadRequestError(err.message);
470
+ }
471
+ throw err;
472
+ }
473
+ if (!result) {
474
+ throw new NotFoundError(`No conversation for ${pathParams.id}`);
475
+ }
476
+ return result;
477
+ }
478
+
455
479
  async function handleRegenerateResponse({ pathParams = {} }: RouteHandlerArgs) {
456
480
  const conversationId = pathParams.id!;
457
481
  try {
@@ -820,6 +844,40 @@ export const ROUTES: RouteDefinition[] = [
820
844
  }),
821
845
  handler: handleUndoLastMessage,
822
846
  },
847
+ {
848
+ operationId: "resolveConversationSlashCommand",
849
+ endpoint: "conversations/:id/slash",
850
+ method: "POST",
851
+ policy: {
852
+ requiredScopes: ["chat.write"],
853
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
854
+ },
855
+ summary: "Resolve a local meta slash command",
856
+ description:
857
+ "Run a local meta slash command (/clean, /status, /commands, /models) " +
858
+ "without starting a turn: no messages are persisted and no turn events " +
859
+ "are emitted. /clean also strips runtime injections from the history. " +
860
+ "Returns the text to render and, for /clean, the post-strip context usage.",
861
+ tags: ["conversations"],
862
+ pathParams: [{ name: "id", type: "uuid" }],
863
+ requestBody: z.object({
864
+ command: z
865
+ .string()
866
+ .describe("The slash command text, e.g. `/clean` or `/status`."),
867
+ }),
868
+ responseBody: z.object({
869
+ kind: z.enum(["clean", "info"]),
870
+ text: z.string(),
871
+ contextUsage: z
872
+ .object({
873
+ tokens: z.number(),
874
+ maxTokens: z.number().nullable(),
875
+ fillRatio: z.number().nullable(),
876
+ })
877
+ .optional(),
878
+ }),
879
+ handler: handleResolveMetaSlashCommand,
880
+ },
823
881
  {
824
882
  operationId: "regenerateResponse",
825
883
  endpoint: "conversations/:id/regenerate",