@vellumai/assistant 0.8.11-dev.202606120012.5656fc7 → 0.8.11-dev.202606120116.b9ee95b

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.8.11-dev.202606120012.5656fc7",
3
+ "version": "0.8.11-dev.202606120116.b9ee95b",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -32,6 +32,11 @@ import {
32
32
  PluginNotInstalledError,
33
33
  uninstallPlugin,
34
34
  } from "../lib/uninstall-plugin.js";
35
+ import {
36
+ PluginNotUpgradableError,
37
+ type PluginUpgradeResult,
38
+ upgradePlugin,
39
+ } from "../lib/upgrade-plugin.js";
35
40
  import { getCliLogger } from "../logger.js";
36
41
 
37
42
  const log = getCliLogger("plugins");
@@ -53,6 +58,8 @@ Examples:
53
58
  $ assistant plugins list --json
54
59
  $ assistant plugins inspect example
55
60
  $ assistant plugins inspect example --json
61
+ $ assistant plugins upgrade example
62
+ $ assistant plugins upgrade example --dry-run
56
63
  $ assistant plugins search example
57
64
  $ assistant plugins search "^example"
58
65
  $ assistant plugins search example --json
@@ -308,6 +315,61 @@ Examples:
308
315
  process.exitCode = 1;
309
316
  }
310
317
  });
318
+
319
+ plugins
320
+ .command("upgrade <name>")
321
+ .description(
322
+ "Upgrade an installed plugin to the marketplace's current pin",
323
+ )
324
+ .option(
325
+ "--dry-run",
326
+ "Show what would change without modifying the install",
327
+ )
328
+ .option("--json", "Emit machine-readable JSON instead of a summary")
329
+ .action(
330
+ async (name: string, opts: { dryRun?: boolean; json?: boolean }) => {
331
+ try {
332
+ const result = await upgradePlugin(
333
+ { name, dryRun: opts.dryRun },
334
+ { fetch: globalThis.fetch.bind(globalThis) },
335
+ );
336
+
337
+ if (opts.json) {
338
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
339
+ return;
340
+ }
341
+
342
+ // Logged after the JSON early-return: the CLI logger writes
343
+ // info to stdout, which would otherwise corrupt --json output.
344
+ log.info(
345
+ {
346
+ name: result.name,
347
+ outcome: result.outcome,
348
+ from: result.fromCommit,
349
+ to: result.toCommit,
350
+ },
351
+ "plugin upgrade",
352
+ );
353
+
354
+ for (const line of formatUpgrade(result)) {
355
+ console.log(line);
356
+ }
357
+ } catch (err) {
358
+ if (
359
+ err instanceof PluginNotInstalledError ||
360
+ err instanceof PluginNotUpgradableError ||
361
+ err instanceof InvalidPluginNameError
362
+ ) {
363
+ console.error(err.message);
364
+ process.exitCode = 1;
365
+ return;
366
+ }
367
+ const message = err instanceof Error ? err.message : String(err);
368
+ console.error(`Plugin upgrade failed: ${message}`);
369
+ process.exitCode = 1;
370
+ }
371
+ },
372
+ );
311
373
  },
312
374
  });
313
375
  }
@@ -380,3 +442,31 @@ function formatInspection(inspection: PluginInspection): string[] {
380
442
 
381
443
  return lines;
382
444
  }
