@lmzhen/dsh-evolution-review 0.58.0 → 0.59.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/lib/index.js CHANGED
@@ -1,8 +1,9 @@
1
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 { BlockAssembler, SessionId, createToolResultMessage, createUserMessage } 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, 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";
6
7
  import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-evolution-core/skills";
7
8
  //#region lib/types/review-executor.js
8
9
  /**
@@ -14,6 +15,98 @@ import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-
14
15
  *
15
16
  * @module @lmzhen/dsh-evolution-review/review-executor
16
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
+ }
17
110
  var ReviewModelError = class extends Error {
18
111
  code;
19
112
  constructor(message, code) {
@@ -68,6 +161,7 @@ async function runReview(input) {
68
161
  const header = parent.session.requestHeader();
69
162
  if (header === void 0) throw new Error("review requires the parent request header");
70
163
  const beforeSeq = parent.session.seq;
164
+ const toolHistory = input.channel?.mode === "ptc" ? parent.session.toolHistory?.() : void 0;
71
165
  const messages = [...parent.session.deriveMessages(), createUserMessage({
72
166
  content: [{
73
167
  type: "text",
@@ -75,13 +169,18 @@ async function runReview(input) {
75
169
  }],
76
170
  source: { kind: "evolution-review" }
77
171
  })];
78
- const toolHistory = parent.session.toolHistory();
79
172
  const maxRounds = input.maxRounds ?? 4;
173
+ const maxToolCalls = input.maxToolCalls ?? 50;
80
174
  const actions = [];
81
175
  let finalText = "";
82
176
  let usage;
83
177
  let requests = 0;
84
178
  let toolCalls = 0;
179
+ let done = false;
180
+ let hitRoundLimit = false;
181
+ let partialReason;
182
+ let report;
183
+ let waitCount = 0;
85
184
  markReview();
86
185
  try {
87
186
  for (let round = 0; round < maxRounds; round += 1) {
@@ -94,7 +193,7 @@ async function runReview(input) {
94
193
  ...header.config.temperature === void 0 ? {} : { temperature: header.config.temperature },
95
194
  ...header.config.maxTokens === void 0 ? {} : { maxTokens: header.config.maxTokens },
96
195
  messages,
97
- ...header.tools === void 0 ? {} : { tools: [...header.tools] },
196
+ tools: [...input.channel?.visibleTools ?? header.tools ?? [], ...input.channel?.mode === "ptc" ? [] : [REVIEW_WAIT_TOOL, REVIEW_DONE_TOOL]],
98
197
  ...toolHistory === void 0 ? {} : { toolHistory },
99
198
  signal
100
199
  }, signal);
@@ -116,19 +215,137 @@ async function runReview(input) {
116
215
  if (text !== "") finalText = text;
117
216
  const calls = assistant.content.filter((block) => block.type === "tool-call");
118
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
+ }
119
275
  messages.push(assistant);
120
- const allowedCalls = calls.filter((call) => toolAllow.has(call.name));
121
- const batch = allowedCalls.length === 0 ? { results: [] } : await tools.execute({
122
- calls: allowedCalls,
123
- signal,
124
- agent: parent
125
- });
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
+ }
126
325
  const byCall = new Map(batch.results.map((item) => [item.callId, item]));
127
- const allowedNames = [...toolAllow].sort().join(", ");
326
+ const allowedLabel = [...allowedNames].sort().join(", ");
128
327
  for (const call of calls) {
129
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
+ }
130
347
  if (item === void 0) {
131
- 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");
132
349
  actions.push({
133
350
  type: actionType(call.name),
134
351
  action: call.name,
@@ -139,7 +356,7 @@ async function runReview(input) {
139
356
  callId: call.id,
140
357
  content: [{
141
358
  type: "text",
142
- 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}`
143
360
  }],
144
361
  isError: true
145
362
  }));
@@ -162,20 +379,430 @@ async function runReview(input) {
162
379
  }));
163
380
  }
164
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;
165
387
  if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review tool mutated the parent Session", actions);
166
388
  }
167
389
  } finally {
168
390
  clearReview();
169
391
  }
170
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";
171
395
  return {
172
396
  finalText,
173
397
  actions,
174
398
  ...usage === void 0 ? {} : { usage },
175
399
  requests,
176
- toolCalls
400
+ toolCalls,
401
+ done,
402
+ hitRoundLimit,
403
+ waitCount,
404
+ ...report === void 0 ? {} : { report },
405
+ ...partialReason === void 0 ? {} : { partialReason }
406
+ };
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
+ }
177
438
  };
178
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
+ /** Build the PTC program SDK text from the child's assembled tool sections. */
473
+ async function ptcSdkInstruction(tools, childAgent, allowedTools) {
474
+ const systemPrompt = (childAgent?.ctx)?.get?.("systemPrompt");
475
+ if (systemPrompt === void 0 || typeof systemPrompt.assemble !== "function" || tools.resolve === void 0) return "";
476
+ const toolSet = filterToolSet(await tools.resolve({ agent: childAgent }), allowedTools);
477
+ return (await systemPrompt.assemble({
478
+ scope: childAgent,
479
+ toolSet
480
+ })).sections.filter((section) => section.name === "tools:ptc-only" || section.name === "tools:sdk").map((section) => section.text).filter((text) => text.length > 0).join("\n\n");
481
+ }
482
+ 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.";
483
+ function asObject(value) {
484
+ return value !== null && typeof value === "object" ? value : void 0;
485
+ }
486
+ function controlFor(controls, exec) {
487
+ const reviewId = currentReviewContext()?.reviewId;
488
+ if (reviewId !== void 0 && controls.has(reviewId)) return controls.get(reviewId);
489
+ const sessionId = exec?.agent?.session?.id;
490
+ const text = typeof sessionId === "string" ? sessionId : String(sessionId ?? "");
491
+ for (const [taskId, control] of controls) if (text.startsWith("review-child:" + taskId + ":")) return control;
492
+ }
493
+ function reviewDefinitions(controls, locks) {
494
+ return [defineTool({
495
+ name: REVIEW_DONE_TOOL_NAME,
496
+ description: "Finish the review. Must be the only review action in its program.",
497
+ parameters: {
498
+ summary: {
499
+ type: "string",
500
+ required: true
501
+ },
502
+ memoryChanged: {
503
+ type: "boolean",
504
+ required: true
505
+ },
506
+ skillsChanged: {
507
+ type: "array",
508
+ items: { type: "string" },
509
+ required: true
510
+ },
511
+ unresolved: {
512
+ type: "array",
513
+ items: { type: "string" },
514
+ required: true
515
+ }
516
+ },
517
+ output: {
518
+ schema: {
519
+ type: "object",
520
+ additionalProperties: false,
521
+ properties: { ok: {
522
+ type: "boolean",
523
+ required: true
524
+ } }
525
+ },
526
+ render: () => [{
527
+ type: "text",
528
+ text: "review_done accepted"
529
+ }]
530
+ },
531
+ async execute(args, exec) {
532
+ const raw = asObject(args);
533
+ if (raw === void 0) return { ok: false };
534
+ const parsed = parseReviewReport(JSON.stringify(raw));
535
+ const control = controlFor(controls, exec);
536
+ if (parsed === void 0 || control === void 0) return { ok: false };
537
+ control.report = parsed;
538
+ control.done = true;
539
+ return { ok: true };
540
+ }
541
+ }), defineTool({
542
+ name: REVIEW_WAIT_TOOL_NAME,
543
+ description: "Wait for a review resource lock after resource-busy; re-read before retrying.",
544
+ parameters: {
545
+ resource: {
546
+ type: "string",
547
+ required: true
548
+ },
549
+ timeoutMs: { type: "number" }
550
+ },
551
+ output: {
552
+ schema: {
553
+ type: "object",
554
+ additionalProperties: false,
555
+ properties: { ok: {
556
+ type: "boolean",
557
+ required: true
558
+ } }
559
+ },
560
+ render: (_args, value) => [{
561
+ type: "text",
562
+ text: value.ok ? "review_wait released" : "review_wait timed out"
563
+ }]
564
+ },
565
+ async execute(args, exec) {
566
+ const raw = asObject(args);
567
+ const resource = typeof raw?.resource === "string" ? raw.resource : "";
568
+ const timeoutMs = typeof raw?.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : 1e3;
569
+ const control = controlFor(controls, exec);
570
+ if (control === void 0) return { ok: false };
571
+ control.waitCount += 1;
572
+ if (resource === "") return { ok: true };
573
+ return { ok: await locks.wait(resource, timeoutMs, exec.signal) };
574
+ }
575
+ })];
576
+ }
577
+ /**
578
+ * One shared registration surface for all PTC review channels in this plugin
579
+ * instance. Construct once, `register()` once, then `channel()` per task.
580
+ */
581
+ var PtcReviewToolHost = class {
582
+ tools;
583
+ locks;
584
+ controls = /* @__PURE__ */ new Map();
585
+ active = /* @__PURE__ */ new Set();
586
+ disposers = [];
587
+ registered = false;
588
+ constructor(tools, locks) {
589
+ this.tools = tools;
590
+ this.locks = locks;
591
+ }
592
+ /** Register the review-only tools once; idempotent. */
593
+ register() {
594
+ if (this.registered) return;
595
+ this.registered = true;
596
+ this.disposers = reviewDefinitions(this.controls, this.locks).map((definition) => this.tools.register(definition, { when: () => {
597
+ const reviewId = currentReviewContext()?.reviewId;
598
+ return reviewId !== void 0 && this.active.has(reviewId);
599
+ } }));
600
+ }
601
+ /**
602
+ * Build one task channel over the shared registration.
603
+ *
604
+ * `toolSetAgent` owns the TOOL CATALOG used for the program SDK; `childAgent`
605
+ * owns execution and its detached session. They are deliberately separate:
606
+ * the child's own PTC presentation view exposes only `run_code`, while the
607
+ * nested program must see the review tools inherited from the parent. Resolve
608
+ * the former from the parent and execute/dispatch as the child.
609
+ */
610
+ async channel(taskId, parentHeaderTools, childAgent, modelSelection, allowedTools, toolSetAgent = childAgent) {
611
+ this.register();
612
+ this.active.add(taskId);
613
+ const sdk = await ptcSdkInstruction(this.tools, childAgent, allowedTools).catch(() => "");
614
+ const control = {
615
+ done: false,
616
+ waitCount: 0
617
+ };
618
+ this.controls.set(taskId, control);
619
+ const host = this;
620
+ return {
621
+ mode: "ptc",
622
+ visibleTools: parentHeaderTools,
623
+ instruction: sdk === "" ? 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.\n\n" + sdk,
624
+ control,
625
+ completion: () => control.done && control.report !== void 0 ? {
626
+ done: true,
627
+ report: control.report,
628
+ waitCount: control.waitCount
629
+ } : void 0,
630
+ async execute(calls, signal) {
631
+ if (host.tools.execute === void 0) throw new Error("PTC review channel requires tools.execute");
632
+ if (host.tools.resolve === void 0) throw new Error("PTC review channel requires tools.resolve for the review allowlist");
633
+ const toolSet = filterToolSet(await host.tools.resolve({
634
+ agent: toolSetAgent,
635
+ modelSelection,
636
+ signal
637
+ }), allowedTools);
638
+ return await host.tools.execute({
639
+ calls,
640
+ signal,
641
+ agent: childAgent,
642
+ ...toolSet === void 0 ? {} : { toolSet }
643
+ });
644
+ },
645
+ dispose() {
646
+ host.active.delete(taskId);
647
+ host.controls.delete(taskId);
648
+ }
649
+ };
650
+ }
651
+ /** Remove the global registrations; used when the plugin fiber unloads. */
652
+ dispose() {
653
+ for (const dispose of this.disposers.reverse()) dispose();
654
+ this.disposers = [];
655
+ this.controls.clear();
656
+ this.active.clear();
657
+ this.registered = false;
658
+ }
659
+ };
660
+ //#endregion
661
+ //#region lib/types/review-write-locks.js
662
+ /**
663
+ * Process-local review write locks.
664
+ *
665
+ * The SkillLibrary's per-directory lock + CAS is the final correctness layer.
666
+ * This small registry gives the review model the *recoverable* state it needs:
667
+ * a second review writing the same skill/memory resource gets a `resource-busy`
668
+ * tool result instead of racing silently, and `review_wait` can wait for the
669
+ * holder to release before the model re-reads and retries.
670
+ *
671
+ * It is intentionally not durable and does not coordinate foreground writers or
672
+ * other processes; those keep their existing HomeFence/CAS guarantees.
673
+ *
674
+ * @module @lmzhen/dsh-evolution-review/review-write-locks
675
+ */
676
+ /** One process-local holder per resource plus its waiters. */
677
+ var ReviewWriteLocks = class {
678
+ closed = false;
679
+ holders = /* @__PURE__ */ new Map();
680
+ waiters = /* @__PURE__ */ new Map();
681
+ /** @returns the holder when the resource is busy, otherwise undefined. */
682
+ holder(resource) {
683
+ return this.holders.get(resource)?.owner;
684
+ }
685
+ /** Drop all holders and wake waiters; used when the plugin fiber unloads. */
686
+ dispose() {
687
+ this.closed = true;
688
+ this.holders.clear();
689
+ for (const waiting of this.waiters.values()) for (const wake of waiting) wake();
690
+ this.waiters.clear();
691
+ }
692
+ /**
693
+ * Try to become the holder.
694
+ * @returns the release callback, or undefined when another owner holds it.
695
+ */
696
+ tryAcquire(resource, owner) {
697
+ if (this.closed || this.holders.has(resource)) return void 0;
698
+ this.holders.set(resource, { owner });
699
+ let released = false;
700
+ return () => {
701
+ if (released) return;
702
+ released = true;
703
+ this.holders.delete(resource);
704
+ const waiting = this.waiters.get(resource);
705
+ if (waiting === void 0) return;
706
+ this.waiters.delete(resource);
707
+ for (const wake of waiting) wake();
708
+ };
709
+ }
710
+ /**
711
+ * Wait until the resource has no holder.
712
+ * @returns true when free, false on timeout/abort.
713
+ */
714
+ async wait(resource, timeoutMs, signal) {
715
+ if (this.closed) return false;
716
+ if (!this.holders.has(resource)) return true;
717
+ if (signal.aborted) return false;
718
+ return await new Promise((resolve) => {
719
+ let finished = false;
720
+ const finish = (value) => {
721
+ if (finished) return;
722
+ finished = true;
723
+ clearTimeout(timer);
724
+ signal.removeEventListener("abort", onAbort);
725
+ this.waiters.get(resource)?.delete(wake);
726
+ if (this.waiters.get(resource)?.size === 0) this.waiters.delete(resource);
727
+ resolve(value);
728
+ };
729
+ const wake = () => {
730
+ if (this.closed) finish(false);
731
+ else if (!this.holders.has(resource)) finish(true);
732
+ };
733
+ const waiting = this.waiters.get(resource) ?? /* @__PURE__ */ new Set();
734
+ waiting.add(wake);
735
+ this.waiters.set(resource, waiting);
736
+ const timer = setTimeout(() => finish(false), Math.max(1, timeoutMs));
737
+ const onAbort = () => finish(false);
738
+ signal.addEventListener("abort", onAbort, { once: true });
739
+ });
740
+ }
741
+ };
742
+ //#endregion
743
+ //#region lib/types/review-limiter.js
744
+ /**
745
+ * Process-local bound on concurrent AUX reviews.
746
+ *
747
+ * The family deliberately keeps this small: one semaphore for the plugin
748
+ * instance, no per-session or weighted fairness. A review waits for a slot
749
+ * before its first model request; the bounded queue is what keeps a burst of
750
+ * sessions from opening unbounded LLM streams.
751
+ *
752
+ * @module @lmzhen/dsh-evolution-review/review-limiter
753
+ */
754
+ /** A tiny FIFO semaphore whose waiters can be aborted by unload/timeout. */
755
+ var ReviewLimiter = class {
756
+ limit;
757
+ active = 0;
758
+ closed = false;
759
+ waiters = [];
760
+ constructor(limit) {
761
+ this.limit = limit;
762
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("review limiter limit must be a positive integer");
763
+ }
764
+ /** Wait for a slot; undefined means the wait was aborted or the limiter closed. */
765
+ async acquire(signal) {
766
+ if (this.closed || signal?.aborted === true) return void 0;
767
+ if (this.active < this.limit) {
768
+ this.active += 1;
769
+ return this.releaseOnce();
770
+ }
771
+ return await new Promise((resolve) => {
772
+ const waiter = { resolve };
773
+ if (signal !== void 0) {
774
+ waiter.signal = signal;
775
+ waiter.onAbort = () => {
776
+ const index = this.waiters.indexOf(waiter);
777
+ if (index >= 0) this.waiters.splice(index, 1);
778
+ resolve(void 0);
779
+ };
780
+ signal.addEventListener("abort", waiter.onAbort, { once: true });
781
+ }
782
+ this.waiters.push(waiter);
783
+ });
784
+ }
785
+ dispose() {
786
+ this.closed = true;
787
+ for (const waiter of this.waiters.splice(0)) {
788
+ if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
789
+ waiter.resolve(void 0);
790
+ }
791
+ }
792
+ releaseOnce() {
793
+ let released = false;
794
+ return () => {
795
+ if (released) return;
796
+ released = true;
797
+ this.active -= 1;
798
+ const waiter = this.waiters.shift();
799
+ if (waiter === void 0) return;
800
+ if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
801
+ this.active += 1;
802
+ waiter.resolve(this.releaseOnce());
803
+ };
804
+ }
805
+ };
179
806
  /**
180
807
  * Whether a message is a notice this plugin delivered, judged only by durable source fields.
181
808
  *
@@ -290,6 +917,9 @@ var SessionScopedState = class {
290
917
  */
