@lmzhen/dsh-evolution-review 0.38.0 → 0.39.1

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/README.md CHANGED
@@ -14,17 +14,23 @@ Subagent-origin, background-visibility, and review-child sessions are excluded.
14
14
 
15
15
  | Mode | Behavior | Recorded history |
16
16
  |---|---|---|
17
- | `inject` (default) | Sends the review prompt into the parent session. `reviewWakeInject=true` uses a waking follow-up when available. | Emits `review-scheduled`; does **not** emit `plan-applied`, so plan-based activity/replay stays empty. |
18
- | `branch` | Creates a child agent with a seed from the live session log and delivers the result to the parent. | Emits `review-completed` and `plan-applied`, including failure/timeout status when known. |
17
+ | `aux` (default) | Runs a plugin-owned manual loop over the parent request prefix: parent Agent, no child Session, no parent append, allowlisted parent-visible tools executed without a log; a disallowed call returns a tool error instead of aborting the review. | Emits `review-scheduled` and `review-completed`; the completion event is folded into the bounded activity review list (preview + actions + usage). |
18
+ | `inject` (debug) | Sends the review prompt into the parent session as an ordinary turn. `reviewWakeInject=true` uses a waking follow-up when available. | Emits `review-scheduled`; does **not** emit `plan-applied`, so plan-based activity/replay stays empty. |
19
19
 
20
- Branch mode requires `agents`. It is a temporary platform-gap path with trade-offs among durable-log governance, parent prefix-cache reuse, and workspace pollution; it is not the default product path.
21
-
22
- `reviewNotice=true` allows result notices. It does not suppress an inject-mode review prompt, because that prompt is the review itself.
20
+ `reviewNotice=true` allows result notices for the inject path. Aux results are audit-only: `finalText` lands in the bounded activity review record and never becomes a parent message or a new parent turn.
23
21
 
24
22
  ## Events and limits
25
23
 
26
- The package emits `evolution/review-scheduled`, `evolution/review-completed` (branch), `evolution/review-error`, and branch-mode `evolution/plan-applied`. `reviewTimeoutMs` bounds the branch run. Review cadence state is persisted when `evolution-state` is available; without it, cadence can reset between turns.
24
+ The package emits `evolution/review-scheduled`, `evolution/review-completed`, `evolution/review-error`, and an aux `evolution/plan-applied` ledger entry. `reviewTimeoutMs` bounds the aux loop. Review cadence state is persisted when `evolution-state` is available; without it, cadence can reset between turns.
27
25
 
28
26
  **Unimplemented metadata:** `reviewProvider`, `reviewContextMessages`, `reviewMessageChars`, `reviewMaxDepth`, and `reviewToolAllow` may still appear in generated parameter/bundle metadata, but this plugin does not read them. Do not rely on them for provider selection, context limits, delegation depth, or tool restrictions. `reviewTimeoutMs` is implemented.
29
27
 
30
28
  `memoryInterval` and `skillInterval` remain readable deprecated aliases of `reviewMemoryInterval` and `reviewSkillInterval`; writes to the old names are refused (G0/S0.3).