445
+
446
+ /** Render an upgrade result as human-readable summary lines. */
447
+ function formatUpgrade(result: PluginUpgradeResult): string[] {
448
+ const { name, fromCommit, toCommit } = result;
449
+ const move = `${shortSha(fromCommit)} → ${shortSha(toCommit)}`;
450
+ const provenanceNote = result.provenanceWasUnknown
451
+ ? " (previous install had no recorded provenance)"
452
+ : "";
453
+
454
+ switch (result.outcome) {
455
+ case "already-up-to-date":
456
+ return [`"${name}" is already up to date (${shortSha(toCommit)}).`];
457
+ case "would-upgrade":
458
+ return [
459
+ `"${name}" would upgrade ${move}${provenanceNote} (dry run; no changes made).`,
460
+ ];
461
+ case "upgraded": {
462
+ const count =
463
+ result.fileCount === null
464
+ ? ""
465
+ : ` (${result.fileCount} file${result.fileCount === 1 ? "" : "s"})`;
466
+ return [
467
+ `Upgraded "${name}" ${move}${count}${provenanceNote} → ${result.target}`,
468
+ "Restart the assistant to pick up the upgrade.",
469
+ ];
470
+ }
471
+ }
472
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Tests for {@link upgradePlugin}.
3
+ *
4
+ * An upgrade is drift detection (the same exact SHA comparison
5
+ * {@link inspectPlugin} performs) followed by a forced re-install at the
6
+ * marketplace pin. The marketplace + GitHub Contents API are replaced with an
7
+ * in-memory fixture passed via `fetch`, the clone is replaced with a fake
8
+ * {@link GitRunner} that materializes a tree, and the install target is a real
9
+ * temp directory passed via `workspacePluginsDir` — no globals are patched.
10
+ */
11
+
12
+ import {
13
+ existsSync,
14
+ mkdirSync,
15
+ mkdtempSync,
16
+ readFileSync,
17
+ rmSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
23
+
24
+ import type { FetchLike, GitRunner } from "../install-from-github.js";
25
+ import { PluginNotInstalledError } from "../uninstall-plugin.js";
26
+ import { PluginNotUpgradableError, upgradePlugin } from "../upgrade-plugin.js";
27
+
28
+ const SHA_A = "a".repeat(40);
29
+ const SHA_B = "b".repeat(40);
30
+ const CANON_REPO = "vellum-ai/vellum-assistant";
31
+ const MANIFEST_URL = `https://api.github.com/repos/${CANON_REPO}/contents/plugins/marketplace.json`;
32
+ const CONTENTS = `https://api.github.com/repos/${CANON_REPO}/contents/`;
33
+
34
+ /** A marketplace manifest pinning `name` to `ref`. */
35
+ function manifestWith(name: string, ref: string): unknown {
36
+ return {
37
+ name: "vellum",
38
+ plugins: [
39
+ {
40
+ name,
41
+ source: { source: "github", repo: `example-org/${name}`, ref },
42
+ description: "A test plugin.",
43
+ category: "developer",
44
+ license: "MIT",
45
+ },
46
+ ],
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Build a `fetch` that serves the marketplace manifest and answers the GitHub
52
+ * Contents API listing (used by the adapter-stub lookup) with a 404, so the
53
+ * clone is treated as a raw external tree. `manifest: undefined` answers the
54
+ * manifest with 404; `manifestStatus` overrides the manifest status to
55
+ * simulate a transient marketplace failure.
56
+ */
57
+ function makeFetch(opts: {
58
+ manifest?: unknown;
59
+ manifestStatus?: number;
60
+ }): FetchLike {
61
+ return (async (input: RequestInfo | URL) => {
62
+ const url = typeof input === "string" ? input : input.toString();
63
+ if (url.startsWith(MANIFEST_URL)) {
64
+ if (opts.manifestStatus !== undefined && opts.manifestStatus !== 200) {
65
+ return new Response("manifest unavailable", {
66
+ status: opts.manifestStatus,
67
+ });
68
+ }
69
+ if (opts.manifest === undefined) {
70
+ return new Response("not found", { status: 404 });
71
+ }
72
+ return new Response(JSON.stringify(opts.manifest), { status: 200 });
73
+ }
74
+ // No adapter stub: the Contents API listing for plugins/<name> is empty.
75
+ if (url.startsWith(CONTENTS)) {
76
+ return new Response("not found", { status: 404 });
77
+ }
78
+ return new Response(`unexpected url: ${url}`, { status: 500 });
79
+ }) as FetchLike;
80
+ }
81
+
82
+ /** A fake clone that materializes one file and reports `commit` at HEAD. */
83
+ function fakeGitRunner(commit: string, calls?: string[][]): GitRunner {
84
+ return async (args, { cwd }) => {
85
+ calls?.push([...args]);
86
+ switch (args[0]) {
87
+ case "fetch": {
88
+ mkdirSync(join(cwd, ".git"), { recursive: true });
89
+ writeFileSync(join(cwd, ".git", "config"), "[core]\n");
90
+ writeFileSync(join(cwd, "package.json"), '{"name":"level-up"}');
91
+ return { stdout: "" };
92
+ }
93
+ case "rev-parse":
94
+ return { stdout: `${commit}\n` };
95
+ default:
96
+ return { stdout: "" };
97
+ }
98
+ };
99
+ }
100
+
101
+ /** A git runner that fails the test if any git command runs. */
102
+ const unusedGitRunner: GitRunner = async (args) => {
103
+ throw new Error(`git should not run for this upgrade: ${args.join(" ")}`);
104
+ };
105
+
106
+ /** Materialize an installed plugin copy with an optional provenance sidecar. */
107
+ function installCopy(
108
+ pluginsDir: string,
109
+ name: string,
110
+ sidecar: { commit: string } | null,
111
+ ): void {
112
+ const dir = join(pluginsDir, name);
113
+ mkdirSync(dir, { recursive: true });
114
+ writeFileSync(
115
+ join(dir, "package.json"),
116
+ JSON.stringify({ name, version: "0.1.0", description: "Installed copy." }),
117
+ );
118
+ if (sidecar !== null) {
119
+ writeFileSync(
120
+ join(dir, ".vellum-plugin.json"),
121
+ JSON.stringify({
122
+ name,
123
+ source: {
124
+ kind: "github",
125
+ owner: "example-org",
126
+ repo: name,
127
+ ref: sidecar.commit,
128
+ },
129
+ commit: sidecar.commit,
130
+ installedAt: "2026-06-10T12:00:00.000Z",
131
+ }),
132
+ );
133
+ }
134
+ }
135
+
136
+ /** Read the commit recorded in a copy's provenance sidecar, if present. */
137
+ function sidecarCommit(pluginsDir: string, name: string): string | null {
138
+ const path = join(pluginsDir, name, ".vellum-plugin.json");
139
+ if (!existsSync(path)) return null;
140
+ return JSON.parse(readFileSync(path, "utf-8")).commit ?? null;
141
+ }
142
+
143
+ let ws: string;
144
+ let pluginsDir: string;
145
+
146
+ beforeEach(() => {
147
+ ws = mkdtempSync(join(tmpdir(), "upgrade-plugin-"));
148
+ pluginsDir = join(ws, "plugins");
149
+ mkdirSync(pluginsDir, { recursive: true });
150
+ });
151
+
152
+ afterEach(() => {
153
+ rmSync(ws, { recursive: true, force: true });
154
+ });
155
+
156
+ describe("upgradePlugin", () => {
157
+ test("upgrades to the marketplace pin when it has advanced", async () => {
158
+ // GIVEN an installed copy pinned to SHA_A
159
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
160
+ // AND the marketplace now pins SHA_B
161
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_B) });
162
+ const runGit = fakeGitRunner(SHA_B);
163
+
164
+ // WHEN the plugin is upgraded
165
+ const result = await upgradePlugin(
166
+ { name: "level-up" },
167
+ { fetch, runGit, workspacePluginsDir: pluginsDir },
168
+ );
169
+
170
+ // THEN it reports the move from the old commit to the pin
171
+ expect(result.outcome).toBe("upgraded");
172
+ expect(result.fromCommit).toBe(SHA_A);
173
+ expect(result.toCommit).toBe(SHA_B);
174
+ expect(result.fileCount).toBeGreaterThan(0);
175
+ // AND the new pin is recorded in the provenance sidecar on disk
176
+ expect(sidecarCommit(pluginsDir, "level-up")).toBe(SHA_B);
177
+ });
178
+
179
+ test("is a no-op when the installed commit already equals the pin", async () => {
180
+ // GIVEN an installed copy already pinned to SHA_A
181
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
182
+ // AND the marketplace pins the same SHA_A
183
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_A) });
184
+
185
+ // WHEN the plugin is upgraded (git must never run)
186
+ const result = await upgradePlugin(
187
+ { name: "level-up" },
188
+ { fetch, runGit: unusedGitRunner, workspacePluginsDir: pluginsDir },
189
+ );
190
+
191
+ // THEN it reports already-up-to-date and makes no changes
192
+ expect(result.outcome).toBe("already-up-to-date");
193
+ expect(result.fileCount).toBeNull();
194
+ expect(result.toCommit).toBe(SHA_A);
195
+ });
196
+
197
+ test("a dry run reports the move without modifying the install", async () => {
198
+ // GIVEN an installed copy pinned to SHA_A and a marketplace pin of SHA_B
199
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
200
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_B) });
201
+
202
+ // WHEN the plugin is upgraded with dryRun (git must never run)
203
+ const result = await upgradePlugin(
204
+ { name: "level-up", dryRun: true },
205
+ { fetch, runGit: unusedGitRunner, workspacePluginsDir: pluginsDir },
206
+ );
207
+
208
+ // THEN it reports what would change but leaves the install untouched
209
+ expect(result.outcome).toBe("would-upgrade");
210
+ expect(result.dryRun).toBe(true);
211
+ expect(result.fileCount).toBeNull();
212
+ expect(sidecarCommit(pluginsDir, "level-up")).toBe(SHA_A);
213
+ });
214
+
215
+ test("re-pins and records provenance for an install with none", async () => {
216
+ // GIVEN an installed copy with no provenance sidecar
217
+ installCopy(pluginsDir, "level-up", null);
218
+ // AND the marketplace pins SHA_B
219
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_B) });
220
+ const runGit = fakeGitRunner(SHA_B);
221
+
222
+ // WHEN the plugin is upgraded
223
+ const result = await upgradePlugin(
224
+ { name: "level-up" },
225
+ { fetch, runGit, workspacePluginsDir: pluginsDir },
226
+ );
227
+
228
+ // THEN it upgrades, flags the missing provenance, and records the new pin
229
+ expect(result.outcome).toBe("upgraded");
230
+ expect(result.fromCommit).toBeNull();
231
+ expect(result.provenanceWasUnknown).toBe(true);
232
+ expect(sidecarCommit(pluginsDir, "level-up")).toBe(SHA_B);
233
+ });
234
+
235
+ test("throws PluginNotInstalledError when nothing is installed", async () => {
236
+ // GIVEN no installed copy, though the marketplace has an entry
237
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_B) });
238
+
239
+ // WHEN an upgrade is attempted
240
+ // THEN it refuses because there is no install to advance
241
+ await expect(
242
+ upgradePlugin(
243
+ { name: "level-up" },
244
+ { fetch, runGit: unusedGitRunner, workspacePluginsDir: pluginsDir },
245
+ ),
246
+ ).rejects.toBeInstanceOf(PluginNotInstalledError);
247
+ });
248
+
249
+ test("throws PluginNotUpgradableError when not in the marketplace", async () => {
250
+ // GIVEN an installed copy but an empty marketplace catalog
251
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
252
+ const fetch = makeFetch({ manifest: undefined });
253
+
254
+ // WHEN an upgrade is attempted
255
+ // THEN there is no pin to advance to
256
+ await expect(
257
+ upgradePlugin(
258
+ { name: "level-up" },
259
+ { fetch, runGit: unusedGitRunner, workspacePluginsDir: pluginsDir },
260
+ ),
261
+ ).rejects.toBeInstanceOf(PluginNotUpgradableError);
262
+ });
263
+
264
+ test("throws PluginNotUpgradableError when the marketplace is unreachable", async () => {
265
+ // GIVEN an installed copy and a marketplace fetch that fails transiently
266
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
267
+ const fetch = makeFetch({ manifestStatus: 500 });
268
+
269
+ // WHEN an upgrade is attempted
270
+ // THEN the latest pin cannot be determined, so it refuses
271
+ await expect(
272
+ upgradePlugin(
273
+ { name: "level-up" },
274
+ { fetch, runGit: unusedGitRunner, workspacePluginsDir: pluginsDir },
275
+ ),
276
+ ).rejects.toBeInstanceOf(PluginNotUpgradableError);
277
+ });
278
+
279
+ test("preserves the existing install when the re-install clone fails", async () => {
280
+ // GIVEN an installed copy pinned to SHA_A and an advanced marketplace pin
281
+ installCopy(pluginsDir, "level-up", { commit: SHA_A });
282
+ const fetch = makeFetch({ manifest: manifestWith("level-up", SHA_B) });
283
+ // AND a clone that fails mid-fetch
284
+ const failingGit: GitRunner = async (args) => {
285
+ if (args[0] === "fetch") throw new Error("network down");
286
+ return { stdout: "" };
287
+ };
288
+
289
+ // WHEN the upgrade is attempted
290
+ // THEN it surfaces the clone failure
291
+ await expect(
292
+ upgradePlugin(
293
+ { name: "level-up" },
294
+ { fetch, runGit: failingGit, workspacePluginsDir: pluginsDir },
295
+ ),
296
+ ).rejects.toThrow("network down");
297
+ // AND the previously installed copy is left intact at its old pin
298
+ expect(sidecarCommit(pluginsDir, "level-up")).toBe(SHA_A);
299
+ });
300
+ });
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Upgrade a single installed plugin to the marketplace's current pin.
3
+ *
4
+ * The marketplace pins every plugin to a full, immutable commit SHA (see
5
+ * {@link ./plugin-marketplace}); an upgrade re-materializes the install at
6
+ * whatever SHA the catalog currently advertises. Drift is detected with the
7
+ * same exact commit-SHA comparison {@link ./inspect-plugin} uses, so an
8
+ * upgrade is a no-op when the installed copy already matches the pin.
9
+ *
10
+ * This is deliberately a distinct operation from install: `install` is
11
+ * first-time materialization (and errors on an existing install unless
12
+ * `--force` is passed), whereas `upgrade` moves an existing install forward.
13
+ * Mechanically the move is a forced re-install at the current pin, which the
14
+ * underlying {@link ./install-from-github.installPlugin} performs atomically —
15
+ * the previously installed copy is preserved until the fetch succeeds.
16
+ *
17
+ * Conflict resolution for locally-modified plugins is intentionally out of
18
+ * scope here: this overwrites the install with the pinned tree. A future
19
+ * iteration will detect local edits (installed SHA = merge base) and resolve
20
+ * them before the swap.
21
+ *
22
+ * Designed for direct programmatic use with injected dependencies, mirroring
23
+ * the sibling plugin libraries. The CLI command `assistant plugins upgrade
24
+ * <name>` is a thin wrapper that supplies production deps and formats the
25
+ * result.
26
+ */
27
+
28
+ import { join } from "node:path";
29
+
30
+ import { getWorkspacePluginsDir } from "../../util/platform.js";
31
+ import {
32
+ inspectPlugin,
33
+ type PluginInspection,
34
+ PluginInspectNotFoundError,
35
+ } from "./inspect-plugin.js";
36
+ import {
37
+ type FetchLike,
38
+ type GitRunner,
39
+ installPlugin,
40
+ type PostinstallRunner,
41
+ sanitizePluginName,
42
+ } from "./install-from-github.js";
43
+ import { PluginNotInstalledError } from "./uninstall-plugin.js";
44
+
45
+ /**
46
+ * Outcome of an upgrade attempt.
47
+ *
48
+ * - `upgraded` — the install was moved to the current marketplace pin.
49
+ * - `already-up-to-date` — the installed commit already equals the pin; no-op.
50
+ * - `would-upgrade` — a `--dry-run` that found drift but made no changes.
51
+ */
52
+ export type PluginUpgradeOutcome =
53
+ | "upgraded"
54
+ | "already-up-to-date"
55
+ | "would-upgrade";
56
+
57
+ /** Options that control which plugin to upgrade and how. */
58
+ export interface UpgradePluginOptions {
59
+ /** Install name (kebab-case directory name). */
60
+ readonly name: string;
61
+ /** Report what would change without modifying the install. */
62
+ readonly dryRun?: boolean;
63
+ }
64
+
65
+ /** Dependencies injected by the caller. */
66
+ export interface UpgradePluginDeps {
67
+ /** HTTP client. Production callers pass `globalThis.fetch.bind(globalThis)`. */
68
+ readonly fetch: FetchLike;
69
+ /** Override the workspace plugins directory. Falls back to the live workspace. */
70
+ readonly workspacePluginsDir?: string;
71
+ /** Override the git runner used to clone the source. Forwarded to {@link installPlugin}. */
72
+ readonly runGit?: GitRunner;
73
+ /** Override the postinstall adapter runner. Forwarded to {@link installPlugin}. */
74
+ readonly runPostinstall?: PostinstallRunner;
75
+ }
76
+
77
+ /** Result of an upgrade attempt. */
78
+ export interface PluginUpgradeResult {
79
+ readonly name: string;
80
+ readonly outcome: PluginUpgradeOutcome;
81
+ /** Installed commit before the upgrade; `null` when no provenance was recorded. */
82
+ readonly fromCommit: string | null;
83
+ /** Marketplace-pinned commit the install was (or would be) moved to. */
84
+ readonly toCommit: string;
85
+ /** Absolute path to the installed plugin directory. */
86
+ readonly target: string;
87
+ /** Files materialized by the upgrade; `null` for a no-op or dry run. */
88
+ readonly fileCount: number | null;
89
+ /** Whether this was a dry run (no changes made). */
90
+ readonly dryRun: boolean;
91
+ /**
92
+ * Whether the installed copy lacked resolvable provenance before the
93
+ * upgrade. Such installs are re-pinned to the current SHA, which also
94
+ * records provenance going forward.
95
+ */
96
+ readonly provenanceWasUnknown: boolean;
97
+ }
98
+
99
+ /** An installed plugin has no marketplace pin to upgrade to. */
100
+ export class PluginNotUpgradableError extends Error {
101
+ constructor(
102
+ readonly pluginName: string,
103
+ reason: string,
104
+ ) {
105
+ super(`Plugin "${pluginName}" cannot be upgraded: ${reason}.`);
106
+ this.name = "PluginNotUpgradableError";
107
+ }
108
+ }
109
+
110
+ function pluginTarget(name: string, deps: UpgradePluginDeps): string {
111
+ const dir = deps.workspacePluginsDir ?? getWorkspacePluginsDir();
112
+ return join(dir, name);
113
+ }
114
+
115
+ /**
116
+ * Move an installed plugin to the marketplace's current pin.
117
+ *
118
+ * Throws {@link PluginNotInstalledError} when no copy is installed,
119
+ * {@link PluginNotUpgradableError} when the install has no marketplace pin to
120
+ * advance to (no catalog entry, or the catalog was unreachable), and
121
+ * propagates {@link installPlugin}'s errors (e.g. source unavailable,
122
+ * postinstall failure) when the re-install itself fails.
123
+ */
124
+ export async function upgradePlugin(
125
+ opts: UpgradePluginOptions,
126
+ deps: UpgradePluginDeps,
127
+ ): Promise<PluginUpgradeResult> {
128
+ const name = sanitizePluginName(opts.name);
129
+ const dryRun = opts.dryRun ?? false;
130
+
131
+ let inspection: PluginInspection;
132
+ try {
133
+ inspection = await inspectPlugin(
134
+ { name },
135
+ { fetch: deps.fetch, workspacePluginsDir: deps.workspacePluginsDir },
136
+ );
137
+ } catch (err) {
138
+ if (err instanceof PluginInspectNotFoundError) {
139
+ throw new PluginNotInstalledError(name, pluginTarget(name, deps));
140
+ }
141
+ throw err;
142
+ }
143
+
144
+ switch (inspection.status) {
145
+ case "not-installed":
146
+ throw new PluginNotInstalledError(name, pluginTarget(name, deps));
147
+ case "not-in-marketplace":
148
+ throw new PluginNotUpgradableError(
149
+ name,
150
+ "it has no marketplace entry to upgrade from",
151
+ );
152
+ case "remote-unavailable":
153
+ throw new PluginNotUpgradableError(
154
+ name,
155
+ `the marketplace could not be reached (${inspection.remoteError ?? "unknown error"})`,
156
+ );
157
+ }
158
+
159
+ // The remaining statuses (up-to-date, update-available, unknown-provenance)
160
+ // all imply an installed copy and a resolvable marketplace pin.
161
+ const { local, remote } = inspection;
162
+ if (!local || !remote) {
163
+ throw new PluginNotUpgradableError(
164
+ name,
165
+ "its install or marketplace metadata could not be resolved",
166
+ );
167
+ }
168
+
169
+ const fromCommit = local.commit;
170
+ const toCommit = remote.commit;
171
+ const provenanceWasUnknown = inspection.status === "unknown-provenance";
172
+
173
+ if (inspection.status === "up-to-date") {
174
+ return {
175
+ name,
176
+ outcome: "already-up-to-date",
177
+ fromCommit,
178
+ toCommit,
179
+ target: local.target,
180
+ fileCount: null,
181
+ dryRun,
182
+ provenanceWasUnknown: false,
183
+ };
184
+ }
185
+
186
+ if (dryRun) {
187
+ return {
188
+ name,
189
+ outcome: "would-upgrade",
190
+ fromCommit,
191
+ toCommit,
192
+ target: local.target,
193
+ fileCount: null,
194
+ dryRun: true,
195
+ provenanceWasUnknown,
196
+ };
197
+ }
198
+
199
+ const result = await installPlugin(
200
+ { name, force: true },
201
+ {
202
+ fetch: deps.fetch,
203
+ workspacePluginsDir: deps.workspacePluginsDir,
204
+ runGit: deps.runGit,
205
+ runPostinstall: deps.runPostinstall,
206
+ },
207
+ );
208
+
209
+ return {
210
+ name,
211
+ outcome: "upgraded",
212
+ fromCommit,
213
+ toCommit: result.commit ?? toCommit,
214
+ target: result.target,
215
+ fileCount: result.fileCount,
216
+ dryRun: false,
217
+ provenanceWasUnknown,
218
+ };
219
+ }
@@ -8,6 +8,7 @@ describe("MemoryV3ConfigSchema", () => {
8
8
  expect(parsed).toEqual({
9
9
  prune: { maxResidentBytes: 393216, targetResidentBytes: 262144 },
10
10
  hotSet: { k: 40, halfLifeDays: 14 },
11
+ freshSet: { k: 50 },
11
12
  spotlight: { n: 6, windowTurns: 2 },
12
13
  needleK: 100,
13
14
  denseK: 100,
@@ -63,6 +63,26 @@ export const MemoryV3HotSetSchema = z
63
63
  })
64
64
  .describe("Memory v3 hot-set lane (decayed selection frequency) tuning.");
65
65
 
66
+ /**
67
+ * Fresh-set lane tuning: the top-K pages by most-recent on-disk modification
68
+ * folded into the candidate pool as a stable-prefix lane. Recency covers the
69
+ * window before the other lanes can reach a just-written page (no selection
70
+ * history for the hot set; nothing lexical for the finders on summary-shaped
71
+ * messages).
72
+ */
73
+ export const MemoryV3FreshSetSchema = z
74
+ .object({
75
+ k: z
76
+ .number({ error: "memory.v3.freshSet.k must be a number" })
77
+ .int("memory.v3.freshSet.k must be an integer")
78
+ .nonnegative("memory.v3.freshSet.k must be a non-negative integer")
79
+ .default(50)
80
+ .describe(
81
+ "Number of most-recently-modified pages included in the fresh-set lane (0 disables the lane). Sized to cover roughly the last day or two of page writes — the recency window conversations reference most.",
82
+ ),
83
+ })
84
+ .describe("Memory v3 fresh-set lane (page-modification recency) tuning.");
85
+
66
86
  /**
67
87
  * Ephemeral section-spotlight tuning: how many of the current turn's selected
68
88
  * finder hits render their matched section into the `<memory_spotlight>`
@@ -142,6 +162,7 @@ export const MemoryV3ConfigSchema = z
142
162
  .object({
143
163
  prune: MemoryV3PruneSchema.default(MemoryV3PruneSchema.parse({})),
144
164
  hotSet: MemoryV3HotSetSchema.default(MemoryV3HotSetSchema.parse({})),
165
+ freshSet: MemoryV3FreshSetSchema.default(MemoryV3FreshSetSchema.parse({})),
145
166
  spotlight: MemoryV3SpotlightSchema.default(
146
167
  MemoryV3SpotlightSchema.parse({}),
147
168
  ),
@@ -255,6 +255,7 @@ async function scriptedObserveTurn(conversationId: string, turnIndex: number) {
255
255
  edgeGraph: lanes.edgeGraph,
256
256
  coreSlugs: lanes.coreSlugs,
257
257
  hotSlugs: lanes.hotSlugs,
258
+ freshSlugs: [],
258
259
  prefixCards: lanes.prefixCards,
259
260
  },
260
261
  );
@@ -0,0 +1,52 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { computeFreshSet } from "../fresh-set.js";
4
+
5
+ const entry = (slug: string, modifiedAt: number) => ({ slug, modifiedAt });
6
+
7
+ describe("computeFreshSet", () => {
8
+ test("ranks by modification time, newest first", () => {
9
+ const slugs = computeFreshSet(
10
+ [entry("old", 1000), entry("newest", 3000), entry("mid", 2000)],
11
+ { k: 3, excludeSlugs: new Set() },
12
+ );
13
+ expect(slugs).toEqual(["newest", "mid", "old"]);
14
+ });
15
+
16
+ test("cuts to k after exclusions", () => {
17
+ const slugs = computeFreshSet(
18
+ [entry("a", 4000), entry("b", 3000), entry("c", 2000), entry("d", 1000)],
19
+ { k: 2, excludeSlugs: new Set(["a"]) },
20
+ );
21
+ // "a" is excluded BEFORE the cut, so the two slots go to the next-newest.
22
+ expect(slugs).toEqual(["b", "c"]);
23
+ });
24
+
25
+ test("skips synthetic entries (modifiedAt 0)", () => {
26
+ const slugs = computeFreshSet(
27
+ [entry("skills/oura", 0), entry("real-page", 500)],
28
+ { k: 5, excludeSlugs: new Set() },
29
+ );
30
+ expect(slugs).toEqual(["real-page"]);
31
+ });
32
+
33
+ test("k = 0 disables the lane", () => {
34
+ expect(
35
+ computeFreshSet([entry("a", 1000)], { k: 0, excludeSlugs: new Set() }),
36
+ ).toEqual([]);
37
+ });
38
+
39
+ test("breaks modification-time ties by slug, ascending", () => {
40
+ const slugs = computeFreshSet(
41
+ [entry("zebra", 1000), entry("apple", 1000), entry("mango", 1000)],
42
+ { k: 3, excludeSlugs: new Set() },
43
+ );
44
+ expect(slugs).toEqual(["apple", "mango", "zebra"]);
45
+ });
46
+
47
+ test("does not mutate the input array", () => {
48
+ const entries = [entry("b", 1000), entry("a", 2000)];
49
+ computeFreshSet(entries, { k: 2, excludeSlugs: new Set() });
50
+ expect(entries.map((e) => e.slug)).toEqual(["b", "a"]);
51
+ });
52
+ });
@@ -215,6 +215,7 @@ function result(
215
215
  lanes: {
216
216
  core: [],
217
217
  hot: [],
218
+ fresh: [],
218
219
  finder: matched.map(([slug]) => ({
219
220
  slug,
220
221
  descriptor: "",
@@ -235,6 +235,7 @@ async function runTurn(
235
235
  edgeGraph: deps.lanes.edgeGraph,
236
236
  coreSlugs: [],
237
237
  hotSlugs: [],
238
+ freshSlugs: [],
238
239
  prefixCards: new Map(),
239
240
  });
240
241
  const active = getActiveSlugs(conversationId);
@@ -127,8 +127,9 @@ function depsOf(
127
127
  ): OrchestrateDeps {
128
128
  const coreSlugs = overrides.coreSlugs ?? [];
129
129
  const hotSlugs = overrides.hotSlugs ?? [];
130
+ const freshSlugs = overrides.freshSlugs ?? [];
130
131
  const prefixCards = new Map<Slug, string>(
131
- [...coreSlugs, ...hotSlugs].map((slug) => [
132
+ [...coreSlugs, ...hotSlugs, ...freshSlugs].map((slug) => [
132
133
  slug,
133
134
  renderCard(slug, RAW[slug] ?? ""),
134
135
  ]),
@@ -140,6 +141,7 @@ function depsOf(
140
141
  edgeGraph: lanes.edgeGraph,
141
142
  coreSlugs,
142
143
  hotSlugs,
144
+ freshSlugs,
143
145
  prefixCards,
144
146
  ...overrides,
145
147
  };
@@ -371,6 +373,26 @@ describe("orchestrate — cache-ordered pool (core + hot + finders)", () => {
371
373
  ]);
372
374
  });
373
375
 
376
+ test("fresh follows hot in the pool and dedups against core/hot", async () => {
377
+ const lanes = await buildLanes();
378
+ denseHits = [];
379
+ providerStub = selectProvider([]);
380
+
381
+ const result = await orchestrate(
382
+ makeTurn(1, "apple"),
383
+ depsOf(lanes, {
384
+ coreSlugs: ["topic-c"],
385
+ hotSlugs: ["topic-d"],
386
+ // topic-c (core) and topic-d (hot) are defensively dropped; only
387
+ // topic-b earns a fresh slot.
388
+ freshSlugs: ["topic-c", "topic-d", "topic-b"],
389
+ }),
390
+ );
391
+
392
+ expect(lastPool).toEqual(["topic-c", "topic-d", "topic-b", "topic-a"]);
393
+ expect(result.lanes.fresh).toEqual(["topic-b"]);
394
+ });
395
+
374
396
  test("the rendered stable prefix is byte-identical across turns with different queries", async () => {
375
397
  const lanes = await buildLanes();
376
398
  const deps = depsOf(lanes, {
@@ -202,6 +202,7 @@ describe("summarizeSelections", () => {
202
202
  expect(summary.bySource).toEqual({
203
203
  core: 0,
204
204
  hot: 0,
205
+ fresh: 0,
205
206
  needle: 2,
206
207
  dense: 0,
207
208
  edge: 2,
@@ -216,6 +217,7 @@ describe("summarizeSelections", () => {
216
217
  bySource: {
217
218
  core: 0,
218
219
  hot: 0,
220
+ fresh: 0,
219
221
  needle: 0,
220
222
  dense: 0,
221
223
  edge: 0,
@@ -310,6 +310,7 @@ async function runTurn(
310
310
  edgeGraph: deps.lanes.edgeGraph,
311
311
  coreSlugs: deps.core ?? [],
312
312
  hotSlugs: deps.hot ?? [],
313
+ freshSlugs: [],
313
314
  // Mirrors lane init: every stable-prefix slug gets a pre-rendered card.
314
315
  prefixCards: new Map(
315
316
  stableSlugs.map((slug) => [slug, renderCard(slug, RAW[slug] ?? "")]),
@@ -476,6 +477,7 @@ describe("memory-v3 shadow integration — selection-log readout", () => {
476
477
  bySource: {
477
478
  core: 0,
478
479
  hot: 0,
480
+ fresh: 0,
479
481
  needle: 0,
480
482
  dense: 0,
481
483
  edge: 0,
@@ -88,8 +88,9 @@ const CAPABILITY_SLUG = "skills/example";
88
88
  const CAPABILITY_CONTENT = "use the kumquat skill to do the thing";
89
89
 
90
90
  // The orchestrate result the spy returns. `lanes` records where each pooled
91
- // slug lived: page-core in the core lane, page-hot in the hot lane, and the
92
- // finder entries page-1 → "needle", page-2 → "dense", page-3 → "edge";
91
+ // slug lived: page-core in the core lane, page-hot in the hot lane, page-fresh
92
+ // in the fresh lane, and the finder entries page-1 → "needle", page-2 → "dense",
93
+ // page-3 → "edge";
93
94
  // `attributeSelections` reads it directly. `matchedSections` carries the
94
95
  // matched section for the slugs that had one (page-1/page-2) — consumed by the
95
96
  // live injector's progressive disclosure, independent of source attribution.
@@ -98,6 +99,7 @@ const orchestrateSpy = mock(
98
99
  selections: [
99
100
  { slug: "page-core", pinned: false },
100
101
  { slug: "page-hot", pinned: false },
102
+ { slug: "page-fresh", pinned: false },
101
103
  { slug: "page-1", pinned: true },
102
104
  { slug: "page-2", pinned: false },
103
105
  { slug: "page-3", pinned: false },
@@ -109,6 +111,7 @@ const orchestrateSpy = mock(
109
111
  lanes: {
110
112
  core: ["page-core"],
111
113
  hot: ["page-hot"],
114
+ fresh: ["page-fresh"],
112
115
  finder: [
113
116
  { slug: "page-1", descriptor: "", lane: "needle" },
114
117
  { slug: "page-2", descriptor: "", lane: "dense" },
@@ -180,6 +183,7 @@ mock.module("../../../../config/loader.js", () => ({
180
183
  enabled: memoryEnabled,
181
184
  v3: {
182
185
  hotSet: { k: 40, halfLifeDays: 14 },
186
+ freshSet: { k: 50 },
183
187
  spotlight: { n: 6, windowTurns: 2 },
184
188
  needleK: 100,
185
189
  denseK: 100,
@@ -463,8 +467,10 @@ describe("memory-v3 shadow plugin", () => {
463
467
  { slug: "page-2", source: "dense", pinned: 0 },
464
468
  // page-3 was surfaced by the edge lane → "edge".
465
469
  { slug: "page-3", source: "edge", pinned: 0 },
466
- // page-core / page-hot sit in the stable prefix → "core" / "hot".
470
+ // page-core / page-hot / page-fresh sit in the stable prefix →
471
+ // "core" / "hot" / "fresh".
467
472
  { slug: "page-core", source: "core", pinned: 0 },
473
+ { slug: "page-fresh", source: "fresh", pinned: 0 },
468
474
  { slug: "page-hot", source: "hot", pinned: 0 },
469
475
  ]);
470
476
  });
@@ -476,6 +482,7 @@ describe("memory-v3 shadow plugin", () => {
476
482
  lanes: {
477
483
  core: ["page-core"],
478
484
  hot: [],
485
+ fresh: [],
479
486
  // The needle also hit the core page this turn — the row still logs
480
487
  // "core" because that is where the candidate lived in the pool.
481
488
  finder: [{ slug: "page-core", descriptor: "", lane: "needle" }],
@@ -598,7 +605,7 @@ describe("memory-v3 shadow plugin", () => {
598
605
  orchestrateSpy.mockImplementationOnce(async () => ({
599
606
  selections: [],
600
607
  matchedSections: new Map(),
601
- lanes: { core: [], hot: [], finder: [] },
608
+ lanes: { core: [], hot: [], fresh: [], finder: [] },
602
609
  }));
603
610
  const block = await produce("conv-1", 0);
604
611
  expect(block).toBeNull();
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Recency fresh-set lane.
3
+ *
4
+ * Returns the top-K page slugs by most-recent on-disk modification
5
+ * (`PageIndexEntry.modifiedAt`). The fresh set keeps *just-written* pages in
6
+ * the candidate pool during the window before the other lanes can reach them:
7
+ * a page consolidated minutes ago has no selection history (so frecency can't
8
+ * rank it into the hot set) and a "what happened today?"-shaped message gives
9
+ * the finder lanes nothing lexical to match it on. Recency is exactly the
10
+ * signal those lanes are missing, so it gets its own lane.
11
+ *
12
+ * Like core and hot, the fresh set is a stable-prefix lane: it is computed at
13
+ * lane init and recomputed only on lane invalidation (the consolidation
14
+ * cadence), so its membership — and therefore the selector's cache-stable
15
+ * prefix — never changes mid-window. Page mtimes move on every consolidation
16
+ * write, which is the same event that invalidates the lanes, so recompute
17
+ * lag is bounded by the consolidation interval.
18
+ *
19
+ * Slugs in `excludeSlugs` (core + hot members) are dropped before the K cut —
20
+ * those pages already sit in the stable prefix, so re-listing them would only
21
+ * spend fresh slots on duplicates. Synthetic capability entries carry
22
+ * `modifiedAt: 0` and are skipped: they have no on-disk write to be fresh by.
23
+ */
24
+
25
+ import type { Slug } from "./types.js";
26
+
27
+ /** The slice of a page-index entry the fresh lane ranks on. */
28
+ export interface FreshSetEntry {
29
+ slug: Slug;
30
+ /** File mtime in epoch ms; `0` for synthetic entries (skills, CLI commands). */
31
+ modifiedAt: number;
32
+ }
33
+
34
+ export interface FreshSetOptions {
35
+ /** Maximum number of slugs returned; `0` disables the lane. */
36
+ k: number;
37
+ /** Slugs excluded from the result (core + hot — fresh never duplicates the
38
+ * rest of the stable prefix). */
39
+ excludeSlugs: Set<string>;
40
+ }
41
+
42
+ /**
43
+ * Compute the top-`k` fresh slugs by file modification time, newest first.
44
+ *
45
+ * Deterministic for fixed inputs: ties break `modifiedAt` desc, then slug asc.
46
+ */
47
+ export function computeFreshSet(
48
+ entries: readonly FreshSetEntry[],
49
+ opts: FreshSetOptions,
50
+ ): Slug[] {
51
+ const { k, excludeSlugs } = opts;
52
+ if (k <= 0) return [];
53
+
54
+ return entries
55
+ .filter((entry) => entry.modifiedAt > 0 && !excludeSlugs.has(entry.slug))
56
+ .sort((a, b) => b.modifiedAt - a.modifiedAt || (a.slug < b.slug ? -1 : 1))
57
+ .slice(0, k)
58
+ .map((entry) => entry.slug);
59
+ }
@@ -301,14 +301,16 @@ export const memoryV3Injector: Injector = {
301
301
  // `produce()` would let a never-attached turn (non-user tail) claim
302
302
  // cards in the store, suppressing them until compaction. The valve is
303
303
  // scheduled after `recordInjected` so the resident accounting includes
304
- // this turn's cards; core/hot lane members are exempt — the selector's
305
- // stable prefix must never be pruned out from under it.
304
+ // this turn's cards; stable-prefix lane members (core/hot/fresh) are
305
+ // exempt — the selector's stable prefix must never be pruned out from
306
+ // under it.
306
307
  const commit = (): void => {
307
308
  recordInjected(ctx.conversationId, entries);
308
309
  schedulePruneValve(ctx.conversationId, {
309
310
  exemptSlugs: new Set<Slug>([
310
311
  ...result.lanes.core,
311
312
  ...result.lanes.hot,
313
+ ...result.lanes.fresh,
312
314
  ]),
313
315
  });
314
316
  };
@@ -10,13 +10,13 @@
10
10
  * Each lane only ever ADDS candidates, so the pool is recall-safe by
11
11
  * construction.
12
12
  * 2. Build the candidate pool in CACHE ORDER: the stable prefix —
13
- * `[...core (file order), ...hot (score order)]`, both computed at lane
14
- * init — followed by the finder candidates (needle → dense → edge
15
- * surfacing order). The stable prefix is identical across consecutive
16
- * turns while the lanes are unchanged (lane invalidation at consolidation
17
- * is the recompute cadence), so the selector input's leading segment
18
- * rides the provider KV cache (the cache breakpoint itself lives in
19
- * `pool-select.ts`).
13
+ * `[...core (file order), ...hot (score order), ...fresh (recency
14
+ * order)]`, all computed at lane init — followed by the finder
15
+ * candidates (needle → dense → edge surfacing order). The stable prefix
16
+ * is identical across consecutive turns while the lanes are unchanged
17
+ * (lane invalidation at consolidation is the recompute cadence), so the
18
+ * selector input's leading segment rides the provider KV cache (the
19
+ * cache breakpoint itself lives in `pool-select.ts`).
20
20
  *
21
21
  * Stable-prefix candidates render as FULL CARDS (`renderCard` — head
22
22
  * section + TOC), pre-rendered at lane init (`prefixCards`) so the
@@ -71,10 +71,13 @@ export interface OrchestrateDeps {
71
71
  /** The frecency hot set in score order (computed at lane init with the core
72
72
  * set excluded). Follows core in the stable prefix. */
73
73
  hotSlugs: Slug[];
74
+ /** The modification-recency fresh set in recency order (computed at lane
75
+ * init with core and hot excluded). Follows hot in the stable prefix. */
76
+ freshSlugs: Slug[];
74
77
  /** Pre-rendered FULL cards for the stable-prefix slugs, keyed by slug.
75
78
  * Rendered ONCE at lane init so the selector's stable prefix is
76
- * byte-identical across turns (the cache contract). Every core/hot slug
77
- * MUST have an entry — a missing card is a lane-init bug and throws
79
+ * byte-identical across turns (the cache contract). Every core/hot/fresh
80
+ * slug MUST have an entry — a missing card is a lane-init bug and throws
78
81
  * (silently degrading would violate the byte-stable-prefix contract). */
79
82
  prefixCards: ReadonlyMap<Slug, string>;
80
83
  /** Number of BM25 needle articles. Defaults to {@link DEFAULT_NEEDLE_K}. */
@@ -101,16 +104,19 @@ export interface FinderCandidate {
101
104
  }
102
105
 
103
106
  /**
104
- * The three candidate lanes in cache order. `core` and `hot` are the stable
105
- * prefix (byte-identical across turns while lanes are unchanged); `finder` is
106
- * the dynamic tail and MAY repeat a stable-prefix slug (a finder hit on a
107
- * core/hot page is kept so its current relevance stays visible downstream).
107
+ * The candidate lanes in cache order. `core`, `hot`, and `fresh` are the
108
+ * stable prefix (byte-identical across turns while lanes are unchanged);
109
+ * `finder` is the dynamic tail and MAY repeat a stable-prefix slug (a finder
110
+ * hit on a stable-prefix page is kept so its current relevance stays visible
111
+ * downstream).
108
112
  */
109
113
  export interface OrchestrateLanes {
110
114
  /** Curated core set, file order. */
111
115
  core: Slug[];
112
116
  /** Frecency hot set, score order (never overlaps core). */
113
117
  hot: Slug[];
118
+ /** Modification-recency fresh set, recency order (never overlaps core/hot). */
119
+ fresh: Slug[];
114
120
  /** Finder candidates in surfacing order, deduped among themselves only. */
115
121
  finder: FinderCandidate[];
116
122
  }
@@ -144,12 +150,15 @@ export async function orchestrate(
144
150
  const denseK = deps.denseK ?? DEFAULT_DENSE_K;
145
151
  const { sections } = deps.sectionIndex;
146
152
 
147
- // The stable prefix: core (file order) then hot (score order). Hot is
148
- // computed with core excluded at lane init; the filter here is a cheap
149
- // defensive dedup so a misbehaving lane can never double-list a slug.
153
+ // The stable prefix: core (file order), hot (score order), fresh (recency
154
+ // order). Hot is computed with core excluded at lane init, fresh with both
155
+ // excluded; the filters here are a cheap defensive dedup so a misbehaving
156
+ // lane can never double-list a slug.
150
157
  const core = deps.coreSlugs;
151
158
  const hot = deps.hotSlugs.filter((slug) => !core.includes(slug));
152
- const stablePrefix = new Set<Slug>([...core, ...hot]);
159
+ const coreHot = new Set<Slug>([...core, ...hot]);
160
+ const fresh = deps.freshSlugs.filter((slug) => !coreHot.has(slug));
161
+ const stablePrefix = new Set<Slug>([...coreHot, ...fresh]);
153
162
 
154
163
  // Step 1: needle (sync BM25) and dense (async embed + Qdrant) lanes run in
155
164
  // parallel. Both return distinct articles each tagged with their best-scoring
@@ -246,7 +255,7 @@ export async function orchestrate(
246
255
  }
247
256
 
248
257
  // Step 2: assemble the selector pool in cache order — the stable prefix
249
- // (core then hot) as FULL CARDS, then the finder tail. Cards are
258
+ // (core, hot, fresh) as FULL CARDS, then the finder tail. Cards are
250
259
  // pre-rendered at lane init (`prefixCards`): query- AND
251
260
  // conversation-state-INDEPENDENT by design, so the rendered prefix is
252
261
  // byte-identical across turns while the lanes are unchanged. The tail is
@@ -254,7 +263,7 @@ export async function orchestrate(
254
263
  // its own snippet line so its CURRENT relevance stays visible; `selectPool`
255
264
  // dedupes selections by slug. Finder candidates with no match text fall
256
265
  // back to the page's lead-section snippet.
257
- const stable: StableCandidate[] = [...core, ...hot].map((slug) => {
266
+ const stable: StableCandidate[] = [...core, ...hot, ...fresh].map((slug) => {
258
267
  const card = deps.prefixCards.get(slug);
259
268
  if (card === undefined) {
260
269
  // Lane init renders a card for every core/hot slug; a hole here means
@@ -283,7 +292,7 @@ export async function orchestrate(
283
292
  return {
284
293
  selections,
285
294
  matchedSections,
286
- lanes: { core, hot, finder },
295
+ lanes: { core, hot, fresh, finder },
287
296
  };
288
297
  }
289
298
 
@@ -50,6 +50,7 @@ import { renderCard } from "./card.js";
50
50
  import { loadCoreSet } from "./core-set.js";
51
51
  import type { EdgeGraph } from "./edge.js";
52
52
  import { buildEdgeGraph } from "./edge.js";
53
+ import { computeFreshSet } from "./fresh-set.js";
53
54
  import { computeHotSet } from "./hot-set.js";
54
55
  import type { OrchestrateResult } from "./orchestrate.js";
55
56
  import { orchestrate } from "./orchestrate.js";
@@ -92,8 +93,11 @@ export interface ShadowLanes {
92
93
  /** Frecency hot set in score order: core excluded, filtered to pages in the
93
94
  * section index. */
94
95
  hotSlugs: string[];
95
- /** Pre-rendered FULL cards for the stable-prefix (core+hot) slugs, keyed by
96
- * slug. Frozen at lane build so the selector's stable prefix is
96
+ /** Modification-recency fresh set in recency order: core and hot excluded,
97
+ * filtered to pages in the section index. */
98
+ freshSlugs: string[];
99
+ /** Pre-rendered FULL cards for the stable-prefix (core+hot+fresh) slugs,
100
+ * keyed by slug. Frozen at lane build so the selector's stable prefix is
97
101
  * byte-identical across turns until the next invalidation. */
98
102
  prefixCards: Map<Slug, string>;
99
103
  }
@@ -189,6 +193,15 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
189
193
  .map((entry) => entry.slug)
190
194
  .filter((slug) => sectionIndex.byArticle.has(slug));
191
195
 
196
+ // Fresh is the modification-recency top-K over the page index with core and
197
+ // hot excluded (fresh never duplicates the rest of the prefix). Page mtimes
198
+ // move at consolidation — the same event that invalidates the lanes — so the
199
+ // set is recomputed exactly when it can have changed.
200
+ const freshSlugs = computeFreshSet(pageIndex.entries, {
201
+ k: config.memory.v3.freshSet.k,
202
+ excludeSlugs: new Set([...coreSlugs, ...hotSlugs]),
203
+ }).filter((slug) => sectionIndex.byArticle.has(slug));
204
+
192
205
  // Pre-render the stable-prefix cards ONCE per lane build: the selector's
193
206
  // stable prefix must be byte-identical across turns to ride the provider KV
194
207
  // cache, so the cards are frozen here (lane invalidation at consolidation is
@@ -196,7 +209,7 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
196
209
  // render their capability content; disk pages render raw (frontmatter +
197
210
  // body) so `kind: index` pages surface their `links:` map in the card TOC.
198
211
  const prefixCards = new Map<Slug, string>();
199
- for (const slug of [...coreSlugs, ...hotSlugs]) {
212
+ for (const slug of [...coreSlugs, ...hotSlugs, ...freshSlugs]) {
200
213
  const raw = await capabilityOrDiskBody(
201
214
  slug,
202
215
  async (s) => (await loadPage(s))?.raw ?? "",
@@ -230,6 +243,7 @@ async function initLanes(config: AssistantConfig): Promise<ShadowLanes> {
230
243
  edgeGraph,
231
244
  coreSlugs,
232
245
  hotSlugs,
246
+ freshSlugs,
233
247
  prefixCards,
234
248
  };
235
249
  }
@@ -325,17 +339,18 @@ interface SelectionRow {
325
339
  /**
326
340
  * Map an orchestrate result onto telemetry rows with per-lane source
327
341
  * attribution, by pool position: a selection of a stable-prefix page is
328
- * attributed `"core"` / `"hot"` (the lane that placed it in the pool), and any
329
- * other selection is attributed the finder lane that FIRST surfaced it
330
- * (`"needle"` / `"dense"` / `"edge"`, recorded at pool-build time). A finder
331
- * hit on a core/hot page therefore still logs as core/hot — the prefix is
332
- * where the candidate lived. (`"needle"` is the fallback if a selected slug is
333
- * somehow absent from every lane, which should not happen since every pooled
334
- * candidate comes from one.)
342
+ * attributed `"core"` / `"hot"` / `"fresh"` (the lane that placed it in the
343
+ * pool), and any other selection is attributed the finder lane that FIRST
344
+ * surfaced it (`"needle"` / `"dense"` / `"edge"`, recorded at pool-build
345
+ * time). A finder hit on a stable-prefix page therefore still logs as its
346
+ * prefix lane — the prefix is where the candidate lived. (`"needle"` is the
347
+ * fallback if a selected slug is somehow absent from every lane, which should
348
+ * not happen since every pooled candidate comes from one.)
335
349
  */
336
350
  export function attributeSelections(result: OrchestrateResult): SelectionRow[] {
337
351
  const core = new Set<Slug>(result.lanes.core);
338
352
  const hot = new Set<Slug>(result.lanes.hot);
353
+ const fresh = new Set<Slug>(result.lanes.fresh);
339
354
  const finderLane = new Map(
340
355
  result.lanes.finder.map((c) => [c.slug, c.lane] as const),
341
356
  );
@@ -345,7 +360,9 @@ export function attributeSelections(result: OrchestrateResult): SelectionRow[] {
345
360
  ? ("core" as const)
346
361
  : hot.has(sel.slug)
347
362
  ? ("hot" as const)
348
- : (finderLane.get(sel.slug) ?? "needle"),
363
+ : fresh.has(sel.slug)
364
+ ? ("fresh" as const)
365
+ : (finderLane.get(sel.slug) ?? "needle"),
349
366
  pinned: sel.pinned ? 1 : 0,
350
367
  }));
351
368
  }
@@ -396,6 +413,7 @@ export async function observeTurn(
396
413
  edgeGraph: lanes.edgeGraph,
397
414
  coreSlugs: lanes.coreSlugs,
398
415
  hotSlugs: lanes.hotSlugs,
416
+ freshSlugs: lanes.freshSlugs,
399
417
  prefixCards: lanes.prefixCards,
400
418
  needleK: v3.needleK,
401
419
  denseK: v3.denseK,
@@ -404,6 +422,22 @@ export async function observeTurn(
404
422
  edgeCap: v3.edge.cap,
405
423
  });
406
424
 
425
+ // A zero-selection turn over a non-trivial pool is unusual enough to be
426
+ // worth a breadcrumb (observed on meta-prompt-shaped system turns): the
427
+ // turn itself proceeds normally — cards already in context still serve it.
428
+ if (result.selections.length === 0) {
429
+ log.info(
430
+ {
431
+ conversationId,
432
+ core: result.lanes.core.length,
433
+ hot: result.lanes.hot.length,
434
+ fresh: result.lanes.fresh.length,
435
+ finder: result.lanes.finder.length,
436
+ },
437
+ "memory-v3: selector returned zero selections",
438
+ );
439
+ }
440
+
407
441
  const rows = attributeSelections(result);
408
442
  writeSelections(conversationId, turnIndex, rows);
409
443
  return result;
@@ -81,8 +81,9 @@ export interface MemoryRoutingTurn {
81
81
  * exactly one place and the runtime list (used for telemetry roll-ups and
82
82
  * source validation) can never drift from the type.
83
83
  *
84
- * `core` / `hot` are the stable-prefix lanes (curated core set, frecency hot
85
- * set); `needle` / `dense` / `edge` are the per-turn finder lanes.
84
+ * `core` / `hot` / `fresh` are the stable-prefix lanes (curated core set,
85
+ * frecency hot set, modification-recency fresh set); `needle` / `dense` /
86
+ * `edge` are the per-turn finder lanes.
86
87
  *
87
88
  * The `memory_v3_selections.source` column is free-text, so tightening this set
88
89
  * needs no migration: any historical rows with retired labels (e.g. the old
@@ -92,6 +93,7 @@ export interface MemoryRoutingTurn {
92
93
  export const SELECTION_SOURCES = [
93
94
  "core",
94
95
  "hot",
96
+ "fresh",
95
97
  "needle",
96
98
  "dense",
97
99
  "edge",
@@ -101,9 +103,9 @@ export type SelectionSource = (typeof SELECTION_SOURCES)[number];
101
103
 
102
104
  /**
103
105
  * The per-turn finder lanes — the strict subset of {@link SelectionSource} a
104
- * finder candidate can be tagged with at pool-build time. (`core` / `hot` are
105
- * assigned by stable-prefix membership, not by a finder.) Defined via
106
- * `Exclude` so it can never drift from {@link SELECTION_SOURCES}: adding a
106
+ * finder candidate can be tagged with at pool-build time. (`core` / `hot` /
107
+ * `fresh` are assigned by stable-prefix membership, not by a finder.) Defined
108
+ * via `Exclude` so it can never drift from {@link SELECTION_SOURCES}: adding a
107
109
  * finder lane there widens this automatically.
108
110
  */
109
- export type FinderLane = Exclude<SelectionSource, "core" | "hot">;
111
+ export type FinderLane = Exclude<SelectionSource, "core" | "hot" | "fresh">;