ceulen 0.28.1 → 0.28.2

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/CHANGELOG.md CHANGED
@@ -1,4 +1,12 @@
1
1
  # Changelog
2
+ ## 0.28.2 — 2026-11-20
3
+
4
+ - DeepSeek V4.1 Flash gets the same minimal-mode bootstrap as V4 Pro, including
5
+ `router/combo/deepseek-v4.1-flash`. The full prompt now returns with the full
6
+ tool catalog after the first assistant reply, even within the same turn.
7
+ Both models get loadout-aware tool guidance for exact paths, file and symbol
8
+ search, codemode batching, and targeted tool discovery.
9
+
2
10
  ## 0.28.1 — 2026-11-18
3
11
 
4
12
  **Serena actually works, and models actually reach for it.** Two independent
@@ -6,9 +6,8 @@
6
6
  // steering with a prompt-rewriting handler fails HERE even if nobody updates
7
7
  // the array-order assertions in registry.test.ts.
8
8
  //
9
- // Live incident class (reviewer 2026-10-06): rtk loaded after steering and
10
- // its before_agent_start appended the RTK note to the ds-anchor's
11
- // byte-identical minimal prompt, silently defeating the anchor.
9
+ // Steering sees the prompt and tool loadout after the other composers run.
10
+ // The minimal prompt itself is applied at the provider boundary.
12
11
 
13
12
  import { describe, it, before, after } from "node:test";
14
13
  import assert from "node:assert/strict";