29
+
30
+
31
+ ## Known limitations and migration
32
+
33
+ Step-by-step upgrade instructions: [docs/UPGRADE-0.39.md](../../docs/UPGRADE-0.39.md).
34
+
35
+ - **PTC sessions:** their parent request header exposes only `run_code`. Aux review deliberately rejects `run_code` to keep the parent log append-free, so a PTC review cannot inspect the skill library and may return an empty/degraded result. Use a standard Agent preset for semantic review; do not report a PTC empty review as success.
36
+ - **0.39 migration:** `branch` was removed from the closed `reviewMode` union. An existing `reviewMode: branch` profile patch now fails validation and deactivates the policy row; rewrite it to `aux` before restarting. Old branch activity records remain readable through `branchSessionId`; no new branch run is produced.
package/lib/index.js CHANGED
@@ -1,9 +1,152 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { randomUUID } from "node:crypto";
3
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
3
+ import { BlockAssembler, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
4
4
  import { SessionId } from "@deepseek-ai/dsh-session";
5
- import { COMPLETION_SKILL_REVIEW_PROMPT, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, MAX_TIMER_DELAY_MS, MEMORY_REVIEW_PROMPT, PROMPT_BUNDLE, advanceReview, assertSkillsRootAliasRetired, clampOnce, classifySessionEvent, clearReviewChannel, filterUnreadSkillOps, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, registerOwnerSettings, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle } from "@lmzhen/dsh-evolution-core";
6
- import { modelRoute, presetsPort } from "@lmzhen/dsh-evolution-core/platform";
5
+ import { COMPLETION_SKILL_REVIEW_PROMPT, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, MAX_TIMER_DELAY_MS, MEMORY_REVIEW_PROMPT, PROMPT_BUNDLE, advanceReview, assertSkillsRootAliasRetired, clampOnce, classifySessionEvent, clearReviewChannel, filterUnreadSkillOps, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, registerOwnerSettings, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
6
+ //#region lib/types/review-executor.js
7
+ /**
8
+ * Plugin-side review execution over the parent request prefix.
9
+ *
10
+ * This module deliberately has no AgentLoop child: it replays the parent
11
+ * messages/tools, runs a bounded tool loop, and keeps every intermediate
12
+ * message in memory. The caller owns ReviewRun persistence and audit.
13
+ *
14
+ * @module @lmzhen/dsh-evolution-review/review-executor
15
+ */
16
+ function toolTarget(name, raw) {
17
+ if (raw === "") return name;
18
+ try {
19
+ const parsed = JSON.parse(raw);
20
+ if (parsed !== null && typeof parsed === "object" && "name" in parsed) {
21
+ const value = parsed.name;
22
+ if (typeof value === "string") return value;
23
+ }
24
+ } catch {}
25
+ return name;
26
+ }
27
+ function actionType(name) {
28
+ if (name === "memory") return "memory";
29
+ if (name === "skill_manage") return "skill";
30
+ return "tool";
31
+ }
32
+ /**
33
+ * Execute one review in the parent's request prefix without creating a child.
34
+ *
35
+ * @param input - parent view, LLM/tool ports, allowlist, cancellation, and review mark hooks.
36
+ * @returns final text, action ledger, usage, and request/tool counts.
37
+ * @throws ReviewToolNotAllowedError when the model requests a tool outside the parent-visible allowlist.
38
+ * @throws Error when the parent Session grows during review or the model returns no header.
39
+ */
40
+ async function runReview(input) {
41
+ const { parent, llm, tools, instruction, toolAllow, signal, markReview, clearReview } = input;
42
+ if (parent.status !== "idle") throw new Error("review requires an idle parent");
43
+ const header = parent.session.requestHeader();
44
+ if (header === void 0) throw new Error("review requires the parent request header");
45
+ const beforeSeq = parent.session.seq;
46
+ const messages = [...parent.session.deriveMessages(), createUserMessage({
47
+ content: [{
48
+ type: "text",
49
+ text: instruction
50
+ }],
51
+ source: { kind: "evolution-review" }
52
+ })];
53
+ const toolHistory = parent.session.toolHistory();
54
+ const maxRounds = input.maxRounds ?? 4;
55
+ const actions = [];
56
+ let finalText = "";
57
+ let usage;
58
+ let requests = 0;
59
+ let toolCalls = 0;
60
+ markReview();
61
+ try {
62
+ for (let round = 0; round < maxRounds; round += 1) {
63
+ signal.throwIfAborted();
64
+ const assembler = new BlockAssembler();
65
+ const stream = llm.stream({
66
+ provider: header.config.provider,
67
+ model: header.config.model,
68
+ ...header.config.reasoningEffort === void 0 ? {} : { reasoningEffort: header.config.reasoningEffort },
69
+ ...header.config.temperature === void 0 ? {} : { temperature: header.config.temperature },
70
+ ...header.config.maxTokens === void 0 ? {} : { maxTokens: header.config.maxTokens },
71
+ messages,
72
+ ...header.tools === void 0 ? {} : { tools: [...header.tools] },
73
+ ...toolHistory === void 0 ? {} : { toolHistory },
74
+ signal
75
+ });
76
+ requests += 1;
77
+ for await (const chunk of stream) {
78
+ assembler.push(chunk);
79
+ if (chunk.type === "usage") usage = {
80
+ inputTokens: chunk.usage.inputTokens,
81
+ outputTokens: chunk.usage.outputTokens,
82
+ ...chunk.usage.cacheReadTokens === void 0 ? {} : { cacheReadTokens: chunk.usage.cacheReadTokens }
83
+ };
84
+ }
85
+ signal.throwIfAborted();
86
+ const assistant = assembler.message({
87
+ provider: header.config.provider,
88
+ model: header.config.model
89
+ });
90
+ const text = assistant.content.filter((block) => block.type === "text").map((block) => block.text).join("");
91
+ if (text !== "") finalText = text;
92
+ const calls = assistant.content.filter((block) => block.type === "tool-call");
93
+ if (calls.length === 0) break;
94
+ messages.push(assistant);
95
+ const allowedCalls = calls.filter((call) => toolAllow.has(call.name));
96
+ const batch = allowedCalls.length === 0 ? { results: [] } : await tools.execute({
97
+ calls: allowedCalls,
98
+ signal,
99
+ agent: parent
100
+ });
101
+ const byCall = new Map(batch.results.map((item) => [item.callId, item]));
102
+ const allowedNames = [...toolAllow].sort().join(", ");
103
+ for (const call of calls) {
104
+ const item = byCall.get(call.id);
105
+ if (item === void 0) {
106
+ if (toolAllow.has(call.name)) throw new Error("review tool result has no matching call");
107
+ actions.push({
108
+ type: actionType(call.name),
109
+ action: call.name,
110
+ target: toolTarget(call.name, call.arguments),
111
+ status: "error"
112
+ });
113
+ messages.push(createToolResultMessage({
114
+ callId: call.id,
115
+ content: [{
116
+ type: "text",
117
+ text: `review tool not allowed: ${call.name}; PTC is unavailable in auxiliary review. Use these parent-visible tools directly: ${allowedNames}`
118
+ }],
119
+ isError: true
120
+ }));
121
+ continue;
122
+ }
123
+ actions.push({
124
+ type: actionType(call.name),
125
+ action: call.name,
126
+ target: toolTarget(call.name, call.arguments),
127
+ status: item.result.isError ? "error" : "ok"
128
+ });
129
+ messages.push(createToolResultMessage({
130
+ callId: item.callId,
131
+ content: item.result.content,
132
+ isError: item.result.isError
133
+ }));
134
+ }
135
+ toolCalls += calls.length;
136
+ if (parent.session.seq !== beforeSeq) throw new Error("review tool mutated the parent Session");
137
+ }
138
+ } finally {
139
+ clearReview();
140
+ }
141
+ if (parent.session.seq !== beforeSeq) throw new Error("review mutated the parent Session");
142
+ return {
143
+ finalText,
144
+ actions,
145
+ ...usage === void 0 ? {} : { usage },
146
+ requests,
147
+ toolCalls
148
+ };
149
+ }
7
150
  /**
8
151
  * Whether a message is a notice this plugin delivered, judged only by durable source fields.
9
152
  *
@@ -149,7 +292,7 @@ function noticeAllowed(reviewPrompt, notice) {
149
292
  }
150
293
  const Config = z.object({
151
294
  reviewEnabled: z.boolean().default(true).volatile(),
152
- reviewMode: z.union([z.const("inject"), z.const("branch")]).default("inject").volatile(),
295
+ reviewMode: z.union([z.const("inject"), z.const("aux")]).default("aux").volatile(),
153
296
  reviewMemoryInterval: z.number().min(1).volatile(),
154
297
  reviewSkillInterval: z.number().min(1).volatile(),
155
298
  memoryInterval: z.number().min(1).default(DEFAULT_REVIEW_MEMORY_INTERVAL),
@@ -208,7 +351,7 @@ function resolveReviewRowSettings(rawConfig, warn) {
208
351
  skillReviewTrigger: unwrapLive(rawConfig.skillReviewTrigger) ?? DEFAULT_SKILL_REVIEW_TRIGGER,
209
352
  skillReviewCompletionMinToolCalls: clampOnce(warned, warn, "skillReviewCompletionMinToolCalls", rawConfig.skillReviewCompletionMinToolCalls, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, 1),
210
353
  reviewEnabled: liveBool(rawConfig.reviewEnabled, true),
211
- reviewMode: unwrapLive(rawConfig.reviewMode) ?? "inject",
354
+ reviewMode: unwrapLive(rawConfig.reviewMode) ?? "aux",
212
355
  reviewWakeInject: liveBool(rawConfig.reviewWakeInject, true),
213
356
  reviewNotice: liveBool(rawConfig.reviewNotice, true)
214
357
  };
@@ -235,10 +378,8 @@ function apply(ctx, rawConfig = {}) {
235
378
  const pendingCadenceWarned = sessionState.add("pendingCadenceWarned", /* @__PURE__ */ new Set());
236
379
  const pendingReviewNotices = sessionState.add("pendingReviewNotices", /* @__PURE__ */ new Map());
237
380
  const cadenceResetWarned = sessionState.add("cadenceResetWarned", /* @__PURE__ */ new Set());
238
- /** Branch mode runs at most one branch per parent session; a second trigger only sets rerun. */
239
- const branchRunning = sessionState.add("branchRunning", /* @__PURE__ */ new Map());
240
- /** Child Sessions this plugin owns; their turn/end must not start another review. */
241
- const branchSessions = sessionState.add("branchSessions", /* @__PURE__ */ new Set());
381
+ /** Aux mode runs at most one plugin-side review per parent session; a second trigger only sets rerun. */
382
+ const auxRunning = sessionState.add("auxRunning", /* @__PURE__ */ new Map());
242
383
  const policy = () => ctx.get("evolutionPolicy")?.get();
243
384
  /**
244
385
  * This row's knobs as they stand right now (G1 §8.3): the live fields are resolved
@@ -272,7 +413,7 @@ function apply(ctx, rawConfig = {}) {
272
413
  /** The value the schema fills in when nobody sets the key — for a volatile field the
273
414
  * reference is always present, so this is what "the row set nothing" resolves to. */
274
415
  const SHADOW_DEFAULTS = {
275
- reviewMode: "inject",
416
+ reviewMode: "aux",
276
417
  reviewMemoryInterval: DEFAULT_REVIEW_MEMORY_INTERVAL,
277
418
  reviewSkillInterval: DEFAULT_REVIEW_SKILL_INTERVAL
278
419
  };
@@ -298,7 +439,7 @@ function apply(ctx, rawConfig = {}) {
298
439
  warnShadowed();
299
440
  });