291
918
  /** Model requests per auxiliary review run. One skill of incremental edits may need many rounds. */
292
919
  const DEFAULT_REVIEW_MAX_ROUNDS = 12;
920
+ /** Tool calls per auxiliary review run; completion is still required before this bound. */
921
+ const DEFAULT_REVIEW_MAX_TOOL_CALLS = 50;
922
+ const MAX_REVIEW_MAX_TOOL_CALLS = 500;
293
923
  /** Keep a mistyped deployment value from turning one review into an unbounded loop. */
294
924
  const MAX_REVIEW_MAX_ROUNDS = 200;
295
925
  /** Emit one `evolution/review-scheduled` inside its OWN protection domain (V8-03, V5-19③/F-334).
@@ -330,6 +960,7 @@ const Config = z.object({
330
960
  reviewSkillInterval: z.number().min(1).volatile(),
331
961
  reviewTimeoutMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_REVIEW_TIMEOUT_MS),
332
962
  reviewMaxRounds: z.number().min(1).max(MAX_REVIEW_MAX_ROUNDS).default(DEFAULT_REVIEW_MAX_ROUNDS),
963
+ reviewMaxToolCalls: z.number().min(1).max(MAX_REVIEW_MAX_TOOL_CALLS).default(DEFAULT_REVIEW_MAX_TOOL_CALLS),
333
964
  skillReviewTrigger: z.union([
334
965
  z.const("cadence"),
335
966
  z.const("completion"),
@@ -348,6 +979,20 @@ const Config = z.object({
348
979
  * kind: memory / skill / combined), both in the queue and in the session log.
349
980
  */