@@ -63,7 +62,7 @@ describe("before_agent_start registration order (steering contract)", () => {
63
62
  rewroteAfter.map((r) => r.module),
64
63
  [],
65
64
  `before_agent_start registered AFTER steering by: ${rewroteAfter.map((r) => r.module).join(", ")} — ` +
66
- "steering must be the last prompt rewriter (ds-anchor byte-identity). " +
65
+ "steering should see the final composed prompt and loadout. " +
67
66
  `(load failures tolerated: ${failures.length})`,
68
67
  );
69
68
  // Sanity: the harness captured real registrations from many modules.
@@ -83,15 +83,7 @@ describe("deferredTools tiers", () => {
83
83
  });
84
84
 
85
85
  describe("MODULES load order", () => {
86
- // The steering entry must stay behind every before_agent_start prompt
87
- // rewriter (its ds-anchor bootstrap REPLACES the final prompt; a rewriter
88
- // loaded after it would append to the byte-identical minimal prompt, which
89
- // is exactly what serena/web used to do) and ahead of the non-rewriters
90
- // (config). Modules registering before_agent_start and loading BEFORE
91
- // steering: munin, advisor, ux, ponytail, subagent, plan, fff, serena, web,
92
- // rules, rtk — web is the last of them, hence the anchor below. rtk IS a
93
- // prompt rewriter (its before_agent_start appends the RTK note), so it must
94
- // sit before steering or the ds-anchor bootstrap loses byte-identity.
86
+ // Steering sees the prompt and loadout after the other composers run.
95
87
  it("steering is the last prompt rewriter, after rtk, before config", async () => {
96
88
  const { MODULES } = await import("./registry.js");
97
89
  const at = (name: string) => MODULES.findIndex((m) => m.name === name);
@@ -220,22 +220,10 @@ export const MODULES: ModuleEntry[] = [
220
220
  { name: "sg", category: "Tools", describe: "Structural search & rewrite via the ast-grep CLI: ast_grep search, ast_edit dry-run-default rewrites. Registers nothing until ast-grep/sg is installed.", load: sgModule, deferredTools: ["ast_grep", "ast_edit"] },
221
221
  // notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
222
222
  { name: "notify", category: "Tools", describe: "Desktop notification tool: ping the user when long work settles or input is needed (osascript / notify-send / bell).", load: notifyModule, deferredTools: ["notify"] },
223
- // rtk is a PROMPT REWRITER (its before_agent_start appends the RTK note), so
224
- // it must load BEFORE steering — during a ds-anchor bootstrap, steering's
225
- // minimal prompt replaces everything, including this note (byte-identity);
226
- // on the normal path steering composes onto it.
227
- // Steering LAST of the prompt rewriters, i.e. after EVERY before_agent_start
228
- // composer (ponytail/plan/subagent/munin/advisor/ux/fff/serena/web/rules) and
229
- // before the config module (load order is load-bearing even though its
230
- // /config rows live on the Model tab, which PI_TAB_ORDER sorts
231
- // independently): pi chains before_agent_start results, so steering must run
232
- // LAST for its deepseek-v4-pro anchor bootstrap to REPLACE the final prompt
233
- // (byte-identical minimal prompt) instead of appending to a prompt that
234
- // serena/web/rtk then append to. rtk (a prompt rewriter — it appends the
235
- // RTK note) loads BEFORE this entry; nothing after steering touches the
236
- // prompt — do not move rtk back after it or add a prompt rewriter here.
223
+ // Steering sees the prompt and tool loadout after the other composers run
224
+ // (including RTK). The anchor itself rewrites only the first wire payload.
237
225
  { name: "rtk", category: "Shell", describe: "Route shell commands through RTK where RTK supports them; chains and unsupported commands pass through.", load: rtkModule, config: rtkConfig },
238
- { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
226
+ { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): tool guidance, reasoning strip, error recovery, and a minimal-mode anchor for V4 Pro / V4.1 Flash.", load: steeringModule, config: steeringConfig },
239
227
  // ── Shell ──────────────────────────────────────────────────────────────
240
228
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
241
229
  // exist; defers to plan mode via the shared plan-bridge flag (order-free).
@@ -37,7 +37,7 @@ export function buildSteeringGroups(cfg: SteeringSettings): PanelGroup[] {
37
37
  cfg.selectionGuidance = Boolean(v);
38
38
  }, {
39
39
  defaultValue: true,
40
- description: "DeepSeek V4 tool-routing table prepended to the system prompt. Static per session, so the prefix cache stays warm.",
40
+ description: "Shared DeepSeek V4 guidance for file and symbol navigation, batching calls, and tool discovery.",
41
41
  }),
42
42
  row("steering.superpower", "Super Power prompt", "toggle", cfg.superpower, (v) => {
43
43
  cfg.superpower = Boolean(v);
@@ -67,8 +67,8 @@ export function buildSteeringGroups(cfg: SteeringSettings): PanelGroup[] {
67
67
  cfg.dsAnchor = Boolean(v);
68
68
  }, {
69
69
  defaultValue: true,
70
- warning: "deepseek-v4-pro only: request #1 gets a minimal prompt + bash/str_replace_editor only; full catalog returns after the first reply. Repair module must be enabled for the anchor tool pair.",
71
- description: "Two-phase bootstrap that anchors request #1 to the DeepSeek Harness minimal-mode distribution.",
70
+ warning: "V4 Pro and V4.1 Flash: request #1 uses only bash and str_replace_editor when both are declared. The full prompt and catalog return after the first reply.",
71
+ description: "DeepSeek Harness minimal-mode bootstrap. Skipped in plan mode and restricted tool loadouts without the tool pair.",
72
72
  }),
73
73
  row("steering.weNeed", "We-need directive", "toggle", cfg.weNeed, (v) => {
74
74
  cfg.weNeed = Boolean(v);
@@ -10,7 +10,7 @@
10
10
  * fast-mode body) — the "zai" module.
11
11
  *
12
12
  * What stays here is everything that depends on knowing WHICH model family is
13
- * serving the request, plus the DeepSeek v4 Pro minimal-mode anchor:
13
+ * serving the request, plus the DeepSeek V4 Pro / V4.1 Flash minimal-mode anchor:
14
14
  *
15
15
  * 1. family detection (deepseek-v4 | glm), latched from the requested model
16
16
  * and the session-captured one (proxies rewrite ctx.model between hooks).
@@ -23,17 +23,14 @@
23
23
  * 4. tool-error categorization → the next turn's recovery hint, plus the
24
24
  * reasoning-accumulation 400 detector.
25
25
  * 5. DeepSeek-only semantic-miss / dedicated-tool steering on tool_call.
26
- * 6. the ds-anchor two-phase bootstrap for deepseek-v4-pro.
26
+ * 6. the request-scoped ds-anchor two-phase bootstrap.
27
27
  *
28
28
  * ORDERING CONTRACT (why this module is its own unit): in ceulen's registry
29
29
  * `steering` loads AFTER ponytail and subagent, so this `before_agent_start`
30
30
  * handler runs LAST in the chain (each handler's returned systemPrompt becomes
31
- * the next handler's event.systemPrompt). Therefore:
32
- * • the bootstrap branch deliberately REPLACES the whole prompt — everything
33
- * earlier handlers composed is sacrificed for request #1, which is the
34
- * entire point of the anchor;
35
- * • every other branch COMPOSES: the incoming systemPrompt is preserved
36
- * verbatim and only prepended/appended to. Never clobber outside bootstrap.
31
+ * the next handler's event.systemPrompt). Always compose the full prompt here.
32
+ * Replace it only at the wire boundary, atomically with the bootstrap tool pair,
33
+ * so a fail-open or the next tool round gets the original composed prompt.
37
34
  *
38
35
  * Config: the `steering` section of the agent-dir settings.json, overlaid by a
39
36
  * trusted project `.pi/settings.json` (lib/settings.ts), read per turn — so
@@ -71,6 +68,7 @@ import {
71
68
  dshBootstrapTools,
72
69
  hasPromotionSignal,
73
70
  isAnchorTarget,
71
+ withMinimalPrompt,
74
72
  } from "./lib/anchor.js";
75
73
  import {
76
74
  categorizeToolError,
@@ -130,11 +128,12 @@ export default function steeringModule(pi: ExtensionAPI): void {
130
128
  // reinforcement) stashed here and appended to the CURRENT user message by
131
129
  // before_provider_request — never the system prompt (the cache head).
132
130
  let pendingGuidance: string | undefined;
131
+ let bootstrapGuidance: string | undefined;
133
132
  // Effective settings — refreshed per turn (before_agent_start) and at
134
133
  // session_start (the anchor bootstrap keys off dsAnchor/weNeed).
135
134
  let settings: SteeringSettings = readSteeringSettings();
136
135
 
137
- // DeepSeek v4 Pro minimal-mode anchor (two-phase bootstrap) state.
136
+ // DeepSeek V4 Pro / V4.1 Flash minimal-mode anchor state.
138
137
  // Invariant: anchorBootstrapping = dsAnchor && target && !anchorPromoted.
139
138
  let anchorReady = false;
140
139
  let anchorPromoted = false;
@@ -234,7 +233,7 @@ export default function steeringModule(pi: ExtensionAPI): void {
234
233
  ` Strict Serena (DeepSeek V4): ${settings.strictSerena ? `on (block after ${BLOCK_AFTER_REMINDERS} reminders)` : "off"}`,
235
234
  ` Reasoning strip: ${settings.stripReasoning ? "on" : "off"}`,
236
235
  ` Leaked content cleaning: always on for detected families`,
237
- ` ds-anchor (deepseek-v4-pro): ${anchorState}`,
236
+ ` ds-anchor (V4 Pro / V4.1 Flash): ${anchorState}`,
238
237
  ` We-need directive (bootstrap): ${settings.weNeed ? "on" : "off"}`,
239
238
  ` Thinking level: ${currentThinking ?? "unknown"}${currentThinking !== "max" && anchorActive ? " (recipe wants max)" : ""}`,
240
239
  ` Super Power turns: ${turnCounter}`,
@@ -297,6 +296,7 @@ export default function steeringModule(pi: ExtensionAPI): void {
297
296
  cacheStats.hitTurns = 0;
298
297
  cacheStats.missTurns = 0;
299
298
  pendingGuidance = undefined;
299
+ bootstrapGuidance = undefined;
300
300
  });
301
301
 
302
302
  // ── thinking_level_select: track the level (max is required by the DSH recipe) ──
@@ -349,37 +349,26 @@ export default function steeringModule(pi: ExtensionAPI): void {
349
349
  const messageType = (event as { messageType?: string }).messageType;
350
350
  const isCustomRun = messageType === "custom";
351
351
 
352
- // ds-anchor bootstrap: request #1 gets the byte-identical Minimal prompt
353
- // and NO guidance (Super Power, selection guidance, hints all suppressed).
354
- // This handler is LAST in ceulen's chain, so the returned systemPrompt
355
- // REPLACES everything ponytail/subagent/advisor composed — deliberate, and
356
- // the only place this module clobbers rather than composes.
357
- //
358
- // A machine-initiated run must NOT consume the bootstrap: the minimal prompt
359
- // plus bash/str_replace_editor-only tools would run a cron/background task
360
- // under DSH minimal mode. The bootstrap stays pending for the next user turn.
361
- if (isCustomRun && anchorTarget(ctx.model)) {
362
- // Machine-initiated: never engage the bootstrap (trace once, then the
363
- // normal composition path below).
364
- anchorTracePush(`bootstrap skipped: custom-triggered run (promoted=${anchorPromoted})`);
365
- } else if (anchorBootstrapping(ctx.model)) {
352
+ const selected = event.systemPromptOptions?.selectedTools;
353
+ const activeForHint = selected ?? pi.getActiveTools();
354
+ const hidden = event.systemPromptOptions?.hiddenTools;
355
+ const directTools = hidden?.length ? activeForHint.filter((name) => !hidden.includes(name)) : activeForHint;
356
+
357
+ // Read-only child loadouts, codemode-only, plan mode and custom runs keep
358
+ // their prompt and tools. Wire-level validation below is still authoritative.
359
+ anchorRunActive = false;
360
+ if (!isCustomRun && anchorBootstrapping(ctx.model)) {
366
361
  scanAnchorEntries(ctx);
367
- if (!anchorPromoted) {
362
+ if (!anchorPromoted && BOOTSTRAP_TOOLS.every((name) => directTools.includes(name))) {
368
363
  anchorRunActive = true;
369
- pendingGuidance = undefined;
370
- anchorTracePush(`bootstrap: minimal prompt engaged (model=${ctx.model?.id ?? "?"}${settings.weNeed ? ", +we-need directive" : ""})`);
371
- return { systemPrompt: settings.weNeed ? WE_NEED_DIRECTIVE + MINIMAL_SYSTEM_PROMPT : MINIMAL_SYSTEM_PROMPT };
364
+ } else if (!anchorPromoted) {
365
+ anchorTracePush("bootstrap skipped: bash/str_replace_editor not declared");
372
366
  }
373
- // Scan found a durable signal (resume edge) — fall through to the
374
- // normal path: full prompt + full catalog.
375
- anchorTracePush("bootstrap skipped: durable signal found (resume)");
376
- } else if (anchorTarget(ctx.model)) {
377
- anchorTracePush(isPlanActive() && !anchorPromoted
378
- ? "bootstrap deferred: plan mode active (mutator tools blocked)"
379
- : `bootstrap skipped: already promoted=${anchorPromoted}`);
380
367
  }
381
368
 
382
369
  remindedThisTurn = false;
370
+ pendingGuidance = undefined;
371
+ bootstrapGuidance = undefined;
383
372
  if (!activeFamily) return;
384
373
 
385
374
  const dynamicParts: string[] = [];
@@ -397,25 +386,23 @@ export default function steeringModule(pi: ExtensionAPI): void {
397
386
  hasErrorThisTurn = false;
398
387
  lastErrorInfo = null;
399
388
 
400
- // Prompt-aware first-tool hints — ALL families (correctness, not steering).
401
- // Per-turn dynamic (they depend on the current prompt) → user-message tail.
402
- //
403
- // activeForHint is the SAME source on every turn (host selectedTools when
404
- // populated, pi.getActiveTools() otherwise) so the system prompt stays
405
- // byte-identical — a per-turn source switch would invalidate the cache head.
406
- const selected = event.systemPromptOptions?.selectedTools;
407
- const activeForHint: readonly string[] = Array.isArray(selected) && selected.length > 0 ? selected : pi.getActiveTools();
389
+ // Prompt-aware first-tool hints — ALL families. Per-turn dynamic → user-message tail.
408
390
  // Hints heuristically read the USER's task text: a custom-triggered run has
409
391
  // no prompt, and hinting off a machine message would be noise.
410
392
  const runPrompt = !isCustomRun && "prompt" in event ? event.prompt : "";
411
- if (settings.firstToolHints && !isCustomRun && activeForHint.includes("bash")) {
393
+ if (settings.firstToolHints && anchorRunActive && readUncertainPathHint(runPrompt)) {
394
+ bootstrapGuidance = "Resolve the bare filename inside the current workspace with bash (`find . -name ...`), not by searching from `/`.";
395
+ }
396
+ if (settings.firstToolHints && !isCustomRun && directTools.includes("bash")) {
412
397
  const runHint = runTaskFirstToolHint(runPrompt);
413
398
  if (runHint) dynamicParts.push(runHint);
414
399
  const ghHint = githubCloneFirstToolHint(runPrompt);
415
400
  if (ghHint) dynamicParts.push(ghHint);
416
401
  }
417
- if (settings.firstToolHints && !isCustomRun && activeForHint.includes("find")) {
418
- const readHint = readUncertainPathHint(runPrompt);
402
+ const pathFinder = directTools.includes("fffind") && activeFamily === "deepseek-v4" ? "fffind"
403
+ : directTools.includes("find") ? "find" : undefined;
404
+ if (settings.firstToolHints && !isCustomRun && pathFinder && directTools.includes("read")) {
405
+ const readHint = readUncertainPathHint(runPrompt, pathFinder);
419
406
  if (readHint) dynamicParts.push(readHint);
420
407
  }
421
408
 
@@ -434,8 +421,7 @@ export default function steeringModule(pi: ExtensionAPI): void {
434
421
  if (patchHint) systemPrompt = `${systemPrompt}\n\n${patchHint}`;
435
422
  }
436
423
 
437
- // DeepSeek-only: Super Power Mode + verbose selection guidance (DeepSeek V4
438
- // needs the full steering block; GLM reaches 100% with prompt-aware hints alone).
424
+ // DeepSeek-only: Super Power Mode + compact selection guidance.
439
425
  if (activeFamily === "deepseek-v4") {
440
426
  const prefixParts: string[] = [];
441
427
 
@@ -448,9 +434,8 @@ export default function steeringModule(pi: ExtensionAPI): void {
448
434
  }
449
435
 
450
436
  if (settings.selectionGuidance) {
451
- if (["serena_get_symbols_overview", "serena_find_symbol", "serena_find_referencing_symbols", "serena_find_declaration", "serena_find_implementations", "obsidian", "ls", "grep", "find", "read", "edit", "bash"].some((n) => activeForHint.includes(n))) {
452
- prefixParts.push(deepSeekSelectionGuidance(activeForHint));
453
- }
437
+ const guidance = deepSeekSelectionGuidance(activeForHint, directTools);
438
+ if (guidance) prefixParts.push(guidance);
454
439
  }
455
440
 
456
441
  if (prefixParts.length > 0) {
@@ -475,21 +460,25 @@ export default function steeringModule(pi: ExtensionAPI): void {
475
460
  if (anchorBootstrapping(ctx.model) && anchorRunActive) {
476
461
  const p = payload as Record<string, unknown> | undefined;
477
462
  const filtered = dshBootstrapTools(p?.tools);
478
- if (!filtered.ok) {
463
+ const minimal = filtered.ok && withMinimalPrompt(p, settings.weNeed ? WE_NEED_DIRECTIVE + MINIMAL_SYSTEM_PROMPT : MINIMAL_SYSTEM_PROMPT);
464
+ if (!minimal) {
465
+ const reason = filtered.reason ?? "system prompt unavailable in payload";
479
466
  anchorPromoted = true; // fail-open
480
- anchorTracePush(`FAIL-OPEN: ${filtered.reason}`);
481
- warnAnchorOnce(ctx, `steering: ds-anchor ${filtered.reason}; bootstrap disabled, full catalog exposed`);
467
+ anchorRunActive = false;
468
+ anchorTracePush(`FAIL-OPEN: ${reason}`);
469
+ warnAnchorOnce(ctx, `steering: ds-anchor ${reason}; bootstrap disabled, full prompt and catalog preserved`);
482
470
  } else {
483
471
  // max_tokens: the DSH captured minimal-mode payload sent 256000, and
484
472
  // dsh-anchored-standard issue #11 isolated the output budget as a
485
473
  // trajectory lever. Match it on the bootstrap request only. Exactly one
486
474
  // budget field is emitted — the other is dropped from the spread so a
487
475
  // payload carrying both can't send conflicting fields.
488
- const other = p?.max_completion_tokens !== undefined ? "max_completion_tokens" : "max_tokens";
476
+ const other = minimal.max_completion_tokens !== undefined ? "max_completion_tokens" : "max_tokens";
489
477
  const dropped = other === "max_tokens" ? "max_completion_tokens" : "max_tokens";
490
- const { [dropped]: _omit, ...rest } = p ?? {};
491
- payload = { ...rest, tools: filtered.tools, [other]: BOOTSTRAP_MAX_TOKENS };
492
- anchorTracePush(`payload: tools=[bash,str_replace_editor] + ${other}=${BOOTSTRAP_MAX_TOKENS} sent to ${ctx.model?.id ?? "?"}`);
478
+ const { [dropped]: _omit, ...rest } = minimal;
479
+ const maxTokens = Math.min(BOOTSTRAP_MAX_TOKENS, ctx.model?.maxTokens ?? BOOTSTRAP_MAX_TOKENS);
480
+ payload = { ...rest, tools: filtered.tools, [other]: maxTokens };
481
+ anchorTracePush(`bootstrap: minimal prompt engaged; tools=[bash,str_replace_editor] + ${other}=${maxTokens} sent to ${ctx.model?.id ?? "?"}`);
493
482
  }
494
483
  }
495
484
  // Append per-turn dynamic guidance to the current user message (request
@@ -499,8 +488,9 @@ export default function steeringModule(pi: ExtensionAPI): void {
499
488
  // prompt): mid-turn rounds end with tool results, where re-appending the
500
489
  // hint reads as a fresh repeated demand and loops strict models into
501
490
  // re-running bash ("I've been complying") instead of settling.
502
- if (pendingGuidance && tailIsPlainUserPrompt(payload)) {
503
- const withGuidance = appendGuidanceToLastUserMessage(payload, pendingGuidance);
491
+ const guidance = anchorRunActive ? bootstrapGuidance : pendingGuidance;
492
+ if (guidance && tailIsPlainUserPrompt(payload)) {
493
+ const withGuidance = appendGuidanceToLastUserMessage(payload, guidance);
504
494
  if (withGuidance !== payload) payload = withGuidance;
505
495
  }
506
496
  payload = cleanLeakedContentFromMessages(payload, pi.getAllTools().map((t) => t.name));
@@ -1,5 +1,5 @@
1
1
  /**
2
- * anchor.ts — DeepSeek v4 Pro "minimal-mode anchor" (two-phase bootstrap).
2
+ * anchor.ts — DeepSeek V4 Pro / V4.1 Flash minimal-mode bootstrap.
3
3
  *
4
4
  * DeepSeek v4 Pro GA appears overfitted to DeepSeek Harness (DSH) "minimal
5
5
  * mode": a byte-stable system prompt of one line + only bash/str_replace_editor
@@ -10,9 +10,8 @@
10
10
  * Two-phase design ported from hank9999/pi-ds-anchored (MIT), itself from
11
11
  * xiaobright/dsh-anchored-standard (Project2 benchmark: 98/99).
12
12
  *
13
- * Fail-open by design: any surprise (no session access, malformed payload,
14
- * missing bash/str_replace_editor) disables filtering and exposes the full
15
- * catalog rather than breaking the session.
13
+ * Fail-open by design: if the wire prompt or tool pair isn't available, leave
14
+ * both untouched.
16
15
  */
17
16
  // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5
18
17
  // (extensions/lib/ds-anchor.ts). Local change: anchorEnabled() /
@@ -84,14 +83,29 @@ export const DSH_BOOTSTRAP_TOOL_DEFS = [
84
83
  },
85
84
  ] as const;
86
85
 
87
- const TARGET_FRAGMENT = "deepseek-v4-pro";
86
+ const TARGET_PATTERN = /deepseek-v4-pro|deepseek-v4\.1-flash/i;
88
87
 
89
88
  /** The directive block, prepended verbatim when `steering.weNeed` is on. */
90
89
  export const WE_NEED_DIRECTIVE = "When you think, start each thinking paragraph with \"We need…\".\n\n";
91
90
 
92
- /** Target = model ids containing "deepseek-v4-pro" (case-insensitive). */
91
+ /** Match Pro and V4.1 Flash even behind router prefixes or revision suffixes. */
93
92
  export function isAnchorTarget(modelId?: string): boolean {
94
- return typeof modelId === "string" && modelId.toLowerCase().includes(TARGET_FRAGMENT);
93
+ return typeof modelId === "string" && TARGET_PATTERN.test(modelId);
94
+ }
95
+
96
+ /** Replace the wire prompt, not Pi's run-wide prompt. Unknown shapes fail open. */
97
+ export function withMinimalPrompt(payload: Record<string, unknown> | undefined, prompt: string): Record<string, unknown> | undefined {
98
+ if (!payload) return undefined;
99
+ // Anthropic Messages carries the prompt separately from the conversation.
100
+ if (typeof payload.system === "string") return { ...payload, system: prompt };
101
+ if (Array.isArray(payload.system)) return { ...payload, system: [{ type: "text", text: prompt }] };
102
+ // The router uses Chat Completions. Preserve the role and any message metadata.
103
+ if (!Array.isArray(payload.messages)) return undefined;
104
+ const [head, ...rest] = payload.messages;
105
+ if ((head?.role === "system" || head?.role === "developer") && typeof head.content === "string") {
106
+ return { ...payload, messages: [{ ...head, content: prompt }, ...rest] };
107
+ }
108
+ return undefined;
95
109
  }
96
110
 
97
111
  export interface AnchorEntry {
@@ -3,9 +3,8 @@
3
3
  * and Super Power Mode.
4
4
  *
5
5
  * Gating lives in index.ts: the apply_patch preference hint (edit +
6
- * create-file steering) covers DeepSeek V4 + GLM; the verbose selection
7
- * guidance and Super Power Mode stay DeepSeek-only (eval: GLM reaches full
8
- * tool-selection accuracy without them).
6
+ * create-file steering) covers DeepSeek V4 + GLM; the selection guidance
7
+ * and Super Power Mode stay DeepSeek-only.
9
8
  */
10
9
  // ponytail: vendored from @bacnh85/pi-model-tools 0.9.5
11
10
  // (extensions/lib/guidance.ts). Local change: the env-toggle helpers
@@ -24,35 +23,31 @@ export function clearGuidanceCache(): void {
24
23
  guidanceCache.clear();
25
24
  }
26
25
 
27
- export function deepSeekSelectionGuidance(activeTools: readonly string[]): string {
28
- const cacheKey = [...activeTools].sort().join(",");
26
+ export function deepSeekSelectionGuidance(activeTools: readonly string[], directTools = activeTools): string {
27
+ const cacheKey = `${[...activeTools].sort().join(",")}|${[...directTools].sort().join(",")}`;
29
28
  const cached = guidanceCache.get(cacheKey);
30
- if (cached) return cached;
31
-
32
- const serenaActive = activeTools.some((tool) => tool.startsWith("serena_"));
33
- // Compact routing table — the ONLY part that proved useful in eval (the
34
- // verbose serena descriptions duplicate Pi's own tool descriptions; the
35
- // NEVER/BLOCKED block duplicates the runtime tool_call hook; GitHub-clone is
36
- // handled by the dynamic githubCloneFirstToolHint). Eval (2026-08-04):
37
- // guidance ON vs OFF showed identical 60% first-tool accuracy, so the verbose
38
- // form was pure prefix cost. This compact form keeps the routing value at 1/3
39
- // the token cost.
40
- const lines: string[] = [
41
- "DeepSeek V4 — pick the right tool on the first try:",
42
- ' • "run tests" / "build" / "lint" → bash (NOT find/ls/read first)',
43
- ' • "list files in <dir>" → ls',
44
- ' • "find test files" / "find *.ts files" → find',
45
- ' • "search README/docs/config for <text>" → grep',
46
- ' • bare filename, path uncertain → find before read (never guess a path)',
47
- ' • read a verified path → read; create a file → write (not bash echo >)',
48
- ];
49
- if (serenaActive) {
50
- lines.push(' • "definition of <name>" → serena_find_symbol');
51
- lines.push(' • "references/usages of <name>" → serena_find_referencing_symbols');
52
- lines.push(' • "outline symbols in <file>" → serena_get_symbols_overview');
53
- }
54
-
55
- const result = lines.join("\n");
29
+ if (cached !== undefined) return cached;
30
+
31
+ const has = (name: string) => activeTools.includes(name);
32
+ const finder = has("fffind") ? "fffind" : has("find") ? "find" : undefined;
33
+ const search = has("ffgrep") ? "ffgrep" : has("grep") ? "grep" : undefined;
34
+ const lines = [
35
+ has("bash") && '"run tests" / build / lint → bash; run a known command without discovery first.',
36
+ has("ls") && '"list files in <dir>" → ls',
37
+ finder && `Find files by name or glob → ${finder}`,
38
+ search && `Search literal text in docs, config, or source → ${search}`,
39
+ has("read") && "Exact path supplied → read it directly; don't inventory the repo first.",
40
+ finder && has("read") && `Bare filename, path uncertain → ${finder} before read; never guess a path.`,
41
+ has("write") && "Create a new file → write, not shell redirects.",
42
+ has("serena_find_symbol") && "Named code symbol → serena_find_symbol",
43
+ has("serena_find_referencing_symbols") && "Symbol usages → serena_find_referencing_symbols",
44
+ has("serena_get_symbols_overview") && "File symbol outline → serena_get_symbols_overview",
45
+ directTools.includes("codemode") && "Batch independent calls (e.g. reads of known paths) in one codemode script with Promise.allSettled; await dependencies in order. For one simple call, use the direct tool if declared.",
46
+ directTools.includes("codemode") && directTools.length < activeTools.length && "For tools not declared directly, call them through codemode (tools.<name>(args)).",
47
+ directTools.includes("tool_search") && "To load a deferred tool for direct use, make one targeted tool_search, then call the match.",
48
+ ].filter(Boolean);
49
+
50
+ const result = lines.length ? `DeepSeek V4 — pick the right tool on the first try:\n • ${lines.join("\n • ")}` : "";
56
51
  if (guidanceCache.size >= 100) {
57
52
  const first = guidanceCache.keys().next().value;
58
53
  if (first !== undefined) guidanceCache.delete(first);
@@ -112,7 +107,7 @@ export function runTaskFirstToolHint(prompt: string): string | undefined {
112
107
  * exact dir/file path. Why: DeepSeek V4 Flash non-deterministically guesses
113
108
  * dir/filename and calls read, hitting the path-not-found block.
114
109
  */
115
- export function readUncertainPathHint(prompt: string): string | undefined {
110
+ export function readUncertainPathHint(prompt: string, finder: "find" | "fffind" = "find"): string | undefined {
116
111
  const p = (prompt || "").toLowerCase();
117
112
  const isReadTask = /\b(read|show|open|view|display|cat|head|tail|first \d+ lines?|last \d+ lines?|top \d+ lines?)\b/.test(p);
118
113
  if (!isReadTask) return undefined;
@@ -123,7 +118,7 @@ export function readUncertainPathHint(prompt: string): string | undefined {
123
118
  const files = p.match(new RegExp("\\b[a-z0-9_-]+\\." + codeExt + "\\b", "g")) || [];
124
119
  const hasBareCodeFile = files.some((f) => !p.includes("/" + f));
125
120
  if (!hasBareCodeFile) return undefined;
126
- return "⚠️ THIS request reads a source file referenced only by a bare filename with no directory path — its exact location is uncertain. Call find FIRST to resolve the path, THEN read the exact path find returns. Do NOT guess the path and call read first (a guessed path that doesn't exist is a blocked, wasted turn).";
121
+ return `Call ${finder} FIRST to resolve the bare filename, then read the exact path it returns. Do not guess the directory.`;
127
122
  }
128
123
 
129
124
  /**
@@ -13,7 +13,7 @@
13
13
  // "superpowerPrompt": "", // custom text; empty = built-in
14
14
  // "strictSerena": false, // escalate dedicated-tool misses to a block
15
15
  // "stripReasoning": true, // drop accumulated reasoning_content
16
- // "dsAnchor": true, // deepseek-v4-pro minimal-mode bootstrap
16
+ // "dsAnchor": true, // V4 Pro / V4.1 Flash minimal-mode bootstrap
17
17
  // "weNeed": false, // A/B: "We need…" bootstrap directive
18
18
  // "thinkTool": false // register the OMP-parity think scratchpad
19
19
  // }
@@ -11,7 +11,7 @@ import { createFakePi, isolateAgentDir } from "./harness.js";
11
11
  import { setPlanActive } from "../../../lib/plan-bridge.ts";
12
12
 
13
13
  const MINIMAL = "You are a helpful software engineer assistant.";
14
- const PRO = "deepseek-v4-pro";
14
+ const TARGET = "combo/deepseek-v4.1-flash";
15
15
  // Plan-mode-shaped catalog: reads + plan tools, NO mutator pair.
16
16
  const PLAN_TOOLS = ["read", "bash", "grep", "find", "ls", "write_plan", "ask_user_question"];
17
17
 
@@ -24,14 +24,14 @@ describe("ds-anchor × plan mode", () => {
24
24
  setPlanActive(true);
25
25
  const h = createFakePi(PLAN_TOOLS);
26
26
  h.setEntries([]);
27
- h.fire("session_start", {}, h.ctx(PRO));
27
+ h.fire("session_start", {}, h.ctx(TARGET));
28
28
 
29
- const r = h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
29
+ const r = h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(TARGET));
30
30
  assert.notEqual(r?.systemPrompt, MINIMAL, "no minimal prompt while planning");
31
31
  assert.ok(r?.systemPrompt === undefined || r.systemPrompt.includes("FULL PI PROMPT"), "composed prompt preserved (plan contract survives)");
32
32
 
33
33
  // The payload that triggered the live bug: plan-filtered catalog without str_replace_editor.
34
- const out = h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
34
+ const out = h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(TARGET));
35
35
  assert.equal(out?.tools, undefined, "no tool substitution while planning");
36
36
  assert.equal(out?.max_tokens, undefined, "no budget pin while planning");
37
37
  assert.equal(h.notifications.length, 0, "no fail-open warning");
@@ -39,27 +39,28 @@ describe("ds-anchor × plan mode", () => {
39
39
 
40
40
  it("bootstrap engages on the first post-exit turn when no assistant reply landed", () => {
41
41
  setPlanActive(true);
42
- const h = createFakePi(PLAN_TOOLS);
42
+ const h = createFakePi([...PLAN_TOOLS, "str_replace_editor"]);
43
43
  h.setEntries([]);
44
- h.fire("session_start", {}, h.ctx(PRO));
45
- h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
46
- h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
44
+ h.fire("session_start", {}, h.ctx(TARGET));
45
+ h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(TARGET));
46
+ h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(TARGET));
47
47
  assert.equal(h.notifications.length, 0, "still no warning after exit");
48
48
 
49
49
  setPlanActive(false);
50
- const r2 = h.fire("before_agent_start", { prompt: "now do it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
51
- assert.equal(r2?.systemPrompt, MINIMAL, "plan exit with no durable reply → bootstrap fires");
50
+ h.fire("before_agent_start", { prompt: "now do it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(TARGET));
51
+ const out = h.fire("before_provider_request", { payload: { messages: [{ role: "system", content: "FULL PI PROMPT" }], tools: [{ name: "bash" }, { name: "str_replace_editor" }] } }, h.ctx(TARGET));
52
+ assert.equal(out.messages[0].content, MINIMAL, "plan exit with no durable reply → bootstrap fires");
52
53
  });
53
54
 
54
55
  it("plan-mode assistant replies promote naturally (no post-exit re-anchor)", () => {
55
56
  setPlanActive(true);
56
57
  const h = createFakePi(PLAN_TOOLS);
57
58
  h.setEntries([]);
58
- h.fire("session_start", {}, h.ctx(PRO));
59
+ h.fire("session_start", {}, h.ctx(TARGET));
59
60
  h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "text" }] } }]);
60
61
 
61
62
  setPlanActive(false);
62
- const r = h.fire("before_agent_start", { prompt: "execute", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
63
+ const r = h.fire("before_agent_start", { prompt: "execute", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(TARGET));
63
64
  assert.notEqual(r?.systemPrompt, MINIMAL, "history diverged from DSH distribution — no re-anchor");
64
65
  });
65
66
 
@@ -67,7 +68,7 @@ describe("ds-anchor × plan mode", () => {
67
68
  setPlanActive(true);
68
69
  const h = createFakePi(PLAN_TOOLS);
69
70
  h.setEntries([]);
70
- h.fire("session_start", {}, h.ctx(PRO));
71
- assert.ok(h.status(h.ctx(PRO)).includes("deferred (plan mode)"));
71
+ h.fire("session_start", {}, h.ctx(TARGET));
72
+ assert.ok(h.status(h.ctx(TARGET)).includes("deferred (plan mode)"));
72
73
  });
73
74
  });
@@ -12,6 +12,9 @@ import { describe, it } from "node:test";
12
12
  import { createFakePi } from "./harness.js";
13
13
 
14
14
  const MINIMAL = "You are a helpful software engineer assistant.";
15
+ const payload = { messages: [{ role: "system", content: "FULL" }], tools: [{ name: "bash" }, { name: "str_replace_editor" }, { name: "edit" }] };
16
+ const wirePrompt = (h: ReturnType<typeof createFakePi>, ctx: any) =>
17
+ h.fire("before_provider_request", { payload }, ctx)?.messages?.[0].content ?? payload.messages[0].content;
15
18
 
16
19
  describe("ds-anchor regressions", () => {
17
20
  it("model_select away from target keeps the anchor inert (no stale sessionModel re-engage)", () => {
@@ -32,8 +35,8 @@ describe("ds-anchor regressions", () => {
32
35
  h.setEntries([]);
33
36
  h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
34
37
  h.fire("model_select", { model: { id: "deepseek-v4-pro" }, previousModel: undefined, source: "set" }, h.ctx("deepseek-v4-pro"));
35
- const r = h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
36
- assert.equal(r?.systemPrompt, MINIMAL, "switch to pro engages the bootstrap");
38
+ h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
39
+ assert.equal(wirePrompt(h, h.ctx("deepseek-v4-pro")), MINIMAL, "switch to pro engages the bootstrap");
37
40
  });
38
41
 
39
42
  it("turn_end with stopReason error does NOT promote (retry stays anchored)", () => {
@@ -42,8 +45,8 @@ describe("ds-anchor regressions", () => {
42
45
  h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
43
46
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
44
47
  h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "error", content: [] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
45
- const r = h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
46
- assert.equal(r?.systemPrompt, MINIMAL, "error reply must not promote; retry re-anchors");
48
+ h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
49
+ assert.equal(wirePrompt(h, h.ctx("deepseek-v4-pro")), MINIMAL, "error reply must not promote; retry re-anchors");
47
50
  });
48
51
 
49
52
  it("turn_end with stopReason aborted does NOT promote", () => {
@@ -52,8 +55,8 @@ describe("ds-anchor regressions", () => {
52
55
  h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
53
56
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
54
57
  h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "aborted", content: [] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
55
- const r = h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
56
- assert.equal(r?.systemPrompt, MINIMAL, "aborted reply must not promote");
58
+ h.fire("before_agent_start", { prompt: "retry", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
59
+ assert.equal(wirePrompt(h, h.ctx("deepseek-v4-pro")), MINIMAL, "aborted reply must not promote");
57
60
  });
58
61
 
59
62
  it("turn_end with a real reply promotes", () => {
@@ -62,8 +65,8 @@ describe("ds-anchor regressions", () => {
62
65
  h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
63
66
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
64
67
  h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", stopReason: "stop", content: [{ type: "toolCall" }] }, toolResults: [] }, h.ctx("deepseek-v4-pro"));
65
- const r = h.fire("before_agent_start", { prompt: "next", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
66
- assert.notEqual(r?.systemPrompt, MINIMAL, "durable reply promotes");
68
+ h.fire("before_agent_start", { prompt: "next", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
69
+ assert.notEqual(wirePrompt(h, h.ctx("deepseek-v4-pro")), MINIMAL, "durable reply promotes");
67
70
  });
68
71
 
69
72
  it("anchorTrace resets per session", () => {
@@ -71,6 +74,7 @@ describe("ds-anchor regressions", () => {
71
74
  h.setEntries([]);
72
75
  h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
73
76
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
77
+ wirePrompt(h, h.ctx("deepseek-v4-pro"));
74
78
  let s = h.status(h.ctx("deepseek-v4-pro"));
75
79
  assert.match(s, /bootstrap: minimal prompt engaged/, "trace populated in session 1");
76
80
  // new session
@@ -79,18 +83,6 @@ describe("ds-anchor regressions", () => {
79
83
  assert.doesNotMatch(s, /bootstrap: minimal prompt engaged/, "trace does not leak across sessions");
80
84
  });
81
85
 
82
- it("budget pin emits exactly one field and drops the other", () => {
83
- const h = createFakePi();
84
- h.setEntries([]);
85
- h.fire("session_start", {}, h.ctx("deepseek-v4-pro"));
86
- h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
87
- const out = h.fire("before_provider_request", {
88
- payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }], max_tokens: 8192, max_completion_tokens: 8192 },
89
- }, h.ctx("deepseek-v4-pro"));
90
- assert.equal(out.max_completion_tokens, 256000, "budget pinned on the field the payload already carries");
91
- assert.equal(out.max_tokens, undefined, "conflicting max_tokens dropped");
92
- });
93
-
94
86
  // pi 1.2.0: before_agent_start also fires for sendMessage({triggerTurn: true})
95
87
  // runs (cron fires, auto-bg receipts) with messageType "custom" and NO prompt.
96
88
  it("a custom-triggered run does NOT consume the bootstrap; the next user turn still gets it", () => {
@@ -107,8 +99,8 @@ describe("ds-anchor regressions", () => {
107
99
  assert.equal(out?.tools, undefined, "custom run keeps the full tool catalog");
108
100
  assert.equal(out?.max_tokens, undefined, "custom run gets no budget pin");
109
101
  // the bootstrap stayed pending for the next user turn
110
- const user = h.fire("before_agent_start", { messageType: "user", prompt: "do a task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
111
- assert.equal(user?.systemPrompt, MINIMAL, "the next USER turn still bootstraps");
102
+ h.fire("before_agent_start", { messageType: "user", prompt: "do a task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-pro"));
103
+ assert.equal(wirePrompt(h, h.ctx("deepseek-v4-pro")), MINIMAL, "the next USER turn still bootstraps");
112
104
  });
113
105
 
114
106
  it("a custom-triggered run gets no first-tool hints (no prompt to read)", () => {
@@ -1,99 +1,82 @@
1
- // Lifecycle test, adapted from pi-model-tools
2
- // extensions/test/unit/ds-anchor-wiring.test.ts: the real module is wired into a
3
- // stub ExtensionAPI and the anchor lifecycle is driven directly —
4
- // session_start → before_agent_start (#1 bootstrap) → before_provider_request
5
- // (tool filter) → tool_call (bootstrap tool gate) → turn_end (promote) →
6
- // before_agent_start #2 (full prompt path).
1
+ // Drive the same bootstrap lifecycle for both target model IDs.
2
+ import assert from "node:assert/strict";
3
+ import { after, before, it } from "node:test";
4
+ import { createFakePi, isolateAgentDir, setSteeringSettings } from "./harness.js";
5
+ import { BOOTSTRAP_TOOLS, MINIMAL_SYSTEM_PROMPT, WE_NEED_DIRECTIVE } from "../lib/anchor.js";
7
6
 
8
- import assert from "node:assert";
9
- import { after, before } from "node:test";
10
- import { createFakePi, isolateAgentDir } from "./harness.js";
11
-
12
- let restoreAgentDir: () => void;
13
- before(() => { restoreAgentDir = isolateAgentDir("ceulen-steering-wiring-").restore; });
14
- after(() => { restoreAgentDir(); });
15
-
16
- const MINIMAL = "You are a helpful software engineer assistant.";
17
7
  const PRO = "deepseek-v4-pro-0813";
8
+ const FLASH = "combo/deepseek-v4.1-flash";
9
+ const TOOLS = ["bash", "str_replace_editor", "read", "find", "apply_patch", "codemode"];
10
+ let isolated: ReturnType<typeof isolateAgentDir>;
11
+ before(() => { isolated = isolateAgentDir("ceulen-steering-wiring-"); });
12
+ after(() => isolated.restore());
18
13
 
19
- // 1. session_start with a target model, empty durable history
20
- const h = createFakePi(["bash", "read", "edit", "grep"]);
21
- h.setEntries([]);
22
- h.fire("session_start", {}, h.ctx(PRO));
23
-
24
- // 2. first agent run → bootstrap: minimal prompt, no guidance
25
- const r1 = h.fire("before_agent_start", { prompt: "do a task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
26
- assert.equal(r1?.systemPrompt, MINIMAL, "request #1 gets the Minimal prompt");
27
-
28
- // 3. provider request → tools replaced with the byte-exact DSH Minimal pair
29
- const payload = { model: PRO, messages: [], tools: [
30
- { name: "bash", parameters: {} }, { name: "str_replace_editor", parameters: {} },
31
- { name: "edit", parameters: {} }, { name: "read", parameters: {} }, { name: "grep", parameters: {} },
32
- ] };
33
- const out = h.fire("before_provider_request", { payload }, h.ctx(PRO));
34
- assert.deepEqual(out.tools.map((t: any) => t?.function?.name ?? t?.name), ["bash", "str_replace_editor"], "payload tools replaced with the DSH Minimal pair (flat shape preserved)");
35
- assert.equal(out.tools[0].description.length > 100, true, "DSH bash description is present");
36
- assert.equal(out.tools[1].parameters.properties.command.enum.length, 4, "str_replace_editor command enum present");
37
- assert.equal(out.tools[1].strict, undefined, "no strict field (DSH schema has none)");
38
- assert.equal(out.max_tokens, 256000, "bootstrap budget matches DSH's captured payload");
39
-
40
- // 4. tool_call during bootstrap: a name outside the pair is blocked, the pair passes
41
- const blocked = h.fire("tool_call", { toolName: "read", input: {} }, h.ctx(PRO));
42
- assert.equal(blocked?.block, true, "hidden tool (read) blocked during bootstrap");
43
- const blockedEdit = h.fire("tool_call", { toolName: "edit", input: {} }, h.ctx(PRO));
44
- assert.equal(blockedEdit?.block, true, "hidden tool (edit) blocked during bootstrap");
45
- const okBash = h.fire("tool_call", { toolName: "bash", input: { command: "ls" } }, h.ctx(PRO));
46
- assert.equal(okBash, undefined, "bash allowed during bootstrap");
47
- const okEditor = h.fire("tool_call", { toolName: "str_replace_editor", input: { command: "view", path: "/x" } }, h.ctx(PRO));
48
- assert.equal(okEditor, undefined, "str_replace_editor allowed during bootstrap");
49
-
50
- // 5. assistant reply lands durably → the next before_agent_start scan promotes
51
- h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "toolCall" }] } }]);
52
- h.fire("turn_end", { turnIndex: 0, message: { role: "assistant", content: [] }, toolResults: [] }, h.ctx(PRO));
53
-
54
- // 6. second agent run → NOT minimal; full-prompt path (returns undefined when unchanged)
55
- const r2 = h.fire("before_agent_start", { prompt: "next task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
56
- assert.notEqual(r2?.systemPrompt, MINIMAL, "request #2 uses the full prompt");
57
-
58
- // 7. provider request #2 → tools NOT filtered, budget NOT pinned
59
- const out2 = h.fire("before_provider_request", { payload }, h.ctx(PRO));
60
- assert.equal(out2?.tools, undefined, "no tool filtering after promotion (payload untouched or guidance-only)");
61
- assert.notEqual(out2?.max_tokens, 256000, "budget pin is bootstrap-only");
62
-
63
- // 8. non-target model: anchor inert from the start
64
- h.setEntries([]);
65
- h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
66
- const rFlash = h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx("deepseek-v4-flash"));
67
- assert.notEqual(rFlash?.systemPrompt, MINIMAL, "flash model: normal guidance path, no anchor");
68
- assert.ok(rFlash.systemPrompt.includes("FULL PI PROMPT"), "flash keeps the full prompt");
69
-
70
- // 9. resume edge: target session with existing assistant reply → instantly promoted
71
- h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "text" }] } }]);
72
- h.fire("session_start", {}, h.ctx(PRO));
73
- const rResume = h.fire("before_agent_start", { prompt: "continue", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
74
- assert.notEqual(rResume?.systemPrompt, MINIMAL, "resumed session with replies: no bootstrap");
75
- assert.ok(rResume.systemPrompt.includes("FULL PI PROMPT"), "resumed session keeps the full prompt");
14
+ for (const id of [PRO, FLASH]) {
15
+ it(`${id}: anchors request #1 only, then restores the full composed prompt and catalog in the same turn`, () => {
16
+ const h = createFakePi(TOOLS);
17
+ const ctx = h.ctx(id);
18
+ h.fire("session_start", {}, ctx);
19
+ const { systemPrompt } = h.fire("before_agent_start", { prompt: "Read limits.ts", systemPrompt: "FULL PI PROMPT" }, ctx);
20
+ assert.match(systemPrompt, /FULL PI PROMPT/);
21
+ assert.match(systemPrompt, /Batch independent calls/);
22
+ const payload = { model: id, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: "Read limits.ts" }], tools: TOOLS.map((name) => ({ function: { name } })), max_tokens: 384000 };
23
+ const out = h.fire("before_provider_request", { payload }, ctx);
24
+ assert.deepEqual(out.tools.map((t: any) => t.function.name), BOOTSTRAP_TOOLS);
25
+ assert.equal(out.messages[0].content, MINIMAL_SYSTEM_PROMPT);
26
+ assert.match(out.messages[1].content, /current workspace with bash \(`find \. -name/);
27
+ assert.doesNotMatch(out.messages[1].content, /Call find FIRST/, "no find-tool hint while find is unavailable");
28
+ assert.equal(out.max_tokens, 256000);
29
+ assert.match(h.status(ctx), /bootstrap: minimal prompt engaged; tools=\[bash,str_replace_editor\]/);
30
+ assert.equal(h.fire("tool_call", { toolName: "read", input: {} }, ctx)?.block, true);
31
+ assert.equal(h.fire("tool_call", { toolName: "str_replace_editor", input: { command: "view", path: "/x" } }, ctx), undefined);
32
+ h.fire("turn_end", { message: { role: "assistant", stopReason: "toolUse", content: [{ type: "toolCall" }] } }, ctx);
33
+ assert.equal(h.fire("tool_call", { toolName: "read", input: {} }, ctx), undefined);
34
+ const next = { ...payload, messages: [...payload.messages, { role: "tool", content: "result" }] };
35
+ assert.equal(h.fire("before_provider_request", { payload: next }, ctx), undefined);
36
+ assert.equal(next.messages[0].content, systemPrompt);
37
+ assert.equal(next.tools.length, TOOLS.length);
38
+ });
39
+ }
76
40
 
77
- // 10. REGRESSION: session starts as FLASH (a2a gateway agent config), proxy
78
- // silently serves deepseek-v4-pro — model_select NEVER fires. The anchor must
79
- // still engage on the first agent run (live failure: anchorReady was latched
80
- // only at session_start/model_select, so the bootstrap silently skipped).
81
- h.setEntries([]); // genuinely fresh session — no durable replies yet
82
- const servedCtx = h.ctx("deepseek/deepseek-v4-pro", { model: { id: "deepseek/deepseek-v4-pro", provider: "opencode-go" } });
83
- h.fire("session_start", {}, h.ctx("opencode-go/deepseek-v4-flash"));
84
- const rRewritten = h.fire("before_agent_start", { prompt: "task", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, servedCtx);
85
- assert.equal(rRewritten?.systemPrompt, MINIMAL, "served-pro session bootstraps even though session started as flash");
86
- const outRewritten = h.fire("before_provider_request", { payload }, servedCtx);
87
- assert.deepEqual(outRewritten.tools.map((t: any) => t?.function?.name ?? t?.name), ["bash", "str_replace_editor"], "rewritten session gets the DSH Minimal pair");
41
+ it("keeps guidance and loadout when the pair is absent or hidden", () => {
42
+ for (const active of [["read", "find"], TOOLS]) {
43
+ const h = createFakePi(active);
44
+ const ctx = h.ctx(FLASH);
45
+ h.fire("session_start", {}, ctx);
46
+ const hiddenTools = active === TOOLS ? ["bash", "str_replace_editor"] : [];
47
+ const { systemPrompt } = h.fire("before_agent_start", { prompt: "Read limits.ts", systemPrompt: "CHILD CONTRACT", systemPromptOptions: { selectedTools: active, hiddenTools } }, ctx);
48
+ const payload = { messages: [{ role: "system", content: systemPrompt }, { role: "user", content: "Read limits.ts" }], tools: active.filter((name) => !hiddenTools.includes(name)).map((name) => ({ name })) };
49
+ const out = h.fire("before_provider_request", { payload }, ctx);
50
+ assert.match(out.messages[0].content, /CHILD CONTRACT/);
51
+ assert.match(out.messages[1].content, /Call find FIRST/);
52
+ assert.deepEqual(out.tools, payload.tools);
53
+ assert.equal(out.max_tokens, undefined);
54
+ assert.equal(h.notifications.length, 0);
55
+ }
56
+ });
88
57
 
89
- // 11. anchor trace surfaces in the /steering status output
90
- const h2 = createFakePi(["bash", "read", "edit", "str_replace_editor"]);
91
- h2.setEntries([]);
92
- h2.fire("session_start", {}, h2.ctx("deepseek-v4-pro"));
93
- h2.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, h2.ctx("deepseek-v4-pro"));
94
- h2.fire("before_provider_request", { payload: { tools: [{ name: "bash" }, { name: "str_replace_editor" }] } }, h2.ctx("deepseek-v4-pro"));
95
- const statusText = h2.status(h2.ctx("deepseek-v4-pro"));
96
- assert.match(statusText, /bootstrap: minimal prompt engaged/, "trace shows bootstrap engagement");
97
- assert.match(statusText, /payload: tools=\[bash,str_replace_editor\] \+ max_tokens=256000/, "trace shows the bootstrap payload + DSH budget");
58
+ it("fails open atomically when the wire tools differ from the selected tools", () => {
59
+ const h = createFakePi(TOOLS);
60
+ const ctx = h.ctx(FLASH);
61
+ h.fire("session_start", {}, ctx);
62
+ h.fire("before_agent_start", { prompt: "hello", systemPrompt: "FULL" }, ctx);
63
+ const payload = { messages: [{ role: "system", content: "FULL" }], tools: [{ name: "bash" }, { name: "read" }] };
64
+ assert.equal(h.fire("before_provider_request", { payload }, ctx), undefined);
65
+ assert.equal(h.fire("tool_call", { toolName: "read", input: {} }, ctx), undefined);
66
+ assert.match(h.notifications[0], /full prompt and catalog preserved/);
67
+ });
98
68
 
99
- console.log("steering ds-anchor wiring: all lifecycle checks passed");
69
+ it("anchors the proxied served model, honors the we-need flag and clamps to the model limit", () => {
70
+ setSteeringSettings(isolated.dir, { weNeed: true });
71
+ try {
72
+ const h = createFakePi(TOOLS);
73
+ h.fire("session_start", {}, h.ctx("deepseek-v4-flash"));
74
+ const ctx = h.ctx(FLASH, { model: { id: FLASH, provider: "router", maxTokens: 64000 } });
75
+ h.fire("before_agent_start", { prompt: "task", systemPrompt: "FULL" }, ctx);
76
+ const payload = { messages: [{ role: "developer", content: "FULL" }], tools: TOOLS.map((name) => ({ name })), max_tokens: 8192, max_completion_tokens: 8192 };
77
+ const out = h.fire("before_provider_request", { payload }, ctx);
78
+ assert.equal(out.messages[0].content, WE_NEED_DIRECTIVE + MINIMAL_SYSTEM_PROMPT);
79
+ assert.equal(out.max_completion_tokens, 64000);
80
+ assert.equal(out.max_tokens, undefined);
81
+ } finally { setSteeringSettings(isolated.dir, {}); }
82
+ });
@@ -18,10 +18,12 @@ import {
18
18
  } from "../lib/anchor.js";
19
19
 
20
20
  describe("isAnchorTarget", () => {
21
- it("matches v4-pro ids in any case/format, rejects everything else", () => {
21
+ it("matches V4 Pro and V4.1 Flash, not older Flash or other families", () => {
22
22
  assert.equal(isAnchorTarget("deepseek-v4-pro"), true);
23
23
  assert.equal(isAnchorTarget("deepseek-v4-pro-0813"), true);
24
24
  assert.equal(isAnchorTarget("OCG/DeepSeek-V4-Pro"), true);
25
+ assert.equal(isAnchorTarget("router/combo/deepseek-v4.1-flash"), true);
26
+ assert.equal(isAnchorTarget("OCG/DeepSeek-V4.1-Flash-1017"), true);
25
27
  assert.equal(isAnchorTarget("deepseek-v4-flash"), false);
26
28
  assert.equal(isAnchorTarget("deepseek-chat"), false);
27
29
  assert.equal(isAnchorTarget("deepseek-v3"), false);
@@ -32,20 +32,25 @@ const setSettings = (steering: Record<string, unknown>) => writeFileSync(join(AG
32
32
 
33
33
  describe("deepSeekSelectionGuidance", () => {
34
34
  it("includes the compact routing table with serena entries when serena is active", () => {
35
- const g = deepSeekSelectionGuidance(["read", "bash", "serena_find_symbol", "serena_find_referencing_symbols"]);
35
+ const g = deepSeekSelectionGuidance(["read", "bash", "fffind", "find", "ffgrep", "grep", "serena_find_symbol", "serena_find_referencing_symbols", "codemode", "tool_search"]);
36
36
  assert.match(g, /pick the right tool on the first try/);
37
37
  assert.match(g, /"run tests".*bash/);
38
- assert.match(g, /path uncertain.*find before read/);
38
+ assert.match(g, /path uncertain → fffind before read/);
39
+ assert.match(g, /Search literal text.*→ ffgrep/);
40
+ assert.match(g, /Promise\.allSettled/);
41
+ assert.match(g, /targeted tool_search/);
39
42
  assert.match(g, /serena_find_symbol/);
40
43
  assert.match(g, /serena_find_referencing_symbols/);
41
- assert.match(g, /serena_get_symbols_overview/);
44
+ assert.doesNotMatch(g, /serena_get_symbols_overview/);
42
45
  });
43
46
 
44
47
  it("omits serena entries when serena is not active", () => {
45
48
  const g = deepSeekSelectionGuidance(["ls", "grep", "bash", "write"]);
46
49
  assert.doesNotMatch(g, /serena/);
47
50
  assert.match(g, /"list files in <dir>" → ls/);
48
- assert.match(g, /create a file → write/);
51
+ assert.match(g, /Create a new file → write/);
52
+ assert.doesNotMatch(g, /codemode|tool_search|→ find/);
53
+ assert.equal(deepSeekSelectionGuidance([]), "");
49
54
  });
50
55
 
51
56
  it("produces consistent memoized output for same tool set", () => {
@@ -140,7 +140,7 @@ describe("/config contribution", () => {
140
140
  const anchor = groups[0].rows.find((r) => r.key === "steering.dsAnchor")!;
141
141
  assert.equal(anchor.kind, "toggle");
142
142
  assert.equal(anchor.defaultValue, true);
143
- assert.match(anchor.warning!, /Repair module must be enabled/);
143
+ assert.match(anchor.warning!, /V4 Pro and V4\.1 Flash:.*bash and str_replace_editor when both are declared/);
144
144
  // No Enable row here — the config module prepends it.
145
145
  assert.equal(keys.some((k) => k.startsWith("ceulen.disabled")), false);
146
146
  });
@@ -28,7 +28,7 @@ describe("/steering status", () => {
28
28
  assert.match(text, /Super Power Mode \(DeepSeek V4\): off/);
29
29
  assert.match(text, /Strict Serena \(DeepSeek V4\): off/);
30
30
  assert.match(text, /Reasoning strip: on/);
31
- assert.match(text, /ds-anchor \(deepseek-v4-pro\): off/);
31
+ assert.match(text, /ds-anchor \(V4 Pro \/ V4\.1 Flash\): off/);
32
32
  assert.match(text, /We-need directive \(bootstrap\): off/);
33
33
  assert.match(text, /Super Power turns: 0/);
34
34
  });
@@ -44,25 +44,26 @@ describe("/steering status", () => {
44
44
  });
45
45
 
46
46
  it("flags a thinking level below the recipe's max while the anchor is active", () => {
47
- const h = createFakePi(["bash", "read"]);
48
- const ctx = h.ctx("deepseek-v4-pro", { thinkingLevel: "high" });
47
+ const h = createFakePi();
48
+ const ctx = h.ctx("combo/deepseek-v4.1-flash", { thinkingLevel: "high" });
49
49
  h.fire("session_start", {}, ctx);
50
50
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, ctx);
51
51
  const below = h.status(ctx);
52
52
  assert.match(below, /Thinking level: high \(recipe wants max\)/);
53
- assert.match(below, /ds-anchor \(deepseek-v4-pro\): bootstrapping/);
53
+ assert.match(below, /ds-anchor \(V4 Pro \/ V4\.1 Flash\): bootstrapping/);
54
54
  // A level change past max clears the marker.
55
55
  h.fire("thinking_level_select", { level: "max", previousLevel: "high" }, ctx);
56
56
  assert.match(h.status(ctx), /Thinking level: max$/m);
57
57
  });
58
58
 
59
59
  it("shows the error tally and the ds-anchor trace ring", () => {
60
- const h = createFakePi(["bash", "read"]);
60
+ const h = createFakePi();
61
61
  const ctx = h.ctx("deepseek-v4-pro");
62
62
  h.setEntries([]);
63
63
  h.fire("session_start", {}, ctx);
64
- h.fire("tool_execution_end", { toolName: "read", isError: true, result: "ENOENT: no such file or directory" }, ctx);
65
64
  h.fire("before_agent_start", { prompt: "x", systemPrompt: "FULL", systemPromptOptions: {} }, ctx);
65
+ h.fire("before_provider_request", { payload: { messages: [{ role: "system", content: "FULL" }], tools: [{ name: "bash" }, { name: "str_replace_editor" }] } }, ctx);
66
+ h.fire("tool_execution_end", { toolName: "read", isError: true, result: "ENOENT: no such file or directory" }, ctx);
66
67
  const text = h.status(ctx);
67
68
  assert.match(text, /\*\*Errors:\*\* 1 total, last: path_not_found on read/);
68
69
  assert.match(text, /\*\*ds-anchor trace:\*\*/);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.28.1",
3
+ "version": "0.28.2",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",