300
441
  }
301
- if (params().reviewMode === "inject") ctx.logger.warn("dsh-evolution-review: reviewMode \"inject\" (default) runs the review in the parent session and emits NO evolution/plan-applied ledger entry — evolution-activity and evolution-replay stay empty in this mode (see the evolution-review README, \"Known Limitations and Deferred Work\"). Set reviewMode: \"branch\" on the evolution-policy row to keep the audited plan path; branch review is a temporary platform-gap path (see the README known limitations).");
442
+ if (params().reviewMode === "inject") ctx.logger.warn("dsh-evolution-review: reviewMode \"inject\" (debug-only) runs the review in the parent session and emits NO evolution/plan-applied ledger entry — evolution-activity and evolution-replay stay empty in this mode (see the evolution-review README, \"Known Limitations and Deferred Work\"). Set reviewMode: \"branch\" on the evolution-policy row to keep the audited plan path; branch review is a temporary platform-gap path (see the README known limitations).");
302
443
  const reviewStateLocks = sessionState.add("reviewStateLocks", /* @__PURE__ */ new Map());
303
444
  async function withReviewStateLock(id, task) {
304
445
  const next = (reviewStateLocks.get(id) ?? Promise.resolve()).catch(() => {}).then(task);
@@ -404,7 +545,6 @@ function apply(ctx, rawConfig = {}) {
404
545
  async function runOnTurnEnd(session, event) {
405
546
  if (!params().reviewEnabled) return;
406
547
  if (session.header.origin === "subagent") return;
407
- if (branchSessions.has(session.id)) return;
408
548
  if (session.header.visibility === "background") return;
409
549
  const agent = ctx.agents.get(session.id);
410
550
  if (!agent) return;
@@ -451,8 +591,11 @@ function apply(ctx, rawConfig = {}) {
451
591
  const pendingKind = kind ?? pendingCadenceReviews.get(session.id) ?? void 0;
452
592
  if (pendingKind !== void 0) {
453
593
  pendingCadenceReviews.delete(session.id);
454
- if (params().reviewMode === "branch" && await tryBranchReview(session, agent, pendingKind, signal, "cadence")) return;
455
- if (params().reviewMode === "inject" || params().reviewMode === "branch") {
594
+ if (params().reviewMode === "aux") {
595
+ if (!tryAuxReview(session, agent, pendingKind, signal, "cadence")) pendingCadenceReviews.set(session.id, pendingKind);
596
+ return;
597
+ }
598
+ if (params().reviewMode === "inject") {
456
599
  if (!deliverMessage(agent, reviewPrompt(pendingKind), cadenceSummary(pendingKind), true)) {
457
600
  pendingCadenceReviews.set(session.id, pendingKind);
458
601
  return;
@@ -483,7 +626,10 @@ function apply(ctx, rawConfig = {}) {
483
626
  if (completionInjected.has(session.id)) return;
484
627
  if (!shouldCompletionReview(event.data.reason, cumulative, params().skillReviewCompletionMinToolCalls)) return;
485
628
  completionInjected.add(session.id);
486
- if (params().reviewMode === "branch" && await tryBranchReview(session, agent, "skill", signal, "completion")) return;
629
+ if (params().reviewMode === "aux") {
630
+ if (!tryAuxReview(session, agent, "skill", signal, "completion")) completionInjected.delete(session.id);
631
+ return;
632
+ }
487
633
  if (!deliverMessage(agent, COMPLETION_SKILL_REVIEW_PROMPT, "completion review", true)) {
488
634
  completionInjected.delete(session.id);
489
635
  return;
@@ -608,161 +754,139 @@ function apply(ctx, rawConfig = {}) {
608
754
  }
609
755
  };
610
756
  const BRANCH_MEMORY_PROMPT = MEMORY_REVIEW_PROMPT.replace("If nothing is worth saving, just say \"Nothing to save.\" and stop.", "Do not create skills here; return a short summary of what was saved.\nIf nothing is worth saving, say \"Nothing to save.\" and stop.");
611
- async function tryBranchReview(session, agent, kind, signal, reason) {
612
- const state = branchRunning.get(session.id);
613
- if (state !== void 0) {
614
- state.rerun = kind;
757
+ /** Tools the plugin-side review may call; every name must already be in the parent request head. */
758
+ /**
759
+ * Run one plugin-side review over the parent prefix. No child Agent/Session is
760
+ * created; the parent Agent is used only for tool scope/approval, with no log.
761
+ */
762
+ function tryAuxReview(session, agent, kind, signal, reason) {
763
+ const running = auxRunning.get(session.id);
764
+ if (running !== void 0) {
765
+ running.rerun = kind;
615
766
  return true;
616
767
  }
617
- const branchState = {};
618
- branchRunning.set(session.id, branchState);
619
- const childId = SessionId("session-" + randomUUID());
768
+ const header = session.requestHeader();
769
+ if (header === void 0) {
770
+ ctx.logger.warn("dsh-evolution-review: aux review skipped — parent has no request header");
771
+ return false;
772
+ }
773
+ const llm = ctx.get("llm");
774
+ const tools = ctx.get("tools");
775
+ if (llm === void 0 || tools === void 0) {
776
+ ctx.logger.warn("dsh-evolution-review: aux review skipped — llm/tools service is not mounted");
777
+ return false;
778
+ }
779
+ const state = {};
780
+ auxRunning.set(session.id, state);
781
+ const reviewId = "aux-" + randomUUID();
620
782
  const startedAt = Date.now();
621
783
  const controller = new AbortController();
622
784
  let timedOut = false;
623
- const timeoutDone = Promise.withResolvers();
624
785
  const timer = setTimeout(() => {
625
786
  timedOut = true;
626
787
  controller.abort();
627
- timeoutDone.resolve();
628
- handle?.agent.cancel({
629
- kind: "hook",
630
- reason: "evolution-review-timeout"
631
- });
632
788
  }, config.reviewTimeoutMs);
633
- let handle;
634
- try {
635
- const presets = presetsPort(ctx);
636
- let agentPreset;
637
- let setup;
638
- if (presets !== void 0) {
639
- const resolved = await presets.resolve(session.header.agentPreset);
640
- agentPreset = resolved.id;
641
- setup = async (target, _child) => {
642
- await presets.mount(target, resolved.id);
643
- };
644
- }
645
- const seed = session.snapshotEvents();
646
- const current = modelRoute(ctx, agent, session);
647
- handle = await ctx.agents.create({
648
- sessionId: childId,
649
- parentAgent: agent,
650
- seed,
651
- inheritedEventCount: seed.length,
652
- meta: {
653
- parentSession: session.id,
654
- isSeeded: true,
655
- ...agentPreset === void 0 ? {} : { agentPreset }
656
- },
657
- ...current === void 0 ? {} : { agentOptions: {
658
- provider: current.provider,
659
- model: current.model
660
- } },
661
- ...setup === void 0 ? {} : { setup }
662
- });
663
- } catch (error) {
664
- clearTimeout(timer);
665
- branchRunning.delete(session.id);
666
- ctx.logger.warn("dsh-evolution-review: branch Session did not start: " + (error instanceof Error ? error.message : String(error)));
667
- return false;
668
- }
669
- branchSessions.add(childId);
670
- const collected = {
671
- finalText: "",
672
- actions: [],
673
- usage: void 0,
674
- error: void 0
675
- };
676
- const onEvent = (owner, event) => {
677
- if (owner.id !== childId) return;
678
- if (event.type === "assistant/message") {
679
- const text = event.data.message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
680
- if (text !== "") collected.finalText = text;
681
- if (event.data.usage !== void 0) collected.usage = {
682
- inputTokens: event.data.usage.inputTokens ?? 0,
683
- outputTokens: event.data.usage.outputTokens ?? 0,
684
- cacheReadTokens: event.data.usage.cacheReadTokens ?? 0,
685
- cacheWriteTokens: event.data.usage.cacheWriteTokens ?? 0
686
- };
687
- }
688
- };
689
- const offEvent = ctx.on("session/event", onEvent);
789
+ const AUX_TOOL_ALLOW = new Set([
790
+ "skill_manage",
791
+ "memory",
792
+ "skill",
793
+ "skill_search",
794
+ "read",
795
+ "glob",
796
+ "grep"
797
+ ]);
798
+ const toolAllow = new Set((header.tools ?? []).map((tool) => tool.name).filter((name) => AUX_TOOL_ALLOW.has(name)));
690
799
  emitReviewScheduled(ctx, {
691
800
  sessionId: session.id,
692
801
  kind,
693
802
  toolCalls: signal.toolCalls,
694
803
  userChars: signal.userChars,
695
804
  assistantChars: signal.assistantChars,
696
- channel: "branch"
805
+ channel: "aux"
697
806
  });
698
807
  (async () => {
808
+ let finalText = "";
809
+ let status = "failed";
810
+ let actions = [];
811
+ let usage;
812
+ let error;
699
813
  try {
700
814
  const prompt = kind === "memory" ? BRANCH_MEMORY_PROMPT : COMPLETION_SKILL_REVIEW_PROMPT;
701
- handle.agent.followup(createUserMessage({
702
- content: [{
703
- type: "text",
704
- text: prompt
705
- }],
706
- source: { kind: "user" }
815
+ const result = await withReviewContext({
816
+ reviewId,
817
+ runId: reviewId
818
+ }, () => runReview({
819
+ parent: agent,
820
+ llm: { stream: (options) => llm.stream(options) },
821
+ tools: { execute: (input) => tools.execute({
822
+ calls: input.calls,
823
+ signal: input.signal,
824
+ agent
825
+ }) },
826
+ instruction: prompt,
827
+ toolAllow,
828
+ signal: controller.signal,
829
+ markReview: () => {},
830
+ clearReview: () => {}
707
831
  }));
708
- const idle = handle.agent.whenIdle().catch((error) => {
709
- if (collected.error === void 0) collected.error = error instanceof Error ? error.message : String(error);
710
- });
711
- await Promise.race([idle, timeoutDone.promise]);
712
- if (timedOut) handle.agent.cancel({
713
- kind: "hook",
714
- reason: "evolution-review-timeout"
715
- });
716
- offEvent();
717
- if (collected.finalText.trim() !== "") deliverMessage(agent, collected.finalText, "branch review result", false);
832
+ finalText = result.finalText;
833
+ actions = result.actions;
834
+ if (result.usage !== void 0) usage = {
835
+ inputTokens: result.usage.inputTokens ?? 0,
836
+ outputTokens: result.usage.outputTokens ?? 0,
837
+ cacheReadTokens: result.usage.cacheReadTokens ?? 0,
838
+ cacheWriteTokens: 0
839
+ };
840
+ status = "completed";
841
+ } catch (caught) {
842
+ error = caught instanceof Error ? caught.message : String(caught);
843
+ status = timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "failed";
844
+ ctx.logger.warn("dsh-evolution-review: aux review failed: " + error);
845
+ } finally {
846
+ clearTimeout(timer);
847
+ const finishedAt = Date.now();
718
848
  try {
719
849
  ctx.emit("evolution/review-completed", {
720
850
  version: 1,
721
- reviewId: childId,
722
- sessionId: session.id,
723
- branchSessionId: childId,
851
+ reviewId,
852
+ sessionId: String(session.id),
724
853
  kind,
725
- status: collected.error !== void 0 ? "failed" : timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "completed",
854
+ status,
726
855
  trigger: {
727
856
  reason,
728
857
  toolCalls: signal.toolCalls,
729
858
  userChars: signal.userChars,
730
859
  assistantChars: signal.assistantChars
731
860
  },
732
- finalText: collected.finalText,
733
- actions: collected.actions,
734
- ...collected.usage === void 0 ? {} : { usage: collected.usage },
861
+ finalText,
862
+ actions,
863
+ ...usage === void 0 ? {} : { usage },
735
864
  startedAt,
736
- finishedAt: Date.now(),
737
- ...collected.error === void 0 ? {} : { error: collected.error }
865
+ finishedAt,
866
+ model: {
867
+ provider: header.config.provider,
868
+ model: header.config.model
869
+ },
870
+ ...error === void 0 ? {} : { error }
738
871
  });
739
872
  } catch (emitError) {
740
- ctx.logger.warn("dsh-evolution-review: review-completed emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
873
+ ctx.logger.warn("dsh-evolution-review: aux review-completed emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
741
874
  }
742
875
  try {
743
876
  const ok = (action) => action.status === "ok";
744
877
  ctx.emit("evolution/plan-applied", {
745
878
  sessionId: String(session.id),
746
- planId: String(childId),
747
- memoryApplied: collected.actions.filter((action) => action.type === "memory" && ok(action)).length,
748
- skillApplied: collected.actions.filter((action) => action.type === "skill" && ok(action)).length,
749
- rejectedOps: collected.actions.filter((action) => !ok(action)).length,
750
- ...collected.error === void 0 ? {} : { executionError: collected.error }
879
+ planId: reviewId,
880
+ memoryApplied: actions.filter((action) => action.type === "memory" && ok(action)).length,
881
+ skillApplied: actions.filter((action) => action.type === "skill" && ok(action)).length,
882
+ rejectedOps: actions.filter((action) => !ok(action)).length,
883
+ ...error === void 0 ? {} : { executionError: error }
751
884
  });
752
885
  } catch (emitError) {
753
- ctx.logger.warn("dsh-evolution-review: plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
886
+ ctx.logger.warn("dsh-evolution-review: aux plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
754
887
  }
755
- } catch (error) {
756
- offEvent();
757
- collected.error = error instanceof Error ? error.message : String(error);
758
- ctx.logger.warn("dsh-evolution-review: branch review failed: " + collected.error);
759
- } finally {
760
- clearTimeout(timer);
761
- branchSessions.delete(childId);
762
- await handle.dispose().catch(() => {});
763
- const rerun = branchState.rerun;
764
- branchRunning.delete(session.id);
765
- if (rerun !== void 0) tryBranchReview(session, agent, rerun, signal, reason);
888
+ auxRunning.delete(session.id);
889
+ if (state.rerun !== void 0) tryAuxReview(session, agent, state.rerun, signal, reason);
766
890
  }
767
891
  })();
768
892
  return true;
@@ -27,14 +27,11 @@ export declare const inject: string[];
27
27
  export declare function noticeAllowed(reviewPrompt: boolean, notice: boolean): boolean;
28
28
  export interface Config {
29
29
  reviewEnabled?: Volatile<boolean>;
30
- /** How the flush delivers the review. `'inject'` (default) runs it in the
31
- * parent agent on the parent's model and cached prefix. `'branch'` is a
32
- * TEMPORARY platform-gap path, not a durable product feature: the platform
33
- * cannot currently provide a review child that is simultaneously
34
- * durable-log-governable, parent-prefix-cache-reusing, and free of workspace
35
- * pollution. Choose branch only when that trade-off is acceptable; see the
36
- * README "Branch review is a temporary platform-gap path". */
37
- reviewMode?: Volatile<'inject' | 'branch'>;
30
+ /** How the flush delivers the review. `'aux'` (default) is the plugin-owned
31
+ * manual loop: parent prefix, no child Session, no parent append.
32
+ * `'inject'` remains a debugging/compatibility mode that runs the review as
33
+ * an ordinary parent turn and therefore appends prompt/tool events. */
34
+ reviewMode?: Volatile<'inject' | 'aux'>;
38
35
  /** Review cadence in TOOL CALLS — the CANONICAL registry id (G1, signals.ts:
39
36
  * a turn advances by its tool-call count, minimum 1, or by 1 when the turn
40
37
  * itself carried the memory signal). Shadowed by the policy snapshot in every
@@ -90,7 +87,7 @@ export interface Config {
90
87
  }
91
88
  export declare const Config: z<Schemastery.ObjectS<NoInfer<{
92
89
  reviewEnabled: z<boolean, boolean, "volatile-defined">;
93
- reviewMode: z<"inject" | "branch", "inject" | "branch", "volatile-defined">;
90
+ reviewMode: z<"inject" | "aux", "inject" | "aux", "volatile-defined">;
94
91
  reviewMemoryInterval: z<number, number, "volatile">;
95
92
  reviewSkillInterval: z<number, number, "volatile">;
96
93
  memoryInterval: z<number, number, "defined">;
@@ -105,7 +102,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
105
102
  skillsRoot: z<string, string, "defined">;
106
103
  }>>, Schemastery.ObjectT<NoInfer<{
107
104
  reviewEnabled: z<boolean, boolean, "volatile-defined">;
108
- reviewMode: z<"inject" | "branch", "inject" | "branch", "volatile-defined">;
105
+ reviewMode: z<"inject" | "aux", "inject" | "aux", "volatile-defined">;
109
106
  reviewMemoryInterval: z<number, number, "volatile">;
110
107
  reviewSkillInterval: z<number, number, "volatile">;
111
108
  memoryInterval: z<number, number, "defined">;
@@ -154,7 +151,7 @@ export interface ReviewSettings {
154
151
  /** Master switch for the review plugin. */
155
152
  reviewEnabled: boolean;
156
153
  /** Run the review in the parent session (inject) or on a subagent. */
157
- reviewMode: 'inject' | 'branch';
154
+ reviewMode: 'inject' | 'aux';
158
155
  /** Deliver the deferred review as a waking follow-up message. */
159
156
  reviewWakeInject: boolean;
160
157
  /** Deliver result notices (not review prompts). */
@@ -0,0 +1,82 @@
1
+ import type { ContentBlock, ContextFormed, GenerateOptions, Message, StreamChunk, ToolCallBlock, ToolCallId, ToolHistory } from '@deepseek-ai/dsh-llm';
2
+ import type { EpochHeader, SessionId } from '@deepseek-ai/dsh-session';
3
+ declare module '@deepseek-ai/dsh-llm' {
4
+ interface MessageSourceMap {
5
+ 'evolution-review': {
6
+ kind: 'evolution-review';
7
+ } & ContextFormed;
8
+ }
9
+ }
10
+ /** Minimal parent view required by the executor; a live Agent is structurally compatible. */
11
+ export interface ReviewParent {
12
+ readonly id: SessionId;
13
+ readonly status: string;
14
+ readonly session: {
15
+ readonly id: SessionId;
16
+ readonly seq: number;
17
+ requestHeader(): EpochHeader | undefined;
18
+ deriveMessages(): readonly Message[];
19
+ toolHistory(): ToolHistory | undefined;
20
+ };
21
+ }
22
+ /** Outcome of one tool call, shaped by the platform ToolBatchResult. */
23
+ export interface ReviewToolOutcome {
24
+ readonly callId: ToolCallId;
25
+ readonly result: {
26
+ readonly content: ContentBlock[];
27
+ readonly isError: boolean;
28
+ };
29
+ }
30
+ /** Tool execution port; the platform ToolsService.execute is structurally compatible. */
31
+ export interface ReviewToolPort {
32
+ execute(input: {
33
+ readonly calls: readonly ToolCallBlock[];
34
+ readonly signal: AbortSignal;
35
+ readonly agent?: ReviewParent;
36
+ }): Promise<{
37
+ readonly results: readonly ReviewToolOutcome[];
38
+ }>;
39
+ }
40
+ /** LLM stream port; ctx.llm.stream can be adapted without changing its contract. */
41
+ export interface ReviewLlmPort {
42
+ stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
43
+ }
44
+ export interface ReviewAction {
45
+ readonly type: 'tool' | 'skill' | 'memory';
46
+ readonly action: string;
47
+ readonly target: string;
48
+ readonly status: 'ok' | 'error';
49
+ }
50
+ export interface ReviewUsage {
51
+ readonly inputTokens?: number;
52
+ readonly outputTokens?: number;
53
+ readonly cacheReadTokens?: number;
54
+ }
55
+ export interface ReviewExecutionResult {
56
+ readonly finalText: string;
57
+ readonly actions: readonly ReviewAction[];
58
+ readonly usage?: ReviewUsage;
59
+ readonly requests: number;
60
+ readonly toolCalls: number;
61
+ }
62
+ export interface RunReviewInput {
63
+ readonly parent: ReviewParent;
64
+ readonly llm: ReviewLlmPort;
65
+ readonly tools: ReviewToolPort;
66
+ readonly instruction: string;
67
+ readonly toolAllow: ReadonlySet<string>;
68
+ readonly signal: AbortSignal;
69
+ readonly maxRounds?: number;
70
+ readonly markReview: () => void;
71
+ readonly clearReview: () => void;
72
+ }
73
+ /**
74
+ * Execute one review in the parent's request prefix without creating a child.
75
+ *
76
+ * @param input - parent view, LLM/tool ports, allowlist, cancellation, and review mark hooks.
77
+ * @returns final text, action ledger, usage, and request/tool counts.
78
+ * @throws ReviewToolNotAllowedError when the model requests a tool outside the parent-visible allowlist.
79
+ * @throws Error when the parent Session grows during review or the model returns no header.
80
+ */
81
+ export declare function runReview(input: RunReviewInput): Promise<ReviewExecutionResult>;
82
+ //# sourceMappingURL=review-executor.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-review",
3
3
  "description": "Background review orchestration (community build)",
4
- "version": "0.38.0",
4
+ "version": "0.39.1",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -27,22 +27,22 @@
27
27
  "license": "MIT",
28
28
  "dependencies": {
29
29
  "@deepseek-ai/schemastery": "^3.18.5",
30
- "@lmzhen/dsh-evolution-core": "^0.38.0"
30
+ "@lmzhen/dsh-evolution-core": "^0.39.1"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "@deepseek-ai/cordis": "^4.0.5",
34
34
  "@deepseek-ai/dsh-agent": "^0.2.2-rc.0",
35
35
  "@deepseek-ai/dsh-llm": "^0.2.2-rc.0",
36
36
  "@deepseek-ai/dsh-session": "^0.2.2-rc.0",
37
- "@lmzhen/dsh-evolution-policy": "^0.38.0",
38
- "@lmzhen/dsh-evolution-state": "^0.38.0"
37
+ "@lmzhen/dsh-evolution-policy": "^0.39.1",
38
+ "@lmzhen/dsh-evolution-state": "^0.39.1"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@deepseek-ai/dsh-agent": "^0.2.2-rc.0",
42
42
  "@deepseek-ai/dsh-llm": "^0.2.2-rc.0",
43
43
  "@deepseek-ai/dsh-session": "^0.2.2-rc.0",
44
- "@lmzhen/dsh-evolution-core": "^0.38.0",
45
- "@lmzhen/dsh-evolution-state": "^0.38.0"
44
+ "@lmzhen/dsh-evolution-core": "^0.39.1",
45
+ "@lmzhen/dsh-evolution-state": "^0.39.1"
46
46
  },
47
47
  "engines": {
48
48
  "dsh": ">=0.2.2-rc.0 <0.2.3-0"