350
981
  const cadenceSummary = (kind) => `auto-review:${kind}`;
982
+ /** Foreground delivery still combines both due domains into one prompt. */
983
+ function injectKind(debt) {
984
+ if (debt === null) return null;
985
+ if (debt.memory && debt.skill) return "combined";
986
+ return debt.memory ? "memory" : debt.skill ? "skill" : null;
987
+ }
988
+ function mergeDebt(a, b) {
989
+ if (a === null || a === void 0) return b ?? void 0;
990
+ if (b === null || b === void 0) return a;
991
+ return {
992
+ memory: a.memory || b.memory,
993
+ skill: a.skill || b.skill
994
+ };
995
+ }
351
996
  /**
352
997
  * The DEPLOYMENT layer of this row, clamped once at assembly: the restart-only
353
998
  * numerics (registry tier E2) whose consumers read them from this snapshot. The
@@ -365,7 +1010,8 @@ function clampReviewConfig(rawConfig, ctx) {
365
1010
  const field = (name, value, fallback, min, max) => clampOnce(warned, warn, name, value, fallback, min, max);
366
1011
  return Object.assign({}, rawConfig, {
367
1012
  reviewTimeoutMs: field("reviewTimeoutMs", rawConfig.reviewTimeoutMs, DEFAULT_REVIEW_TIMEOUT_MS, 1, MAX_TIMER_DELAY_MS),
368
- reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS)
1013
+ reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS),
1014
+ reviewMaxToolCalls: field("reviewMaxToolCalls", rawConfig.reviewMaxToolCalls, DEFAULT_REVIEW_MAX_TOOL_CALLS, 1, MAX_REVIEW_MAX_TOOL_CALLS)
369
1015
  });
370
1016
  }
371
1017
  /**
@@ -597,7 +1243,7 @@ function apply(ctx, rawConfig = {}) {
597
1243
  turnsSinceSkill: 0,
598
1244
  lastTurn: -1
599
1245
  };
600
- const advanced = { kind: null };
1246
+ const advanced = { debt: null };
601
1247
  if (settlesHere) await settleNotice(session.id, "turn-end");
602
1248
  else await withReviewStateLock(session.id, async () => {
603
1249
  state = await stateService?.loadReviewState(session.id) ?? {
@@ -605,7 +1251,7 @@ function apply(ctx, rawConfig = {}) {
605
1251
  turnsSinceSkill: 0,
606
1252
  lastTurn: -1
607
1253
  };
608
- advanced.kind = advanceReview(state, event.data.turn, signal, {
1254
+ advanced.debt = advanceReview(state, event.data.turn, signal, {
609
1255
  memoryInterval: params().reviewMemoryInterval,
610
1256
  skillInterval: params().reviewSkillInterval,
611
1257
  substantiveMinToolCalls: snapshot?.substantiveMinToolCalls ?? DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS,
@@ -615,20 +1261,24 @@ function apply(ctx, rawConfig = {}) {
615
1261
  });
616
1262
  await stateService?.saveReviewState(session.id, state);
617
1263
  });
618
- const kind = advanced.kind;
1264
+ const debt = advanced.debt;
1265
+ const kind = injectKind(debt);
619
1266
  const cumulative = (cumulativeToolCalls.get(session.id) ?? 0) + signal.toolCalls;
620
1267
  cumulativeToolCalls.set(session.id, cumulative);
621
1268
  if (event.data.reason.kind === "completed") {
622
- const pendingKind = kind ?? pendingCadenceReviews.get(session.id) ?? void 0;
623
- if (pendingKind !== void 0) {
1269
+ const pendingDebt = params().reviewMode === "inject" ? debt ?? pendingCadenceReviews.get(session.id) : mergeDebt(pendingCadenceReviews.get(session.id), debt);
1270
+ if (pendingDebt !== void 0) {
624
1271
  pendingCadenceReviews.delete(session.id);
625
1272
  if (params().reviewMode === "aux") {
626
- if (!await tryAuxReview(session, agent, pendingKind, signal, "cadence")) pendingCadenceReviews.set(session.id, pendingKind);
1273
+ await consumeReviewDebt(session.id, pendingDebt);
1274
+ await scheduleAuxDebt(session, agent, pendingDebt, signal, "cadence");
627
1275
  return;
628
1276
  }
1277
+ const pendingKind = injectKind(pendingDebt);
1278
+ if (pendingKind === null) return;
629
1279
  if (params().reviewMode === "inject") {
630
1280
  if (!deliverMessage(agent, reviewPrompt(pendingKind), cadenceSummary(pendingKind), true)) {
631
- pendingCadenceReviews.set(session.id, pendingKind);
1281
+ pendingCadenceReviews.set(session.id, pendingDebt);
632
1282
  return;
633
1283
  }
634
1284
  emitReviewScheduled(ctx, {
@@ -643,8 +1293,9 @@ function apply(ctx, rawConfig = {}) {
643
1293
  return;
644
1294
  }
645
1295
  }
646
- if (kind && event.data.reason.kind !== "completed") {
647
- pendingCadenceReviews.set(session.id, kind);
1296
+ if (debt !== null && event.data.reason.kind !== "completed") {
1297
+ const pending = params().reviewMode === "inject" ? debt : mergeDebt(pendingCadenceReviews.get(session.id), debt);
1298
+ pendingCadenceReviews.set(session.id, pending);
648
1299
  if (!pendingCadenceWarned.has(session.id)) {
649
1300
  pendingCadenceWarned.add(session.id);
650
1301
  ctx.logger.warn(`dsh-evolution-review: ${kind} review threshold reached; the review runs at the end of the conversation (no mid-task execution)`);
@@ -790,6 +1441,9 @@ function apply(ctx, rawConfig = {}) {
790
1441
  * created; the parent Agent is used only for tool scope/approval, with no log.
791
1442
  */
