@lmzhen/dsh-evolution-review 0.57.0 → 0.59.0

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/lib/index.js CHANGED
@@ -1,7 +1,9 @@
1
- import { BlockAssembler, SessionId, createToolResultMessage, createUserMessage, llmPort, settingsPort, toolsPort } from "@lmzhen/dsh-evolution-core/platform";
1
+ import { llmPort, settingsPort, toolsPort } from "@lmzhen/dsh-evolution-adapter/ports";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { randomUUID } from "node:crypto";
4
- import { 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, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, MAX_TIMER_DELAY_MS, PROMPT_BUNDLE, advanceReview, clampOnce, classifySessionEvent, clearReviewChannel, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, recordReviewRead, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
4
+ import { BlockAssembler, SessionId, createToolResultMessage, createUserMessage, defineTool } from "@lmzhen/dsh-evolution-adapter/values";
5
+ import { 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, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, MAX_TIMER_DELAY_MS, PROMPT_BUNDLE, advanceReview, clampOnce, classifySessionEvent, clearReviewChannel, currentReviewContext, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, recordReviewRead, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
6
+ import { createReviewChildAgent } from "@lmzhen/dsh-evolution-adapter/review-child";
5
7
  import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-evolution-core/skills";
6
8
  //#region lib/types/review-executor.js
7
9
  /**
@@ -13,6 +15,98 @@ import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-
13
15
  *
14
16
  * @module @lmzhen/dsh-evolution-review/review-executor
15
17
  */
18
+ /** The only terminal tool call in an aux review. */
19
+ const REVIEW_DONE_TOOL_NAME = "review_done";
20
+ /** Tool that lets the model wait for a resource lock before re-reading. */
21
+ const REVIEW_WAIT_TOOL_NAME = "review_wait";
22
+ const REVIEW_WAIT_TOOL = {
23
+ name: REVIEW_WAIT_TOOL_NAME,
24
+ description: "Wait for a resource lock to clear. Call only after a write reports a lock/resource conflict; re-read after it returns.",
25
+ parameters: {
26
+ type: "object",
27
+ properties: {
28
+ resource: { type: "string" },
29
+ timeoutMs: { type: "number" }
30
+ },
31
+ required: ["resource", "timeoutMs"]
32
+ }
33
+ };
34
+ const REVIEW_DONE_TOOL = {
35
+ name: REVIEW_DONE_TOOL_NAME,
36
+ description: "Signal that this review is complete. Call it alone, only after all memory/skill edits for this review are finished.",
37
+ parameters: {
38
+ type: "object",
39
+ properties: {
40
+ summary: { type: "string" },
41
+ memoryChanged: { type: "boolean" },
42
+ skillsChanged: {
43
+ type: "array",
44
+ items: { type: "string" }
45
+ },
46
+ unresolved: {
47
+ type: "array",
48
+ items: { type: "string" }
49
+ }
50
+ },
51
+ required: [
52
+ "summary",
53
+ "memoryChanged",
54
+ "skillsChanged",
55
+ "unresolved"
56
+ ]
57
+ }
58
+ };
59
+ function parseReviewReport(raw) {
60
+ try {
61
+ const parsed = JSON.parse(raw);
62
+ if (parsed === null || typeof parsed !== "object") return void 0;
63
+ const value = parsed;
64
+ if (typeof value.summary !== "string" || typeof value.memoryChanged !== "boolean") return void 0;
65
+ if (!Array.isArray(value.skillsChanged) || !value.skillsChanged.every((item) => typeof item === "string")) return void 0;
66
+ if (!Array.isArray(value.unresolved) || !value.unresolved.every((item) => typeof item === "string")) return void 0;
67
+ return {
68
+ summary: value.summary,
69
+ memoryChanged: value.memoryChanged,
70
+ skillsChanged: value.skillsChanged,
71
+ unresolved: value.unresolved
72
+ };
73
+ } catch {
74
+ return;
75
+ }
76
+ }
77
+ function parseWaitRequest(raw) {
78
+ try {
79
+ const parsed = JSON.parse(raw);
80
+ if (parsed !== null && typeof parsed === "object") {
81
+ const value = parsed;
82
+ const timeoutMs = typeof value.timeoutMs === "number" && Number.isFinite(value.timeoutMs) ? Math.max(1, Math.min(value.timeoutMs, 6e4)) : 1e3;
83
+ return {
84
+ ...typeof value.resource === "string" ? { resource: value.resource } : {},
85
+ timeoutMs
86
+ };
87
+ }
88
+ } catch {}
89
+ return { timeoutMs: 1e3 };
90
+ }
91
+ async function waitForReview(timeoutMs, signal) {
92
+ if (signal.aborted) throw new Error("review_wait aborted");
93
+ await new Promise((resolve) => setTimeout(resolve, timeoutMs));
94
+ signal.throwIfAborted();
95
+ }
96
+ function writeResource(call) {
97
+ if (call.name !== "skill_manage" && call.name !== "memory") return void 0;
98
+ try {
99
+ const parsed = JSON.parse(call.arguments);
100
+ if (parsed !== null && typeof parsed === "object") {
101
+ const value = parsed;
102
+ const name = typeof value.name === "string" ? value.name : void 0;
103
+ const target = typeof value.target === "string" ? value.target : void 0;
104
+ if (call.name === "skill_manage") return "skill:" + (name ?? "<unnamed>");
105
+ return "memory:" + (target ?? "default");
106
+ }
107
+ } catch {}
108
+ return call.name === "skill_manage" ? "skill:<unnamed>" : "memory:default";
109
+ }
16
110
  var ReviewModelError = class extends Error {
17
111
  code;
18
112
  constructor(message, code) {
@@ -67,6 +161,7 @@ async function runReview(input) {
67
161
  const header = parent.session.requestHeader();
68
162
  if (header === void 0) throw new Error("review requires the parent request header");
69
163
  const beforeSeq = parent.session.seq;
164
+ const toolHistory = input.channel?.mode === "ptc" ? parent.session.toolHistory?.() : void 0;
70
165
  const messages = [...parent.session.deriveMessages(), createUserMessage({
71
166
  content: [{
72
167
  type: "text",
@@ -74,13 +169,18 @@ async function runReview(input) {
74
169
  }],
75
170
  source: { kind: "evolution-review" }
76
171
  })];
77
- const toolHistory = parent.session.toolHistory();
78
172
  const maxRounds = input.maxRounds ?? 4;
173
+ const maxToolCalls = input.maxToolCalls ?? 50;
79
174
  const actions = [];
80
175
  let finalText = "";
81
176
  let usage;
82
177
  let requests = 0;
83
178
  let toolCalls = 0;
179
+ let done = false;
180
+ let hitRoundLimit = false;
181
+ let partialReason;
182
+ let report;
183
+ let waitCount = 0;
84
184
  markReview();
85
185
  try {
86
186
  for (let round = 0; round < maxRounds; round += 1) {
@@ -93,7 +193,7 @@ async function runReview(input) {
93
193
  ...header.config.temperature === void 0 ? {} : { temperature: header.config.temperature },
94
194
  ...header.config.maxTokens === void 0 ? {} : { maxTokens: header.config.maxTokens },
95
195
  messages,
96
- ...header.tools === void 0 ? {} : { tools: [...header.tools] },
196
+ tools: [...input.channel?.visibleTools ?? header.tools ?? [], ...input.channel?.mode === "ptc" ? [] : [REVIEW_WAIT_TOOL, REVIEW_DONE_TOOL]],
97
197
  ...toolHistory === void 0 ? {} : { toolHistory },
98
198
  signal
99
199
  }, signal);
@@ -115,19 +215,137 @@ async function runReview(input) {
115
215
  if (text !== "") finalText = text;
116
216
  const calls = assistant.content.filter((block) => block.type === "tool-call");
117
217
  if (calls.length === 0) break;
218
+ const waitCalls = input.channel?.mode === "ptc" ? [] : calls.filter((call) => call.name === REVIEW_WAIT_TOOL_NAME);
219
+ if (waitCalls.length > 0) {
220
+ if (calls.length !== 1) {
221
+ partialReason = "review_wait must be the only tool call in its batch";
222
+ break;
223
+ }
224
+ toolCalls += 1;
225
+ waitCount += 1;
226
+ const parsed = parseWaitRequest(waitCalls[0].arguments);
227
+ const released = parsed.resource !== void 0 && input.writeLocks !== void 0 ? await input.writeLocks.wait(parsed.resource, parsed.timeoutMs, signal) : await waitForReview(parsed.timeoutMs, signal);
228
+ actions.push({
229
+ type: "tool",
230
+ action: REVIEW_WAIT_TOOL_NAME,
231
+ target: parsed.resource ?? "resource",
232
+ status: released === false ? "error" : "ok"
233
+ });
234
+ messages.push(assistant);
235
+ messages.push(createToolResultMessage({
236
+ callId: waitCalls[0].id,
237
+ content: [{
238
+ type: "text",
239
+ text: released === false ? "review_wait timed out" : "review_wait released"
240
+ }],
241
+ isError: released === false
242
+ }));
243
+ if (released === false) {
244
+ partialReason = "lock-wait-exhausted";
245
+ break;
246
+ }
247
+ if (toolCalls >= maxToolCalls) {
248
+ partialReason = "max tool calls reached before review_done";
249
+ break;
250
+ }
251
+ continue;
252
+ }
253
+ const doneCalls = input.channel?.mode === "ptc" ? [] : calls.filter((call) => call.name === REVIEW_DONE_TOOL_NAME);
254
+ if (doneCalls.length > 0) {
255
+ toolCalls += calls.length;
256
+ if (calls.length !== 1) {
257
+ partialReason = "review_done must be the only tool call in its batch";
258
+ break;
259
+ }
260
+ const parsed = parseReviewReport(doneCalls[0].arguments);
261
+ if (parsed === void 0) {
262
+ partialReason = "review_done report is invalid";
263
+ break;
264
+ }
265
+ report = parsed;
266
+ done = true;
267
+ actions.push({
268
+ type: "tool",
269
+ action: REVIEW_DONE_TOOL_NAME,
270
+ target: "review",
271
+ status: "ok"
272
+ });
273
+ break;
274
+ }
118
275
  messages.push(assistant);
119
- const allowedCalls = calls.filter((call) => toolAllow.has(call.name));
120
- const batch = allowedCalls.length === 0 ? { results: [] } : await tools.execute({
121
- calls: allowedCalls,
122
- signal,
123
- agent: parent
124
- });
276
+ const allowedNames = input.channel === void 0 ? toolAllow : new Set(input.channel.visibleTools.map((tool) => tool.name));
277
+ const allowedCalls = calls.filter((call) => allowedNames.has(call.name));
278
+ const releases = [];
279
+ const held = /* @__PURE__ */ new Set();
280
+ const busy = /* @__PURE__ */ new Map();
281
+ const runnable = [];
282
+ for (const call of allowedCalls) {
283
+ const resource = writeResource(call);
284
+ if (resource === void 0 || input.writeLocks === void 0) {
285
+ runnable.push(call);
286
+ continue;
287
+ }
288
+ if (held.has(resource)) {
289
+ runnable.push(call);
290
+ continue;
291
+ }
292
+ const release = input.writeLocks.tryAcquire(resource, input.owner ?? "review");
293
+ if (release === void 0) {
294
+ busy.set(call.id, resource);
295
+ continue;
296
+ }
297
+ held.add(resource);
298
+ releases.push(release);
299
+ runnable.push(call);
300
+ }
301
+ let batch;
302
+ try {
303
+ batch = runnable.length === 0 ? { results: [] } : input.channel === void 0 ? await tools.execute({
304
+ calls: runnable,
305
+ signal,
306
+ agent: parent
307
+ }) : await input.channel.execute(runnable, signal);
308
+ } finally {
309
+ for (const release of releases) release();
310
+ }
311
+ const channelCompletion = input.channel?.completion?.();
312
+ if (channelCompletion?.done === true && channelCompletion.report !== void 0) {
313
+ report = channelCompletion.report;
314
+ done = true;
315
+ toolCalls += calls.length;
316
+ if (channelCompletion.waitCount !== void 0) waitCount = channelCompletion.waitCount;
317
+ actions.push({
318
+ type: "tool",
319
+ action: REVIEW_DONE_TOOL_NAME,
320
+ target: "review",
321
+ status: "ok"
322
+ });
323
+ break;
324
+ }
125
325
  const byCall = new Map(batch.results.map((item) => [item.callId, item]));
126
- const allowedNames = [...toolAllow].sort().join(", ");
326
+ const allowedLabel = [...allowedNames].sort().join(", ");
127
327
  for (const call of calls) {
128
328
  const item = byCall.get(call.id);
329
+ const busyResource = busy.get(call.id);
330
+ if (busyResource !== void 0) {
331
+ actions.push({
332
+ type: actionType(call.name),
333
+ action: call.name,
334
+ target: toolTarget(call.name, call.arguments),
335
+ status: "error"
336
+ });
337
+ messages.push(createToolResultMessage({
338
+ callId: call.id,
339
+ content: [{
340
+ type: "text",
341
+ text: "resource-busy: " + busyResource + "; call review_wait, then re-read the target and retry"
342
+ }],
343
+ isError: true
344
+ }));
345
+ continue;
346
+ }
129
347
  if (item === void 0) {
130
- if (toolAllow.has(call.name)) throw new Error("review tool result has no matching call");
348
+ if (allowedNames.has(call.name)) throw new Error("review tool result has no matching call");
131
349
  actions.push({
132
350
  type: actionType(call.name),
133
351
  action: call.name,
@@ -138,7 +356,7 @@ async function runReview(input) {
138
356
  callId: call.id,
139
357
  content: [{
140
358
  type: "text",
141
- text: `review tool not allowed: ${call.name}; PTC is unavailable in auxiliary review. Use these parent-visible tools directly: ${allowedNames}`
359
+ text: `review tool not allowed: ${call.name}; PTC is unavailable in auxiliary review. Use these parent-visible tools directly: ${allowedLabel}`
142
360
  }],
143
361
  isError: true
144
362
  }));
@@ -161,20 +379,415 @@ async function runReview(input) {
161
379
  }));
162
380
  }
163
381
  toolCalls += calls.length;
382
+ if (toolCalls >= maxToolCalls) {
383
+ partialReason = "max tool calls reached before review_done";
384
+ break;
385
+ }
386
+ if (round === maxRounds - 1) hitRoundLimit = true;
164
387
  if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review tool mutated the parent Session", actions);
165
388
  }
166
389
  } finally {
167
390
  clearReview();
168
391
  }
169
392
  if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review mutated the parent Session", actions);
393
+ if (!done && partialReason === void 0) partialReason = "missing review_done";
394
+ if (hitRoundLimit) partialReason = "max review rounds reached before review_done";
170
395
  return {
171
396
  finalText,
172
397
  actions,
173
398
  ...usage === void 0 ? {} : { usage },
174
399
  requests,
175
- toolCalls
400
+ toolCalls,
401
+ done,
402
+ hitRoundLimit,
403
+ waitCount,
404
+ ...report === void 0 ? {} : { report },
405
+ ...partialReason === void 0 ? {} : { partialReason }
176
406
  };
177
407
  }
408
+ //#endregion
409
+ //#region lib/types/review-tool-channel.js
410
+ /** Native transport: the frozen parent header's direct tools plus the live tools service. */
411
+ function nativeReviewToolChannel(parent, toolAllow, tools, executionAgent = parent) {
412
+ const header = parent.session.requestHeader();
413
+ const blocked = (call) => ({
414
+ callId: call.id,
415
+ result: {
416
+ content: [{
417
+ type: "text",
418
+ text: "Tool \"" + call.name + "\" is not available in this background review; use the review tools or finish with review_done."
419
+ }],
420
+ isError: true
421
+ }
422
+ });
423
+ return {
424
+ mode: "native",
425
+ visibleTools: header?.tools ?? [],
426
+ instruction: "Use only the review tools in this catalog (skill_manage, memory, skill, skill_search, read, glob, grep). Any other tool call is rejected before execution.",
427
+ async execute(calls, signal) {
428
+ const runnable = calls.filter((call) => toolAllow.has(call.name));
429
+ if (runnable.length === 0) return { results: calls.map(blocked) };
430
+ const executed = await tools.execute({
431
+ calls: runnable,
432
+ signal,
433
+ agent: executionAgent
434
+ });
435
+ const byId = new Map(executed.results.map((result) => [result.callId, result]));
436
+ return { results: calls.map((call) => byId.get(call.id) ?? blocked(call)) };
437
+ }
438
+ };
439
+ }
440
+ //#endregion
441
+ //#region lib/types/review-ptc-channel.js
442
+ /**
443
+ * PTC review tool channel.
444
+ *
445
+ * PTC runs tools through `run_code`; its nested dispatch appends to
446
+ * `exec.agent.session`. The review executor therefore passes a detached child
447
+ * agent created by `@lmzhen/dsh-evolution-adapter/review-child`.
448
+ *
449
+ * The review completion tools (`review_done`, `review_wait`) are registered
450
+ * ONCE per plugin instance by {@link PtcReviewToolHost}. Their `when` guard only
451
+ * admits them while one of the host's review tasks is executing, and their
452
+ * handlers resolve the control record from the active review context. This
453
+ * avoids duplicate global registrations when two PTC reviews run at once.
454
+ *
455
+ * @module @lmzhen/dsh-evolution-review/review-ptc-channel
456
+ */
457
+ /** Keep PTC's in-program SDK to the review allowlist instead of the parent preset's full tool set. */
458
+ function filterToolSet(full, allowed) {
459
+ if (full === null || typeof full !== "object" || typeof full.view !== "function") return /* @__PURE__ */ new Map();
460
+ const view = full.view.bind(full);
461
+ return {
462
+ view(scope) {
463
+ const source = view(scope);
464
+ if (source === null || typeof source.entries !== "function") return /* @__PURE__ */ new Map();
465
+ const out = /* @__PURE__ */ new Map();
466
+ for (const [name, definition] of source.entries()) if (allowed.has(name)) out.set(name, definition);
467
+ return out;
468
+ },
469
+ ...typeof full.dispose === "function" ? { dispose: () => full.dispose() } : {}
470
+ };
471
+ }
472
+ const PTC_INSTRUCTION = "You are reviewing in PTC mode. Write one or more run_code programs that call the available review tools. When the review is complete, call tools.review_done as the only review action of that program. A precise no-op is still completed: always finish with tools.review_done instead of stopping without it. If a write reports resource-busy, call tools.review_wait and then re-read before retrying.";
473
+ function asObject(value) {
474
+ return value !== null && typeof value === "object" ? value : void 0;
475
+ }
476
+ function controlFor(controls, exec) {
477
+ const reviewId = currentReviewContext()?.reviewId;
478
+ if (reviewId !== void 0 && controls.has(reviewId)) return controls.get(reviewId);
479
+ const sessionId = exec?.agent?.session?.id;
480
+ const text = typeof sessionId === "string" ? sessionId : String(sessionId ?? "");
481
+ for (const [taskId, control] of controls) if (text.startsWith("review-child:" + taskId + ":")) return control;
482
+ }
483
+ function reviewDefinitions(controls, locks) {
484
+ return [defineTool({
485
+ name: REVIEW_DONE_TOOL_NAME,
486
+ description: "Finish the review. Must be the only review action in its program.",
487
+ parameters: {
488
+ summary: {
489
+ type: "string",
490
+ required: true
491
+ },
492
+ memoryChanged: {
493
+ type: "boolean",
494
+ required: true
495
+ },
496
+ skillsChanged: {
497
+ type: "array",
498
+ items: { type: "string" },
499
+ required: true
500
+ },
501
+ unresolved: {
502
+ type: "array",
503
+ items: { type: "string" },
504
+ required: true
505
+ }
506
+ },
507
+ output: {
508
+ schema: {
509
+ type: "object",
510
+ additionalProperties: false,
511
+ properties: { ok: {
512
+ type: "boolean",
513
+ required: true
514
+ } }
515
+ },
516
+ render: () => [{
517
+ type: "text",
518
+ text: "review_done accepted"
519
+ }]
520
+ },
521
+ async execute(args, exec) {
522
+ const raw = asObject(args);
523
+ if (raw === void 0) return { ok: false };
524
+ const parsed = parseReviewReport(JSON.stringify(raw));
525
+ const control = controlFor(controls, exec);
526
+ if (parsed === void 0 || control === void 0) return { ok: false };
527
+ control.report = parsed;
528
+ control.done = true;
529
+ return { ok: true };
530
+ }
531
+ }), defineTool({
532
+ name: REVIEW_WAIT_TOOL_NAME,
533
+ description: "Wait for a review resource lock after resource-busy; re-read before retrying.",
534
+ parameters: {
535
+ resource: {
536
+ type: "string",
537
+ required: true
538
+ },
539
+ timeoutMs: { type: "number" }
540
+ },
541
+ output: {
542
+ schema: {
543
+ type: "object",
544
+ additionalProperties: false,
545
+ properties: { ok: {
546
+ type: "boolean",
547
+ required: true
548
+ } }
549
+ },
550
+ render: (_args, value) => [{
551
+ type: "text",
552
+ text: value.ok ? "review_wait released" : "review_wait timed out"
553
+ }]
554
+ },
555
+ async execute(args, exec) {
556
+ const raw = asObject(args);
557
+ const resource = typeof raw?.resource === "string" ? raw.resource : "";
558
+ const timeoutMs = typeof raw?.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : 1e3;
559
+ const control = controlFor(controls, exec);
560
+ if (control === void 0) return { ok: false };
561
+ control.waitCount += 1;
562
+ if (resource === "") return { ok: true };
563
+ return { ok: await locks.wait(resource, timeoutMs, exec.signal) };
564
+ }
565
+ })];
566
+ }
567
+ /**
568
+ * One shared registration surface for all PTC review channels in this plugin
569
+ * instance. Construct once, `register()` once, then `channel()` per task.
570
+ */
571
+ var PtcReviewToolHost = class {
572
+ tools;
573
+ locks;
574
+ controls = /* @__PURE__ */ new Map();
575
+ active = /* @__PURE__ */ new Set();
576
+ disposers = [];
577
+ registered = false;
578
+ constructor(tools, locks) {
579
+ this.tools = tools;
580
+ this.locks = locks;
581
+ }
582
+ /** Register the review-only tools once; idempotent. */
583
+ register() {
584
+ if (this.registered) return;
585
+ this.registered = true;
586
+ this.disposers = reviewDefinitions(this.controls, this.locks).map((definition) => this.tools.register(definition, { when: () => {
587
+ const reviewId = currentReviewContext()?.reviewId;
588
+ return reviewId !== void 0 && this.active.has(reviewId);
589
+ } }));
590
+ }
591
+ /** Build one task channel over the shared registration. */
592
+ channel(taskId, parentHeaderTools, childAgent, modelSelection, allowedTools) {
593
+ this.register();
594
+ const control = {
595
+ done: false,
596
+ waitCount: 0
597
+ };
598
+ this.controls.set(taskId, control);
599
+ const host = this;
600
+ return {
601
+ mode: "ptc",
602
+ visibleTools: parentHeaderTools,
603
+ instruction: PTC_INSTRUCTION,
604
+ control,
605
+ completion: () => control.done && control.report !== void 0 ? {
606
+ done: true,
607
+ report: control.report,
608
+ waitCount: control.waitCount
609
+ } : void 0,
610
+ async execute(calls, signal) {
611
+ host.active.add(taskId);
612
+ try {
613
+ if (host.tools.execute === void 0) throw new Error("PTC review channel requires tools.execute");
614
+ if (host.tools.resolve === void 0) throw new Error("PTC review channel requires tools.resolve for the review allowlist");
615
+ const toolSet = filterToolSet(await host.tools.resolve({
616
+ agent: childAgent,
617
+ modelSelection,
618
+ signal
619
+ }), allowedTools);
620
+ return await host.tools.execute({
621
+ calls,
622
+ signal,
623
+ agent: childAgent,
624
+ ...toolSet === void 0 ? {} : { toolSet }
625
+ });
626
+ } finally {
627
+ host.active.delete(taskId);
628
+ }
629
+ },
630
+ dispose() {
631
+ host.active.delete(taskId);
632
+ host.controls.delete(taskId);
633
+ }
634
+ };
635
+ }
636
+ /** Remove the global registrations; used when the plugin fiber unloads. */
637
+ dispose() {
638
+ for (const dispose of this.disposers.reverse()) dispose();
639
+ this.disposers = [];
640
+ this.controls.clear();
641
+ this.active.clear();
642
+ this.registered = false;
643
+ }
644
+ };
645
+ //#endregion
646
+ //#region lib/types/review-write-locks.js
647
+ /**
648
+ * Process-local review write locks.
649
+ *
650
+ * The SkillLibrary's per-directory lock + CAS is the final correctness layer.
651
+ * This small registry gives the review model the *recoverable* state it needs:
652
+ * a second review writing the same skill/memory resource gets a `resource-busy`
653
+ * tool result instead of racing silently, and `review_wait` can wait for the
654
+ * holder to release before the model re-reads and retries.
655
+ *
656
+ * It is intentionally not durable and does not coordinate foreground writers or
657
+ * other processes; those keep their existing HomeFence/CAS guarantees.
658
+ *
659
+ * @module @lmzhen/dsh-evolution-review/review-write-locks
660
+ */
661
+ /** One process-local holder per resource plus its waiters. */
662
+ var ReviewWriteLocks = class {
663
+ closed = false;
664
+ holders = /* @__PURE__ */ new Map();
665
+ waiters = /* @__PURE__ */ new Map();
666
+ /** @returns the holder when the resource is busy, otherwise undefined. */
667
+ holder(resource) {
668
+ return this.holders.get(resource)?.owner;
669
+ }
670
+ /** Drop all holders and wake waiters; used when the plugin fiber unloads. */
671
+ dispose() {
672
+ this.closed = true;
673
+ this.holders.clear();
674
+ for (const waiting of this.waiters.values()) for (const wake of waiting) wake();
675
+ this.waiters.clear();
676
+ }
677
+ /**
678
+ * Try to become the holder.
679
+ * @returns the release callback, or undefined when another owner holds it.
680
+ */
681
+ tryAcquire(resource, owner) {
682
+ if (this.closed || this.holders.has(resource)) return void 0;
683
+ this.holders.set(resource, { owner });
684
+ let released = false;
685
+ return () => {
686
+ if (released) return;
687
+ released = true;
688
+ this.holders.delete(resource);
689
+ const waiting = this.waiters.get(resource);
690
+ if (waiting === void 0) return;
691
+ this.waiters.delete(resource);
692
+ for (const wake of waiting) wake();
693
+ };
694
+ }
695
+ /**
696
+ * Wait until the resource has no holder.
697
+ * @returns true when free, false on timeout/abort.
698
+ */
699
+ async wait(resource, timeoutMs, signal) {
700
+ if (this.closed) return false;
701
+ if (!this.holders.has(resource)) return true;
702
+ if (signal.aborted) return false;
703
+ return await new Promise((resolve) => {
704
+ let finished = false;
705
+ const finish = (value) => {
706
+ if (finished) return;
707
+ finished = true;
708
+ clearTimeout(timer);
709
+ signal.removeEventListener("abort", onAbort);
710
+ this.waiters.get(resource)?.delete(wake);
711
+ if (this.waiters.get(resource)?.size === 0) this.waiters.delete(resource);
712
+ resolve(value);
713
+ };
714
+ const wake = () => {
715
+ if (this.closed) finish(false);
716
+ else if (!this.holders.has(resource)) finish(true);
717
+ };
718
+ const waiting = this.waiters.get(resource) ?? /* @__PURE__ */ new Set();
719
+ waiting.add(wake);
720
+ this.waiters.set(resource, waiting);
721
+ const timer = setTimeout(() => finish(false), Math.max(1, timeoutMs));
722
+ const onAbort = () => finish(false);
723
+ signal.addEventListener("abort", onAbort, { once: true });
724
+ });
725
+ }
726
+ };
727
+ //#endregion
728
+ //#region lib/types/review-limiter.js
729
+ /**
730
+ * Process-local bound on concurrent AUX reviews.
731
+ *
732
+ * The family deliberately keeps this small: one semaphore for the plugin
733
+ * instance, no per-session or weighted fairness. A review waits for a slot
734
+ * before its first model request; the bounded queue is what keeps a burst of
735
+ * sessions from opening unbounded LLM streams.
736
+ *
737
+ * @module @lmzhen/dsh-evolution-review/review-limiter
738
+ */
739
+ /** A tiny FIFO semaphore whose waiters can be aborted by unload/timeout. */
740
+ var ReviewLimiter = class {
741
+ limit;
742
+ active = 0;
743
+ closed = false;
744
+ waiters = [];
745
+ constructor(limit) {
746
+ this.limit = limit;
747
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("review limiter limit must be a positive integer");
748
+ }
749
+ /** Wait for a slot; undefined means the wait was aborted or the limiter closed. */
750
+ async acquire(signal) {
751
+ if (this.closed || signal?.aborted === true) return void 0;
752
+ if (this.active < this.limit) {
753
+ this.active += 1;
754
+ return this.releaseOnce();
755
+ }
756
+ return await new Promise((resolve) => {
757
+ const waiter = { resolve };
758
+ if (signal !== void 0) {
759
+ waiter.signal = signal;
760
+ waiter.onAbort = () => {
761
+ const index = this.waiters.indexOf(waiter);
762
+ if (index >= 0) this.waiters.splice(index, 1);
763
+ resolve(void 0);
764
+ };
765
+ signal.addEventListener("abort", waiter.onAbort, { once: true });
766
+ }
767
+ this.waiters.push(waiter);
768
+ });
769
+ }
770
+ dispose() {
771
+ this.closed = true;
772
+ for (const waiter of this.waiters.splice(0)) {
773
+ if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
774
+ waiter.resolve(void 0);
775
+ }
776
+ }
777
+ releaseOnce() {
778
+ let released = false;
779
+ return () => {
780
+ if (released) return;
781
+ released = true;
782
+ this.active -= 1;
783
+ const waiter = this.waiters.shift();
784
+ if (waiter === void 0) return;
785
+ if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
786
+ this.active += 1;
787
+ waiter.resolve(this.releaseOnce());
788
+ };
789
+ }
790
+ };
178
791
  /**
179
792
  * Whether a message is a notice this plugin delivered, judged only by durable source fields.
180
793
  *
@@ -289,6 +902,9 @@ var SessionScopedState = class {
289
902
  */
290
903
  /** Model requests per auxiliary review run. One skill of incremental edits may need many rounds. */
291
904
  const DEFAULT_REVIEW_MAX_ROUNDS = 12;
905
+ /** Tool calls per auxiliary review run; completion is still required before this bound. */
906
+ const DEFAULT_REVIEW_MAX_TOOL_CALLS = 50;
907
+ const MAX_REVIEW_MAX_TOOL_CALLS = 500;
292
908
  /** Keep a mistyped deployment value from turning one review into an unbounded loop. */
293
909
  const MAX_REVIEW_MAX_ROUNDS = 200;
294
910
  /** Emit one `evolution/review-scheduled` inside its OWN protection domain (V8-03, V5-19③/F-334).
@@ -329,6 +945,7 @@ const Config = z.object({
329
945
  reviewSkillInterval: z.number().min(1).volatile(),
330
946
  reviewTimeoutMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_REVIEW_TIMEOUT_MS),
331
947
  reviewMaxRounds: z.number().min(1).max(MAX_REVIEW_MAX_ROUNDS).default(DEFAULT_REVIEW_MAX_ROUNDS),
948
+ reviewMaxToolCalls: z.number().min(1).max(MAX_REVIEW_MAX_TOOL_CALLS).default(DEFAULT_REVIEW_MAX_TOOL_CALLS),
332
949
  skillReviewTrigger: z.union([
333
950
  z.const("cadence"),
334
951
  z.const("completion"),
@@ -347,6 +964,20 @@ const Config = z.object({
347
964
  * kind: memory / skill / combined), both in the queue and in the session log.
348
965
  */
349
966
  const cadenceSummary = (kind) => `auto-review:${kind}`;
967
+ /** Foreground delivery still combines both due domains into one prompt. */
968
+ function injectKind(debt) {
969
+ if (debt === null) return null;
970
+ if (debt.memory && debt.skill) return "combined";
971
+ return debt.memory ? "memory" : debt.skill ? "skill" : null;
972
+ }
973
+ function mergeDebt(a, b) {
974
+ if (a === null || a === void 0) return b ?? void 0;
975
+ if (b === null || b === void 0) return a;
976
+ return {
977
+ memory: a.memory || b.memory,
978
+ skill: a.skill || b.skill
979
+ };
980
+ }
350
981
  /**
351
982
  * The DEPLOYMENT layer of this row, clamped once at assembly: the restart-only
352
983
  * numerics (registry tier E2) whose consumers read them from this snapshot. The
@@ -364,7 +995,8 @@ function clampReviewConfig(rawConfig, ctx) {
364
995
  const field = (name, value, fallback, min, max) => clampOnce(warned, warn, name, value, fallback, min, max);
365
996
  return Object.assign({}, rawConfig, {
366
997
  reviewTimeoutMs: field("reviewTimeoutMs", rawConfig.reviewTimeoutMs, DEFAULT_REVIEW_TIMEOUT_MS, 1, MAX_TIMER_DELAY_MS),
367
- reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS)
998
+ reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS),
999
+ reviewMaxToolCalls: field("reviewMaxToolCalls", rawConfig.reviewMaxToolCalls, DEFAULT_REVIEW_MAX_TOOL_CALLS, 1, MAX_REVIEW_MAX_TOOL_CALLS)
368
1000
  });
369
1001
  }
370
1002
  /**
@@ -596,7 +1228,7 @@ function apply(ctx, rawConfig = {}) {
596
1228
  turnsSinceSkill: 0,
597
1229
  lastTurn: -1
598
1230
  };
599
- const advanced = { kind: null };
1231
+ const advanced = { debt: null };
600
1232
  if (settlesHere) await settleNotice(session.id, "turn-end");
601
1233
  else await withReviewStateLock(session.id, async () => {
602
1234
  state = await stateService?.loadReviewState(session.id) ?? {
@@ -604,7 +1236,7 @@ function apply(ctx, rawConfig = {}) {
604
1236
  turnsSinceSkill: 0,
605
1237
  lastTurn: -1
606
1238
  };
607
- advanced.kind = advanceReview(state, event.data.turn, signal, {
1239
+ advanced.debt = advanceReview(state, event.data.turn, signal, {
608
1240
  memoryInterval: params().reviewMemoryInterval,
609
1241
  skillInterval: params().reviewSkillInterval,
610
1242
  substantiveMinToolCalls: snapshot?.substantiveMinToolCalls ?? DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS,
@@ -614,20 +1246,24 @@ function apply(ctx, rawConfig = {}) {
614
1246
  });
615
1247
  await stateService?.saveReviewState(session.id, state);
616
1248
  });
617
- const kind = advanced.kind;
1249
+ const debt = advanced.debt;
1250
+ const kind = injectKind(debt);
618
1251
  const cumulative = (cumulativeToolCalls.get(session.id) ?? 0) + signal.toolCalls;
619
1252
  cumulativeToolCalls.set(session.id, cumulative);
620
1253
  if (event.data.reason.kind === "completed") {
621
- const pendingKind = kind ?? pendingCadenceReviews.get(session.id) ?? void 0;
622
- if (pendingKind !== void 0) {
1254
+ const pendingDebt = params().reviewMode === "inject" ? debt ?? pendingCadenceReviews.get(session.id) : mergeDebt(pendingCadenceReviews.get(session.id), debt);
1255
+ if (pendingDebt !== void 0) {
623
1256
  pendingCadenceReviews.delete(session.id);
624
1257
  if (params().reviewMode === "aux") {
625
- if (!await tryAuxReview(session, agent, pendingKind, signal, "cadence")) pendingCadenceReviews.set(session.id, pendingKind);
1258
+ await consumeReviewDebt(session.id, pendingDebt);
1259
+ await scheduleAuxDebt(session, agent, pendingDebt, signal, "cadence");
626
1260
  return;
627
1261
  }
1262
+ const pendingKind = injectKind(pendingDebt);
1263
+ if (pendingKind === null) return;
628
1264
  if (params().reviewMode === "inject") {
629
1265
  if (!deliverMessage(agent, reviewPrompt(pendingKind), cadenceSummary(pendingKind), true)) {
630
- pendingCadenceReviews.set(session.id, pendingKind);
1266
+ pendingCadenceReviews.set(session.id, pendingDebt);
631
1267
  return;
632
1268
  }
633
1269
  emitReviewScheduled(ctx, {
@@ -642,8 +1278,9 @@ function apply(ctx, rawConfig = {}) {
642
1278
  return;
643
1279
  }
644
1280
  }
645
- if (kind && event.data.reason.kind !== "completed") {
646
- pendingCadenceReviews.set(session.id, kind);
1281
+ if (debt !== null && event.data.reason.kind !== "completed") {
1282
+ const pending = params().reviewMode === "inject" ? debt : mergeDebt(pendingCadenceReviews.get(session.id), debt);
1283
+ pendingCadenceReviews.set(session.id, pending);
647
1284
  if (!pendingCadenceWarned.has(session.id)) {
648
1285
  pendingCadenceWarned.add(session.id);
649
1286
  ctx.logger.warn(`dsh-evolution-review: ${kind} review threshold reached; the review runs at the end of the conversation (no mid-task execution)`);
@@ -789,6 +1426,9 @@ function apply(ctx, rawConfig = {}) {
789
1426
  * created; the parent Agent is used only for tool scope/approval, with no log.
790
1427
  */
791
1428
  let inFlightControllers = /* @__PURE__ */ new Set();
1429
+ const reviewWriteLocks = new ReviewWriteLocks();
1430
+ const auxLimiter = new ReviewLimiter(2);
1431
+ let ptcToolHost;
792
1432
  /**
793
1433
  * Freeze the parent prefix for an aux review.
794
1434
  *
@@ -820,40 +1460,77 @@ function apply(ctx, rawConfig = {}) {
820
1460
  return typeof value === "function" ? value.bind(target) : value;
821
1461
  } });
822
1462
  }
1463
+ async function scheduleAuxDebt(session, agent, debt, signal, reason) {
1464
+ const tasks = [];
1465
+ if (debt.memory) tasks.push(tryAuxReview(session, agent, "memory", signal, reason));
1466
+ if (debt.skill) tasks.push(tryAuxReview(session, agent, "skill", signal, reason));
1467
+ await Promise.all(tasks);
1468
+ }
1469
+ async function consumeReviewDebt(sessionId, debt) {
1470
+ await withReviewStateLock(sessionId, async () => {
1471
+ const service = ctx.get("evolutionState");
1472
+ const state = await service?.loadReviewState(sessionId);
1473
+ if (state === void 0 || state === null) return;
1474
+ if (debt.memory) state.turnsSinceMemory = 0;
1475
+ if (debt.skill) state.turnsSinceSkill = 0;
1476
+ await service?.saveReviewState(sessionId, state);
1477
+ });
1478
+ }
823
1479
  async function tryAuxReview(session, agent, kind, signal, reason) {
824
- const running = auxRunning.get(session.id);
1480
+ let runningByKind = auxRunning.get(session.id);
1481
+ if (runningByKind === void 0) {
1482
+ runningByKind = /* @__PURE__ */ new Map();
1483
+ auxRunning.set(session.id, runningByKind);
1484
+ }
1485
+ const running = runningByKind.get(kind);
825
1486
  if (running !== void 0) {
826
1487
  running.rerun = kind;
827
1488
  return true;
828
1489
  }
1490
+ const state = {};
1491
+ runningByKind.set(kind, state);
1492
+ const releaseKind = () => {
1493
+ runningByKind.delete(kind);
1494
+ if (runningByKind.size === 0) auxRunning.delete(session.id);
1495
+ };
1496
+ const projectedPreset = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
1497
+ const headerPreset = session.header?.agentPreset;
1498
+ if ((typeof projectedPreset === "string" ? projectedPreset : typeof headerPreset === "string" ? headerPreset : void 0) === "minimal") {
1499
+ releaseKind();
1500
+ ctx.logger.info("dsh-evolution-review: minimal preset has no family review surface");
1501
+ return true;
1502
+ }
829
1503
  const reviewParent = snapshotReviewParent(agent);
830
1504
  const header = session.requestHeader();
831
1505
  if (header === void 0) {
1506
+ releaseKind();
832
1507
  ctx.logger.warn("dsh-evolution-review: aux review skipped — parent has no request header");
833
1508
  return false;
834
1509
  }
835
1510
  const llm = llmPort(ctx)?.streamRaw;
836
- const tools = toolsPort(ctx)?.execute;
1511
+ const toolsService = toolsPort(ctx);
1512
+ const tools = toolsService?.execute;
837
1513
  if (llm === void 0 || tools === void 0) {
1514
+ releaseKind();
838
1515
  ctx.logger.warn("dsh-evolution-review: aux review skipped — llm/tools service is not mounted");
839
1516
  return false;
840
1517
  }
841
1518
  const authority = ctx.get("evolutionMutationAuthority");
842
1519
  let leaseToken;
843
1520
  if (authority?.lease !== void 0) {
844
- const lease = await authority.lease.acquire("background_review", "review:" + session.id, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
1521
+ const lease = await authority.lease.acquire("background_review", "review:" + session.id + ":" + kind, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
845
1522
  if (lease === void 0) {
1523
+ releaseKind();
846
1524
  ctx.logger.warn("dsh-evolution-review: aux review skipped — lease acquire failed");
847
1525
  return false;
848
1526
  }
849
1527
  if (!lease.ok) {
1528
+ releaseKind();
850
1529
  ctx.logger.warn("dsh-evolution-review: aux review already leased (" + lease.reason + ")");
851
1530
  return false;
852
1531
  }
853
1532
  leaseToken = lease.token;
854
1533
  }
855
- const state = {};
856
- auxRunning.set(session.id, state);
857
1534
  const reviewId = "aux-" + randomUUID();
858
1535
  const startedAt = Date.now();
859
1536
  const controller = new AbortController();
@@ -881,6 +1558,35 @@ function apply(ctx, rawConfig = {}) {
881
1558
  "grep"
882
1559
  ]);
883
1560
  const toolAllow = new Set((header.tools ?? []).map((tool) => tool.name).filter((name) => AUX_TOOL_ALLOW.has(name)));
1561
+ const nativeChannel = nativeReviewToolChannel(reviewParent, toolAllow, { execute: tools }, agent);
1562
+ const ptcOnly = toolAllow.size === 0 && (header.tools ?? []).some((tool) => tool.name === "run_code");
1563
+ let reviewChild;
1564
+ let channel = nativeChannel;
1565
+ try {
1566
+ reviewChild = ptcOnly && toolsService !== void 0 ? await createReviewChildAgent(agent, reviewId, { ptc: true }) : void 0;
1567
+ if (reviewChild !== void 0 && toolsService !== void 0 && ptcToolHost === void 0) {
1568
+ ptcToolHost = new PtcReviewToolHost(toolsService, reviewWriteLocks);
1569
+ ptcToolHost.register();
1570
+ }
1571
+ if (reviewChild !== void 0 && ptcToolHost !== void 0) channel = ptcToolHost.channel(reviewId, header.tools ?? [], reviewChild.agent, {
1572
+ provider: header.config.provider,
1573
+ model: header.config.model
1574
+ }, new Set([
1575
+ ...AUX_TOOL_ALLOW,
1576
+ "run_code",
1577
+ "review_done",
1578
+ "review_wait"
1579
+ ]));
1580
+ } catch (error) {
1581
+ await reviewChild?.dispose();
1582
+ releaseKind();
1583
+ clearTimeout(timer);
1584
+ if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
1585
+ inFlightControllers.delete(controller);
1586
+ if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
1587
+ ctx.logger.warn("dsh-evolution-review: aux review setup failed: " + (error instanceof Error ? error.message : String(error)));
1588
+ return false;
1589
+ }
884
1590
  emitReviewScheduled(ctx, {
885
1591
  sessionId: session.id,
886
1592
  kind,
@@ -896,9 +1602,15 @@ function apply(ctx, rawConfig = {}) {
896
1602
  let usage;
897
1603
  let requests = 0;
898
1604
  let toolCalls = 0;
1605
+ let waitCount = 0;
1606
+ let hitRoundLimit = false;
1607
+ let report;
899
1608
  let error;
1609
+ let limiterRelease;
900
1610
  try {
901
- const prompt = reviewPrompt(kind, "aux");
1611
+ limiterRelease = await auxLimiter.acquire(controller.signal);
1612
+ if (limiterRelease === void 0) throw new Error("aux review queue aborted");
1613
+ const prompt = reviewPrompt(kind, "aux") + "\n\nWhen all durable changes for this review are complete, call review_done as the only tool call in your final batch. Do not call it while more edits remain. A precise no-op is still a completed review: always finish with review_done and an unchanged report instead of stopping without it. If a write is locked, call review_wait once, then re-read the target and retry; never reapply a stale patch." + (channel.instruction === void 0 ? "" : "\n\n" + channel.instruction);
902
1614
  const result = await withReviewContext({
903
1615
  reviewId,
904
1616
  runId: reviewId,
@@ -911,9 +1623,13 @@ function apply(ctx, rawConfig = {}) {
911
1623
  signal: input.signal,
912
1624
  agent
913
1625
  }) },
1626
+ channel,
1627
+ writeLocks: reviewWriteLocks,
1628
+ owner: reviewId,
914
1629
  instruction: prompt,
915
1630
  toolAllow,
916
1631
  maxRounds: config.reviewMaxRounds,
1632
+ maxToolCalls: config.reviewMaxToolCalls,
917
1633
  signal: controller.signal,
918
1634
  markReview: () => {},
919
1635
  clearReview: () => {}
@@ -922,20 +1638,28 @@ function apply(ctx, rawConfig = {}) {
922
1638
  actions = result.actions;
923
1639
  requests = result.requests;
924
1640
  toolCalls = result.toolCalls;
1641
+ waitCount = result.waitCount;
1642
+ hitRoundLimit = result.hitRoundLimit;
1643
+ report = result.report;
925
1644
  if (result.usage !== void 0) usage = {
926
1645
  inputTokens: result.usage.inputTokens ?? 0,
927
1646
  outputTokens: result.usage.outputTokens ?? 0,
928
1647
  cacheReadTokens: result.usage.cacheReadTokens ?? 0,
929
1648
  cacheWriteTokens: 0
930
1649
  };
931
- status = toolAllow.size === 0 ? "failed" : "completed";
932
- if (toolAllow.size === 0) error = "aux review has no allowed tools for this parent (PTC-only header); refusing to report completed";
1650
+ status = result.done && result.partialReason === void 0 ? "completed" : "partial";
1651
+ if (result.partialReason !== void 0) error = result.partialReason;
1652
+ if (toolAllow.size === 0 && reviewChild === void 0) {
1653
+ status = "failed";
1654
+ error = "aux review has no allowed tools for this parent; refusing to report completed";
1655
+ }
933
1656
  } catch (caught) {
934
1657
  error = caught instanceof Error ? caught.message : String(caught);
935
1658
  if (caught instanceof ReviewPartialFailure && caught.actions.length > 0) actions = caught.actions;
936
1659
  status = timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "failed";
937
1660
  ctx.logger.warn("dsh-evolution-review: aux review failed: " + error);
938
1661
  } finally {
1662
+ limiterRelease?.();
939
1663
  clearTimeout(timer);
940
1664
  if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
941
1665
  const finishedAt = Date.now();
@@ -943,9 +1667,16 @@ function apply(ctx, rawConfig = {}) {
943
1667
  ctx.emit("evolution/review-completed", {
944
1668
  version: 1,
945
1669
  reviewId,
1670
+ taskId: reviewId,
946
1671
  sessionId: String(session.id),
947
1672
  kind,
948
1673
  status,
1674
+ toolMode: channel.mode,
1675
+ ...(() => {
1676
+ const projected = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
1677
+ const preset = typeof projected === "string" ? projected : typeof session.header?.agentPreset === "string" ? session.header.agentPreset : void 0;
1678
+ return preset === void 0 ? {} : { preset };
1679
+ })(),
949
1680
  trigger: {
950
1681
  reason,
951
1682
  toolCalls: signal.toolCalls,
@@ -956,6 +1687,10 @@ function apply(ctx, rawConfig = {}) {
956
1687
  actions,
957
1688
  requests,
958
1689
  toolCalls,
1690
+ waitCount,
1691
+ hitRoundLimit,
1692
+ ...report === void 0 ? {} : { report },
1693
+ ...status === "partial" && error !== void 0 ? { partialReason: error } : status === "timeout" ? { partialReason: "review-timeout" } : {},
959
1694
  ...usage === void 0 ? {} : { usage },
960
1695
  startedAt,
961
1696
  finishedAt,
@@ -982,8 +1717,15 @@ function apply(ctx, rawConfig = {}) {
982
1717
  } catch (emitError) {
983
1718
  ctx.logger.warn("dsh-evolution-review: aux plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
984
1719
  }
985
- auxRunning.delete(session.id);
1720
+ const active = auxRunning.get(session.id);
1721
+ active?.delete(kind);
1722
+ if (active !== void 0 && active.size === 0) auxRunning.delete(session.id);
986
1723
  inFlightControllers.delete(controller);
1724
+ try {
1725
+ await reviewChild?.dispose();
1726
+ } catch (disposeError) {
1727
+ ctx.logger.warn("dsh-evolution-review: PTC review child dispose failed: " + (disposeError instanceof Error ? disposeError.message : String(disposeError)));
1728
+ }
987
1729
  if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
988
1730
  if (state.rerun !== void 0) tryAuxReview(session, agent, state.rerun, signal, reason);
989
1731
  }
@@ -993,6 +1735,9 @@ function apply(ctx, rawConfig = {}) {
993
1735
  ctx.effect(() => () => {
994
1736
  for (const controller of inFlightControllers) controller.abort();
995
1737
  inFlightControllers = /* @__PURE__ */ new Set();
1738
+ reviewWriteLocks.dispose();
1739
+ auxLimiter.dispose();
1740
+ ptcToolHost?.dispose();
996
1741
  sessionState.dispose();
997
1742
  }, "dsh-evolution-review.cleanup");
998
1743
  }