792
1443
  let inFlightControllers = /* @__PURE__ */ new Set();
1444
+ const reviewWriteLocks = new ReviewWriteLocks();
1445
+ const auxLimiter = new ReviewLimiter(2);
1446
+ let ptcToolHost;
793
1447
  /**
794
1448
  * Freeze the parent prefix for an aux review.
795
1449
  *
@@ -821,40 +1475,77 @@ function apply(ctx, rawConfig = {}) {
821
1475
  return typeof value === "function" ? value.bind(target) : value;
822
1476
  } });
823
1477
  }
1478
+ async function scheduleAuxDebt(session, agent, debt, signal, reason) {
1479
+ const tasks = [];
1480
+ if (debt.memory) tasks.push(tryAuxReview(session, agent, "memory", signal, reason));
1481
+ if (debt.skill) tasks.push(tryAuxReview(session, agent, "skill", signal, reason));
1482
+ await Promise.all(tasks);
1483
+ }
1484
+ async function consumeReviewDebt(sessionId, debt) {
1485
+ await withReviewStateLock(sessionId, async () => {
1486
+ const service = ctx.get("evolutionState");
1487
+ const state = await service?.loadReviewState(sessionId);
1488
+ if (state === void 0 || state === null) return;
1489
+ if (debt.memory) state.turnsSinceMemory = 0;
1490
+ if (debt.skill) state.turnsSinceSkill = 0;
1491
+ await service?.saveReviewState(sessionId, state);
1492
+ });
1493
+ }
824
1494
  async function tryAuxReview(session, agent, kind, signal, reason) {
825
- const running = auxRunning.get(session.id);
1495
+ let runningByKind = auxRunning.get(session.id);
1496
+ if (runningByKind === void 0) {
1497
+ runningByKind = /* @__PURE__ */ new Map();
1498
+ auxRunning.set(session.id, runningByKind);
1499
+ }
1500
+ const running = runningByKind.get(kind);
826
1501
  if (running !== void 0) {
827
1502
  running.rerun = kind;
828
1503
  return true;
829
1504
  }
1505
+ const state = {};
1506
+ runningByKind.set(kind, state);
1507
+ const releaseKind = () => {
1508
+ runningByKind.delete(kind);
1509
+ if (runningByKind.size === 0) auxRunning.delete(session.id);
1510
+ };
1511
+ const projectedPreset = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
1512
+ const headerPreset = session.header?.agentPreset;
1513
+ if ((typeof projectedPreset === "string" ? projectedPreset : typeof headerPreset === "string" ? headerPreset : void 0) === "minimal") {
1514
+ releaseKind();
1515
+ ctx.logger.info("dsh-evolution-review: minimal preset has no family review surface");
1516
+ return true;
1517
+ }
830
1518
  const reviewParent = snapshotReviewParent(agent);
831
1519
  const header = session.requestHeader();
832
1520
  if (header === void 0) {
1521
+ releaseKind();
833
1522
  ctx.logger.warn("dsh-evolution-review: aux review skipped — parent has no request header");
834
1523
  return false;
835
1524
  }
836
1525
  const llm = llmPort(ctx)?.streamRaw;
837
- const tools = toolsPort(ctx)?.execute;
1526
+ const toolsService = toolsPort(ctx);
1527
+ const tools = toolsService?.execute;
838
1528
  if (llm === void 0 || tools === void 0) {
1529
+ releaseKind();
839
1530
  ctx.logger.warn("dsh-evolution-review: aux review skipped — llm/tools service is not mounted");
840
1531
  return false;
841
1532
  }
842
1533
  const authority = ctx.get("evolutionMutationAuthority");
843
1534
  let leaseToken;
844
1535
  if (authority?.lease !== void 0) {
845
- const lease = await authority.lease.acquire("background_review", "review:" + session.id, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
1536
+ const lease = await authority.lease.acquire("background_review", "review:" + session.id + ":" + kind, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
846
1537
  if (lease === void 0) {
1538
+ releaseKind();
847
1539
  ctx.logger.warn("dsh-evolution-review: aux review skipped — lease acquire failed");
848
1540
  return false;
849
1541
  }
850
1542
  if (!lease.ok) {
1543
+ releaseKind();
851
1544
  ctx.logger.warn("dsh-evolution-review: aux review already leased (" + lease.reason + ")");
852
1545
  return false;
853
1546
  }
854
1547
  leaseToken = lease.token;
855
1548
  }
856
- const state = {};
857
- auxRunning.set(session.id, state);
858
1549
  const reviewId = "aux-" + randomUUID();
859
1550
  const startedAt = Date.now();
860
1551
  const controller = new AbortController();
@@ -882,6 +1573,35 @@ function apply(ctx, rawConfig = {}) {
882
1573
  "grep"
883
1574
  ]);
884
1575
  const toolAllow = new Set((header.tools ?? []).map((tool) => tool.name).filter((name) => AUX_TOOL_ALLOW.has(name)));
1576
+ const nativeChannel = nativeReviewToolChannel(reviewParent, toolAllow, { execute: tools }, agent);
1577
+ const ptcOnly = toolAllow.size === 0 && (header.tools ?? []).some((tool) => tool.name === "run_code");
1578
+ let reviewChild;
1579
+ let channel = nativeChannel;
1580
+ try {
1581
+ reviewChild = ptcOnly && toolsService !== void 0 ? await createReviewChildAgent(agent, reviewId, { ptc: true }) : void 0;
1582
+ if (reviewChild !== void 0 && toolsService !== void 0 && ptcToolHost === void 0) {
1583
+ ptcToolHost = new PtcReviewToolHost(toolsService, reviewWriteLocks);
1584
+ ptcToolHost.register();
1585
+ }
1586
+ if (reviewChild !== void 0 && ptcToolHost !== void 0) channel = await ptcToolHost.channel(reviewId, header.tools ?? [], reviewChild.agent, {
1587
+ provider: header.config.provider,
1588
+ model: header.config.model
1589
+ }, new Set([
1590
+ ...AUX_TOOL_ALLOW,
1591
+ "run_code",
1592
+ "review_done",
1593
+ "review_wait"
1594
+ ]), agent);
1595
+ } catch (error) {
1596
+ await reviewChild?.dispose();
1597
+ releaseKind();
1598
+ clearTimeout(timer);
1599
+ if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
1600
+ inFlightControllers.delete(controller);
1601
+ if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
1602
+ ctx.logger.warn("dsh-evolution-review: aux review setup failed: " + (error instanceof Error ? error.message : String(error)));
1603
+ return false;
1604
+ }
885
1605
  emitReviewScheduled(ctx, {
886
1606
  sessionId: session.id,
887
1607
  kind,
@@ -897,9 +1617,15 @@ function apply(ctx, rawConfig = {}) {
897
1617
  let usage;
898
1618
  let requests = 0;
899
1619
  let toolCalls = 0;
1620
+ let waitCount = 0;
1621
+ let hitRoundLimit = false;
1622
+ let report;
900
1623
  let error;
1624
+ let limiterRelease;
901
1625
  try {
902
- const prompt = reviewPrompt(kind, "aux");
1626
+ limiterRelease = await auxLimiter.acquire(controller.signal);
1627
+ if (limiterRelease === void 0) throw new Error("aux review queue aborted");
1628
+ 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);
903
1629
  const result = await withReviewContext({
904
1630
  reviewId,
905
1631
  runId: reviewId,
@@ -912,9 +1638,13 @@ function apply(ctx, rawConfig = {}) {
912
1638
  signal: input.signal,
913
1639
  agent
914
1640
  }) },
1641
+ channel,
1642
+ writeLocks: reviewWriteLocks,
1643
+ owner: reviewId,
915
1644
  instruction: prompt,
916
1645
  toolAllow,
917
1646
  maxRounds: config.reviewMaxRounds,
1647
+ maxToolCalls: config.reviewMaxToolCalls,
918
1648
  signal: controller.signal,
919
1649
  markReview: () => {},
920
1650
  clearReview: () => {}
@@ -923,20 +1653,28 @@ function apply(ctx, rawConfig = {}) {
923
1653
  actions = result.actions;
924
1654
  requests = result.requests;
925
1655
  toolCalls = result.toolCalls;
1656
+ waitCount = result.waitCount;
1657
+ hitRoundLimit = result.hitRoundLimit;
1658
+ report = result.report;
926
1659
  if (result.usage !== void 0) usage = {
927
1660
  inputTokens: result.usage.inputTokens ?? 0,
928
1661
  outputTokens: result.usage.outputTokens ?? 0,
929
1662
  cacheReadTokens: result.usage.cacheReadTokens ?? 0,
930
1663
  cacheWriteTokens: 0
931
1664
  };
932
- status = toolAllow.size === 0 ? "failed" : "completed";
933
- if (toolAllow.size === 0) error = "aux review has no allowed tools for this parent (PTC-only header); refusing to report completed";
1665
+ status = result.done && result.partialReason === void 0 ? "completed" : "partial";
1666
+ if (result.partialReason !== void 0) error = result.partialReason;
1667
+ if (toolAllow.size === 0 && reviewChild === void 0) {
1668
+ status = "failed";
1669
+ error = "aux review has no allowed tools for this parent; refusing to report completed";
1670
+ }
934
1671
  } catch (caught) {
935
1672
  error = caught instanceof Error ? caught.message : String(caught);
936
1673
  if (caught instanceof ReviewPartialFailure && caught.actions.length > 0) actions = caught.actions;
937
1674
  status = timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "failed";
938
1675
  ctx.logger.warn("dsh-evolution-review: aux review failed: " + error);
939
1676
  } finally {
1677
+ limiterRelease?.();
940
1678
  clearTimeout(timer);
941
1679
  if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
942
1680
  const finishedAt = Date.now();
@@ -944,9 +1682,16 @@ function apply(ctx, rawConfig = {}) {
944
1682
  ctx.emit("evolution/review-completed", {
945
1683
  version: 1,
946
1684
  reviewId,
1685
+ taskId: reviewId,
947
1686
  sessionId: String(session.id),
948
1687
  kind,
949
1688
  status,
1689
+ toolMode: channel.mode,
1690
+ ...(() => {
1691
+ const projected = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
1692
+ const preset = typeof projected === "string" ? projected : typeof session.header?.agentPreset === "string" ? session.header.agentPreset : void 0;
1693
+ return preset === void 0 ? {} : { preset };
1694
+ })(),
950
1695
  trigger: {
951
1696
  reason,
952
1697
  toolCalls: signal.toolCalls,
@@ -957,6 +1702,10 @@ function apply(ctx, rawConfig = {}) {
957
1702
  actions,
958
1703
  requests,
959
1704
  toolCalls,
1705
+ waitCount,
1706
+ hitRoundLimit,
1707
+ ...report === void 0 ? {} : { report },
1708
+ ...status === "partial" && error !== void 0 ? { partialReason: error } : status === "timeout" ? { partialReason: "review-timeout" } : {},
960
1709
  ...usage === void 0 ? {} : { usage },
961
1710
  startedAt,
962
1711
  finishedAt,
@@ -983,8 +1732,15 @@ function apply(ctx, rawConfig = {}) {
983
1732
  } catch (emitError) {
984
1733
  ctx.logger.warn("dsh-evolution-review: aux plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
985
1734
  }
986
- auxRunning.delete(session.id);
1735
+ const active = auxRunning.get(session.id);
1736
+ active?.delete(kind);
1737
+ if (active !== void 0 && active.size === 0) auxRunning.delete(session.id);
987
1738
  inFlightControllers.delete(controller);
1739
+ try {
1740
+ await reviewChild?.dispose();
1741
+ } catch (disposeError) {
1742
+ ctx.logger.warn("dsh-evolution-review: PTC review child dispose failed: " + (disposeError instanceof Error ? disposeError.message : String(disposeError)));
1743
+ }
988
1744
  if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
989
1745
  if (state.rerun !== void 0) tryAuxReview(session, agent, state.rerun, signal, reason);
990
1746
  }
@@ -994,6 +1750,9 @@ function apply(ctx, rawConfig = {}) {
994
1750
  ctx.effect(() => () => {
995
1751
  for (const controller of inFlightControllers) controller.abort();
996
1752
  inFlightControllers = /* @__PURE__ */ new Set();
1753
+ reviewWriteLocks.dispose();
1754
+ auxLimiter.dispose();
1755
+ ptcToolHost?.dispose();
997
1756
  sessionState.dispose();
998
1757
  }, "dsh-evolution-review.cleanup");
999
1758
  }