llm-orchestrator 1.6.0 → 1.7.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/first-run.mjs CHANGED
@@ -184,6 +184,20 @@ export async function checkMandatoryTools(project) {
184
184
  ];
185
185
  }
186
186
 
187
+ /**
188
+ * Tools that are recommended by design rather than mandatory: worth installing at setup,
189
+ * never a gap that blocks. `applies` says whether this project makes the tool useful.
190
+ */
191
+ export async function checkRecommendedTools(project) {
192
+ const root = resolve(project);
193
+ const tools = registry('preferred-tools').tools;
194
+ const hint = (id) => tools.find((entry) => entry.id === id)?.install ?? null;
195
+ const copywriting = await anySkillDirNamed(root, 'copywriting');
196
+ return [
197
+ { id: 'content.copywriting', tool: 'copywriting', applies: true, when: 'any text written for people', present: copywriting, install_hint: hint('copywriting') },
198
+ ];
199
+ }
200
+
187
201
  const registry = (name) => JSON.parse(readFileSync(new URL(`../registries/${name}.json`, import.meta.url), 'utf8'));
188
202
 
189
203
  /**
@@ -194,12 +208,15 @@ const registry = (name) => JSON.parse(readFileSync(new URL(`../registries/${name
194
208
  */
195
209
  export async function checkConditionalMandatoryTools(project, { profile } = {}) {
196
210
  const root = resolve(project);
197
- const domains = new Set((profile ?? await discoverProject({ root })).domains ?? []);
211
+ const discovered = profile ?? await discoverProject({ root });
212
+ const domains = new Set(discovered.domains ?? []);
213
+ const serena = await anyConfigMentions(root, ['serena']);
198
214
  const tools = registry('preferred-tools').tools;
199
215
  const hint = (id) => tools.find((entry) => entry.id === id)?.install ?? null;
200
216
  const impeccable = await anySkillDirNamed(root, 'impeccable').then((v) => v || anyPluginDirNamed('impeccable'));
201
217
  return [
202
218
  { id: 'ui.design_system', tool: 'impeccable', applies: domains.has('frontend'), when: 'any FRONTEND-domain or UI/visual-design task', present: impeccable, install_hint: hint('impeccable') },
219
+ { id: 'code.semantic_edit', tool: 'serena', applies: (discovered.languages ?? []).length > 0, when: 'any task that locates or changes code', present: serena, install_hint: hint('serena') },
203
220
  ];
204
221
  }
205
222
 
@@ -280,6 +297,7 @@ export async function runInit({ project, harnesses, skillsRoot, apply = false, p
280
297
 
281
298
  const mandatory = await checkMandatoryTools(root);
282
299
  const conditional = await checkConditionalMandatoryTools(root);
300
+ const recommended = await checkRecommendedTools(root);
283
301
  const hasBindings = await agentsMdHasBindings(root);
284
302
  let bindingsWritten = false;
285
303
  if (!hasBindings && apply) {
@@ -318,6 +336,7 @@ export async function runInit({ project, harnesses, skillsRoot, apply = false, p
318
336
  install_plan_error: planError,
319
337
  mandatory_tools: mandatory,
320
338
  conditional_mandatory_tools: conditional,
339
+ recommended_tools: recommended,
321
340
  missing_mandatory_tools: missing,
322
341
  bindings_present: hasBindings || bindingsWritten,
323
342
  bindings_written: bindingsWritten,
@@ -348,9 +367,17 @@ export function formatInitReport(report) {
348
367
  const conditional = (report.conditional_mandatory_tools ?? []).filter((item) => item.applies);
349
368
  if (conditional.length > 0) {
350
369
  lines.push('');
351
- lines.push('Mandatory when the task is frontend/UI (this project has a UI framework):');
370
+ lines.push('Mandatory by domain (this project triggers them):');
352
371
  for (const item of conditional) {
353
- lines.push(` [${item.present ? 'present' : 'MISSING'}] ${item.id} (${item.tool})${item.present ? '' : ` — install: ${item.install_hint}`}`);
372
+ lines.push(` [${item.present ? 'present' : 'MISSING'}] ${item.id} (${item.tool})${item.present ? '' : ` — install: ${item.install_hint}`} — applies to ${item.when}`);
373
+ }
374
+ }
375
+ const recommended = (report.recommended_tools ?? []).filter((item) => item.applies);
376
+ if (recommended.length > 0) {
377
+ lines.push('');
378
+ lines.push('Recommended (never blocking; decline one with "llm-orchestrator tools skip <tool>"):');
379
+ for (const item of recommended) {
380
+ lines.push(` [${item.present ? 'present' : 'not installed'}] ${item.id} (${item.tool}) — for ${item.when}${item.present ? '' : ` — install: ${item.install_hint}`}`);
354
381
  }
355
382
  }
356
383
  lines.push('');
package/lib/flow-gate.mjs CHANGED
@@ -7,10 +7,13 @@
7
7
  * tool of an unplanned task. The harness hooks call `handleHook` on each prompt,
8
8
  * tool call and subagent start. With no run open, the first main-thread work tool
9
9
  * of a prompt gets one model-only sentence (`additionalContext`) pointing back at
10
- * the flow; everything else passes silently. Nothing here can deny a tool call or
11
- * stop a session.
10
+ * the flow; everything else passes silently. No other tool call is denied, and no
11
+ * session is stopped.
12
12
  *
13
- * One decision exists, at turn end only: when a typed run is still open and the
13
+ * Two decisions exist. A subagent start that no `dispatch` routed is denied, so the
14
+ * cheapest adequate model, a stored strategy card and the frontier budget are
15
+ * checked before every subagent (`routingDenialFor`; LLM_ORCHESTRATOR_NO_ENFORCE=1
16
+ * turns it back into a reminder). And at turn end: when a typed run is still open and the
14
17
  * model's last message says it is about to continue, the Stop hook answers
15
18
  * `decision: "block"` so the turn goes on instead of ending on an announcement
16
19
  * (`turnEndSignal`, `continueNudgeFor`). It is bounded per prompt, never fires
@@ -33,6 +36,7 @@ import { dirname, join } from 'node:path';
33
36
  import { fileURLToPath } from 'node:url';
34
37
 
35
38
  import { LEDGER_DIRECTORY, projectRoot, samePath } from './project-root.mjs';
39
+ import { dueToolUse, emptyToolUse, inheritToolUse, missingAtClose, projectToolBrief, recordToolUse, requiredToolUse, sessionRules, skipSet, toolRequiredFor, toolUseFacts, toolUseNudgeFor, toolUseRules } from './tool-use.mjs';
36
40
 
37
41
  const LOAD_FIRST = 'The orchestrate-core skill has not been loaded in this session: load the orchestrate-core skill first (Claude Code: the Skill tool, `orchestrate-core` or `llm-orchestrator:orchestrate-core`; other harnesses: the installed skill or the bridge `.agents/skills/orchestrate/SKILL.md`). ';
38
42
 
@@ -57,7 +61,7 @@ export const ENTRYPOINT_NOTICE = 'The orchestrate-core skill is mandatory in thi
57
61
 
58
62
  /** After a compaction or a resume the model may no longer hold the run it opened. */
59
63
  export function resumeNoticeFor(cli = 'llm-orchestrator', run = {}) {
60
- const shards = run.planned ? `, ${run.dispatched ?? 0} of ${run.planned} planned shards dispatched` : '';
64
+ const shards = run.planned ? `, ${run.planned} planned shard${run.planned === 1 ? '' : 's'}, ${run.dispatched ?? 0} subagent${run.dispatched === 1 ? '' : 's'} started` : '';
61
65
  return `An orchestrate-core run is still open in this session (${run.taskType ?? 'typed'}${shards}). Continue it: if the orchestrate-core instructions are no longer in context, load the skill again, then resume from the recorded state instead of re-planning. Close the run when the task is verified (\`${cli} run close\`).`;
62
66
  }
63
67
 
@@ -162,7 +166,11 @@ const EDIT_TOOLS = new Set(['edit', 'write', 'multiedit', 'notebookedit', 'str_r
162
166
  const TEST_PATH = /(^|\/)(test|tests|__tests__|spec|specs)\/|[._-](test|spec)\.[a-z0-9]+$|(^|\/)test_[^/]+\.py$|_spec\.rb$/i;
163
167
  const PATCH_FILE = /^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm;
164
168
 
169
+ // Serena's symbol edits change files too; their path is `relative_path`.
170
+ const SEMANTIC_EDIT = /serena.*(replace_symbol_body|insert_(after|before)_symbol|rename_symbol|safe_delete_symbol|replace_content|replace_in_files|create_text_file)/;
171
+
165
172
  function editedPaths(toolName, input) {
173
+ if (SEMANTIC_EDIT.test(toolName.toLowerCase())) return typeof input?.relative_path === 'string' ? [input.relative_path] : ['(symbol edit)'];
166
174
  if (!EDIT_TOOLS.has(toolName.toLowerCase())) return [];
167
175
  const command = commandOf(input);
168
176
  if (command && command.includes('*** Begin Patch')) return [...command.matchAll(PATCH_FILE)].map((match) => match[1].trim());
@@ -401,6 +409,105 @@ export function parseRunCommand(command) {
401
409
  return parsed;
402
410
  }
403
411
 
412
+ /**
413
+ * The routing steps a shell command runs: `route` (tier and thinking level),
414
+ * `strategy decide` (a stored strategy card, the advisor, or an upgrade in budget)
415
+ * and `budget spend` / `record` (the dispatch ledger). Counts per step.
416
+ */
417
+ export function parseRoutingCalls(command) {
418
+ const calls = { route: 0, decide: 0, spend: 0, advisor: 0, capture: 0 };
419
+ if (typeof command !== 'string' || !command.includes('llm-orchestrator')) return calls;
420
+ for (const words of shellCommands(command)) {
421
+ const args = orchestratorArgs(words);
422
+ if (!args) continue;
423
+ // `dispatch` is the three steps in one; a dry run decides but records nothing.
424
+ if (args[0] === 'dispatch') {
425
+ calls.route += 1;
426
+ calls.decide += 1;
427
+ if (!args.includes('--dry-run')) calls.spend += 1;
428
+ } else if (args[0] === 'route') calls.route += 1;
429
+ else if (args[0] === 'strategy' && (args[1] === 'decide' || args[1] === 'advisor')) {
430
+ calls.decide += 1;
431
+ if (args[1] === 'advisor' && args.includes('--run')) calls.advisor += 1;
432
+ } else if (args[0] === 'strategy' && args[1] === 'add') calls.capture += 1;
433
+ else if (args[0] === 'budget' && (args[1] === 'spend' || args[1] === 'record')) calls.spend += 1;
434
+ }
435
+ return calls;
436
+ }
437
+
438
+ /**
439
+ * Why a subagent start is refused: it was not routed. `noRun` — no typed run is open,
440
+ * so nothing planned the shard; otherwise the run is open and no `dispatch` (or
441
+ * `budget spend`) paid for this start.
442
+ */
443
+ export function routingDenialFor(cli = 'llm-orchestrator', { noRun = false } = {}) {
444
+ const steps = noRun
445
+ ? `open a typed run first (\`${cli} run start --type <TYPE> --shards <n>\`), then run \`${cli} dispatch --task-type <TYPE> --phase <phase> --role <role> --tags <a,b>\` for this shard`
446
+ : `run \`${cli} dispatch --task-type <TYPE> --phase <phase> --role <role> --tags <a,b>\` for this shard`;
447
+ return `Subagent not started: cost-effective routing is enforced. Before a subagent starts, ${steps}. `
448
+ + `The brief names the tier, thinking level and model — the cheapest that clear the risk floor — says whether a strategy card from an earlier run applies `
449
+ + `or whether an advisor consult or an upgrade is useful and in budget, and records the dispatch under the frontier cap. `
450
+ + `Then start the subagent again and pass that model and thinking level in the call. One \`dispatch\` pays for one subagent.`;
451
+ }
452
+
453
+ /** The sentence for every other refusal the gate makes; `why` names which one. */
454
+ export function denialFor(cli = 'llm-orchestrator', why, detail = {}) {
455
+ switch (why) {
456
+ case 'no_skill':
457
+ return `Run not opened: the orchestrate-core skill has not been loaded in this session. Load it first (Claude Code: the Skill tool, \`orchestrate-core\` or \`llm-orchestrator:orchestrate-core\`; other harnesses: read the installed \`orchestrate-core/SKILL.md\` or the bridge \`.agents/skills/orchestrate/SKILL.md\`), then run the same command again. `
458
+ + 'The run command alone leaves out what the skill decides: routing, roles, mandatory tools and gates.';
459
+ case 'inline_shards':
460
+ return `Run not opened: \`--inline\` is for a single shard whose live state a subagent cannot inherit, and this plan has ${detail.shards} shards. `
461
+ + `Drop \`--inline\` and dispatch the shards (\`${cli} dispatch\` before each), or plan \`--shards 1\` if it really is one piece of stateful work.`;
462
+ case 'trivial_edit':
463
+ return `Edit refused: this run was declared trivial and has already grown past a one-line change. Reopen it as a typed run (\`${cli} run start --type <TYPE> --shards <n>\`) so it is planned, routed and verified, then make the edit.`;
464
+ case 'no_run_work':
465
+ return `Refused: this changes files or runs a command with no orchestrate-core run open, after the reminder. Open one first: \`${cli} run start --type <TYPE> --shards <n>\`, `
466
+ + `or \`${cli} run start --trivial "<reason>"\` for a one-line change. Reading and searching stay allowed.`;
467
+ case 'tool_required':
468
+ return toolRequiredFor(cli, detail.rule);
469
+ case 'undispatched':
470
+ return `Edit refused: this run planned ${detail.shards} shards and the main thread is still building them itself after the dispatch reminders. `
471
+ + `Dispatch them (\`${cli} dispatch\` before each subagent), or reopen the run as one stateful shard (\`${cli} run start --type <TYPE> --shards 1 --inline "stateful: <what state>"\`).`;
472
+ case 'close_incomplete': {
473
+ const rules = toolUseRules();
474
+ const lines = (detail.missing ?? []).map((id) => rules.find((rule) => rule.id === id)).filter(Boolean)
475
+ .map((rule) => `- ${rule.display_name} (\`${rule.id}\`): ${rule.use}`);
476
+ if (detail.capture) lines.push(`- Strategy card: a frontier model answered in this run. Distil its answer (When / Steps / Traps / Verify) so the routed model can do this kind of task next time: \`${cli} strategy add --task-type <TYPE> --phase <phase> --tags <a,b> --title "<title>" --file <card.md>\`.`);
477
+ return `Run not closed yet — it is missing:\n${lines.join('\n')}\nDo these, then close the run again. If one cannot be done, say why in the final report; the next \`run close\` goes through and records what was missing.`;
478
+ }
479
+ case 'generic_role':
480
+ return `Subagent not started: a typed run dispatches to the orchestrator's roles, not a generic agent. Use the role \`${cli} dispatch\` named (\`subagent_type: "llm-orchestrator:<role>"\`, for example \`llm-orchestrator:backend-fixer\` or \`llm-orchestrator:explore\`); `
481
+ + 'when no specialist fits, `llm-orchestrator:general`. A role carries its charter, permissions and output contract; a generic agent carries none of them.';
482
+ default:
483
+ return routingDenialFor(cli, { noRun: why === 'no_run' });
484
+ }
485
+ }
486
+
487
+ /** A user question asked in plain text at the end of a turn, instead of the harness's question tool. */
488
+ export function askNativelyFor() {
489
+ return 'Your last message asks the user a question in plain text. Ask it through the harness\'s question tool instead (Claude Code: AskUserQuestion; Codex: request_user_input; OpenCode: question; Kilo: ask_followup_question): '
490
+ + 'one batched question with the options and your recommendation, so the answer comes back as a decision. If no question was meant, finish the work or close the run.';
491
+ }
492
+
493
+ const NATIVE_QUESTION_TOOLS = new Set(['askuserquestion', 'request_user_input', 'question', 'ask_followup_question']);
494
+ // Work calls after the last dispatch reminder before a multi-shard run's own edits are refused.
495
+ const UNDISPATCHED_GRACE = 4;
496
+ // Claude Code's built-in agent types that carry no role.
497
+ const GENERIC_AGENT = /^(general-purpose|claude|statusline-setup)?$/i;
498
+
499
+ // The tools that start a subagent, per harness.
500
+ const DISPATCH_TOOLS = new Set(['agent', 'task', 'spawn_agent', 'spawn_agents_on_csv']);
501
+
502
+ export function routingNudgeFor(cli = 'llm-orchestrator') {
503
+ return `This dispatch was not routed: nothing chose its model or recorded it. Before each dispatch run `
504
+ + `\`${cli} dispatch --task-type <TYPE> --phase <phase> --role <role> --tags <a,b>\`. It answers in one brief: `
505
+ + `the tier, thinking level and model — the cheapest that clear the risk floor; `
506
+ + `whether a strategy card distilled from an earlier run of this kind exists (inject it and stay on the cheap tier), `
507
+ + `whether one advisor consult or an upgrade to a stronger model is useful and in budget; and it records the dispatch under the frontier cap. `
508
+ + `Pass that model and thinking level in the dispatch itself, and distil a strategy card after a frontier-tier answer. This reminder is sent once per run.`;
509
+ }
510
+
404
511
  export function parseRunArgs(args) {
405
512
  const [action, ...rest] = args;
406
513
  if (action === 'close') return { action: 'close' };
@@ -469,6 +576,9 @@ export function normalizePayload(raw) {
469
576
  || Boolean(path && /orchestrate(-core)?\/SKILL\.md$/.test(path))
470
577
  || Boolean(command && /orchestrate(-core)?\/SKILL\.md/.test(command));
471
578
  const readOnly = READ_ONLY_TOOLS.has(toolName.toLowerCase()) || isReadOnlyCommand(command);
579
+ const edited = editedPaths(toolName, input);
580
+ const role = typeof input?.subagent_type === 'string' ? input.subagent_type : typeof input?.agent_type === 'string' ? input.agent_type : null;
581
+ const use = toolUseFacts({ toolName, skill, role, command, path, paths: edited });
472
582
  return {
473
583
  kind: 'tool',
474
584
  session,
@@ -481,7 +591,19 @@ export function normalizePayload(raw) {
481
591
  loadsEntrypoint,
482
592
  readOnly,
483
593
  live: isLiveSource(command),
484
- edits: editedPaths(toolName, input).map((editedPath) => ({ hash: pathHash(editedPath), test: TEST_PATH.test(editedPath) })),
594
+ edits: edited.map((editedPath) => ({ hash: pathHash(editedPath), test: TEST_PATH.test(editedPath) })),
595
+ command,
596
+ dispatch: DISPATCH_TOOLS.has(toolName.toLowerCase()),
597
+ // Claude Code's Agent tool: a dispatch with no role, or a built-in generic type.
598
+ // A frontier-tier subagent: the advisor role, or a frontier model named in the call.
599
+ frontier: DISPATCH_TOOLS.has(toolName.toLowerCase()) && (/(^|:)advisor$/i.test(String(input?.subagent_type ?? input?.agent_type ?? ''))
600
+ || /fable|astra/i.test(String(input?.model ?? ''))),
601
+ genericAgent: toolName.toLowerCase() === 'agent' && (typeof input?.subagent_type !== 'string' || GENERIC_AGENT.test(input.subagent_type.trim())),
602
+ nativeQuestion: NATIVE_QUESTION_TOOLS.has(toolName.toLowerCase()),
603
+ routing: parseRoutingCalls(command),
604
+ use,
605
+ // Memory, reasoning, documentation and symbol lookups serve the flow; they are not work that skips it.
606
+ support: use.satisfies.length > 0 && edited.length === 0 && !DISPATCH_TOOLS.has(toolName.toLowerCase()),
485
607
  };
486
608
  }
487
609
 
@@ -512,6 +634,20 @@ function historyLine(session, fields, now) {
512
634
  role_dispatches: fields.role_dispatches ?? 0,
513
635
  generic_dispatches: fields.generic_dispatches ?? 0,
514
636
  stop_continues: fields.stop_continues ?? 0,
637
+ dispatch_calls: fields.dispatch_calls ?? 0,
638
+ denied_dispatches: fields.denied_dispatches ?? 0,
639
+ plain_questions: fields.plain_questions ?? 0,
640
+ frontier_uses: fields.frontier_uses ?? 0,
641
+ captures: fields.captures ?? 0,
642
+ closed_without: fields.closed_without ?? [],
643
+ unrouted_dispatches: fields.unrouted_dispatches ?? 0,
644
+ route_calls: fields.route_calls ?? 0,
645
+ decide_calls: fields.decide_calls ?? 0,
646
+ spend_calls: fields.spend_calls ?? 0,
647
+ tool_use: fields.tool_use?.used ?? {},
648
+ tool_nudges: (fields.tool_use?.nudged ?? []).filter((id) => !(fields.tool_use?.skipped ?? []).includes(id)),
649
+ tool_followed: fields.tool_use?.followed ?? [],
650
+ tool_skipped: fields.tool_use?.skipped ?? [],
515
651
  closed_by: fields.closed_by,
516
652
  };
517
653
  }
@@ -567,7 +703,10 @@ export function decide(previous, event, now) {
567
703
  }, now));
568
704
  }
569
705
  if (session.run) session.run.stop_continues_prompt = 0;
706
+ session.asked_natively = false;
707
+ session.ask_nudged = false;
570
708
  session.prompt_started_at = now;
709
+ delete session.pre_tool_use;
571
710
  session.nudged = false;
572
711
  session.entrypoint_loaded = false;
573
712
  session.worked_without_run = false;
@@ -605,6 +744,13 @@ export function decide(previous, event, now) {
605
744
  run.stop_continues = (run.stop_continues ?? 0) + 1;
606
745
  output = { kind: 'continue' };
607
746
  }
747
+ // A typed run ended its turn on a plain-text question: once per prompt, ask through the question tool.
748
+ if (!output && run && !run.trivial && !event.isSubagent && !event.noEnforce && event.signal === 'asks'
749
+ && !session.asked_natively && !session.ask_nudged) {
750
+ session.ask_nudged = true;
751
+ run.plain_questions = (run.plain_questions ?? 0) + 1;
752
+ output = { kind: 'ask_native' };
753
+ }
608
754
  return { session, output, history };
609
755
  }
610
756
 
@@ -627,6 +773,51 @@ export function decide(previous, event, now) {
627
773
  if (event.kind !== 'tool') return { session, output, history };
628
774
  // Work resumed: the turn-end allowance is whole again.
629
775
  if (session.run && !event.isSubagent && session.run.stop_continues_prompt) session.run.stop_continues_prompt = 0;
776
+ if (event.nativeQuestion && !event.isSubagent) session.asked_natively = true;
777
+ if (event.loadsEntrypoint) session.entrypoint_seen = true;
778
+
779
+ // Refusals: what a model otherwise skips by habit. Off with LLM_ORCHESTRATOR_NO_ENFORCE.
780
+ const deny = (why, detail = {}) => {
781
+ session.denials = { ...(session.denials ?? {}), [why]: ((session.denials ?? {})[why] ?? 0) + 1 };
782
+ return { session, output: { kind: 'deny', why, ...detail }, history };
783
+ };
784
+ if (!event.isSubagent && !event.noEnforce) {
785
+ if (event.run?.action === 'start' && !event.run.trivial) {
786
+ if (!session.entrypoint_seen) return deny('no_skill');
787
+ if (event.run.inline && (event.run.shards ?? 1) > 1) return deny('inline_shards', { shards: event.run.shards });
788
+ }
789
+ const current = session.run;
790
+ if (current?.trivial && current.overreach_nudged && event.edits.length > 0) return deny('trivial_edit');
791
+ if (!current && session.nudged && !event.run && !event.instruction && !event.orchestratorCall && !event.nonWork
792
+ && !event.loadsEntrypoint && !event.support && !event.dispatch && !event.readOnly
793
+ && (event.edits.length > 0 || typeof event.command === 'string')) return deny('no_run_work');
794
+ if (event.dispatch && current && !current.trivial && event.genericAgent) return deny('generic_role');
795
+ if (current && !current.trivial) {
796
+ const change = event.edits.length > 0 || (typeof event.command === 'string' && !event.readOnly && !event.orchestratorCall);
797
+ // A mandatory tool reminded and still unused: changes wait for it (or for a recorded skip).
798
+ if (change && !event.support) {
799
+ const rule = requiredToolUse(current.tool_use ?? emptyToolUse(), { workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
800
+ if (rule) return deny('tool_required', { rule });
801
+ }
802
+ // A plan of several shards that the main thread keeps building itself, after the reminders.
803
+ const nudges = current.dispatch_nudges ?? (current.dispatch_nudged ? 1 : 0);
804
+ if (event.edits.length > 0 && nudges > 0 && (current.planned_shards ?? 0) >= 2 && current.subagents_started === 0 && !current.inline_reason
805
+ && (current.main_work_calls ?? 0) >= (current.nudged_at_calls ?? 0) + UNDISPATCHED_GRACE) return deny('undispatched', { shards: current.planned_shards });
806
+ // Closing: verification, the memory checkpoint and — after a frontier answer — the strategy card. Sent back once.
807
+ if (event.run?.action === 'close' && !current.close_bounced) {
808
+ const missing = missingAtClose(current.tool_use ?? emptyToolUse(), { taskType: current.task_type, workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
809
+ const capture = (current.frontier_uses ?? 0) > 0 && (current.captures ?? 0) === 0;
810
+ if (missing.length > 0 || capture) {
811
+ current.close_bounced = true;
812
+ current.closed_without = [...missing, ...(capture ? ['strategy.capture'] : [])];
813
+ // Said here; the close that follows does not repeat them as reminders.
814
+ const state = current.tool_use ?? (current.tool_use = emptyToolUse());
815
+ state.nudged = [...new Set([...state.nudged, ...missing])];
816
+ return deny('close_incomplete', { missing, capture });
817
+ }
818
+ }
819
+ }
820
+ }
630
821
 
631
822
  if (event.run?.action === 'start') {
632
823
  if (session.run) history.push(closeRun(session, now, 'succession'));
@@ -653,12 +844,33 @@ export function decide(previous, event, now) {
653
844
  stop_continues_prompt: 0,
654
845
  live_calls: 0,
655
846
  inline_after_nudge: Boolean(event.run.inline && session.run?.dispatch_nudged),
847
+ // Tools used before the run opened count for it; a reopened run keeps what it used and was told.
848
+ tool_use: inheritToolUse({ before: session.pre_tool_use, previous: session.run?.tool_use, session: session.tool_session ?? [] }),
656
849
  };
850
+ delete session.pre_tool_use;
657
851
  // The work already done is accounted for on the run itself now.
658
852
  session.worked_without_run = false;
659
853
  return { session, output, history };
660
854
  }
661
855
  if (event.run?.action === 'close') {
856
+ if (session.run && !session.run.trivial && !event.isSubagent) {
857
+ // The close call is the last chance: every rule due at close is sent together.
858
+ const state = session.run.tool_use ?? (session.run.tool_use = emptyToolUse());
859
+ const due = [];
860
+ for (;;) {
861
+ const rule = dueToolUse(state, { when: 'close', taskType: session.run.task_type, workCalls: session.run.main_work_calls ?? 0, skips: event.skips });
862
+ if (!rule) break;
863
+ due.push(rule);
864
+ }
865
+ if (due.length > 0) output = { additionalContext: due.map((rule) => toolUseNudgeFor(undefined, rule)).join('\n'), kind: 'tool_use', rule: due[0], rules: due };
866
+ }
867
+ if (session.run?.closed_without) {
868
+ // What is still missing when the run actually closes.
869
+ const current = session.run;
870
+ const stillMissing = missingAtClose(current.tool_use ?? emptyToolUse(), { taskType: current.task_type, workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
871
+ const capture = (current.frontier_uses ?? 0) > 0 && (current.captures ?? 0) === 0;
872
+ current.closed_without = [...stillMissing, ...(capture ? ['strategy.capture'] : [])];
873
+ }
662
874
  if (session.run) history.push(closeRun(session, now, 'run_close'));
663
875
  session.run = null;
664
876
  return { session, output, history };
@@ -668,7 +880,60 @@ export function decide(previous, event, now) {
668
880
  session.entrypoint_loaded = true;
669
881
  session.entrypoint_seen = true;
670
882
  }
671
- if (event.isSubagent || event.instruction || event.orchestratorCall || event.nonWork || event.loadsEntrypoint) {
883
+ // A subagent start must be routed: a typed run is open and a `dispatch` paid for it.
884
+ // Enforced (denied) unless LLM_ORCHESTRATOR_NO_ENFORCE is set, which turns it back into a reminder.
885
+ if (event.dispatch && !event.isSubagent && !event.noEnforce) {
886
+ const typed = session.run && !session.run.trivial;
887
+ if (!typed) {
888
+ session.denied_dispatches = (session.denied_dispatches ?? 0) + 1;
889
+ return { session, output: { kind: 'deny', why: 'no_run' }, history };
890
+ }
891
+ const current = session.run;
892
+ const calls = event.routing ?? {};
893
+ if (calls.spend) current.spend_credit = (current.spend_credit ?? 0) + calls.spend;
894
+ if ((current.spend_credit ?? 0) <= 0) {
895
+ current.denied_dispatches = (current.denied_dispatches ?? 0) + 1;
896
+ return { session, output: { kind: 'deny', why: 'unrouted' }, history };
897
+ }
898
+ }
899
+ // Routing steps and dispatches of a typed run: every dispatch should be paid for by a `budget spend`.
900
+ if (session.run && !session.run.trivial && !event.isSubagent) {
901
+ const current = session.run;
902
+ const calls = event.routing ?? {};
903
+ if (calls.route) current.route_calls = (current.route_calls ?? 0) + calls.route;
904
+ if (calls.advisor) current.frontier_uses = (current.frontier_uses ?? 0) + calls.advisor;
905
+ if (calls.capture) current.captures = (current.captures ?? 0) + calls.capture;
906
+ if (event.dispatch && event.frontier) current.frontier_uses = (current.frontier_uses ?? 0) + 1;
907
+ if (calls.decide) current.decide_calls = (current.decide_calls ?? 0) + calls.decide;
908
+ if (calls.spend) {
909
+ current.spend_calls = (current.spend_calls ?? 0) + calls.spend;
910
+ current.spend_credit = (current.spend_credit ?? 0) + calls.spend;
911
+ }
912
+ if (event.dispatch) {
913
+ current.dispatch_calls = (current.dispatch_calls ?? 0) + 1;
914
+ if ((current.spend_credit ?? 0) > 0) current.spend_credit -= 1;
915
+ else {
916
+ current.unrouted_dispatches = (current.unrouted_dispatches ?? 0) + 1;
917
+ if (!current.routing_nudged) {
918
+ current.routing_nudged = true;
919
+ output = { additionalContext: routingNudgeFor(), kind: 'routing' };
920
+ }
921
+ }
922
+ }
923
+ }
924
+ // A subagent's tool calls count for the run it works under: what it used is used.
925
+ if (event.isSubagent && session.run && !session.run.trivial && event.use?.satisfies.length > 0) {
926
+ session.run.tool_use = recordToolUse(session.run.tool_use ?? emptyToolUse(), { satisfies: event.use.satisfies, due: [], codeSearch: false }, session.run.task_type);
927
+ return { session, output, history };
928
+ }
929
+ if (!event.isSubagent && event.use && (event.use.satisfies.length > 0 || event.use.due.length > 0 || event.use.codeSearch)) {
930
+ const holder = session.run ?? session;
931
+ const key = session.run ? 'tool_use' : 'pre_tool_use';
932
+ holder[key] = recordToolUse(holder[key] ?? emptyToolUse(), event.use, session.run?.task_type ?? null);
933
+ const lasting = sessionRules().filter((id) => event.use.satisfies.includes(id));
934
+ if (lasting.length > 0) session.tool_session = [...new Set([...(session.tool_session ?? []), ...lasting])];
935
+ }
936
+ if (event.isSubagent || event.instruction || event.orchestratorCall || event.nonWork || event.loadsEntrypoint || event.support) {
672
937
  return { session, output, history };
673
938
  }
674
939
  if (session.run) {
@@ -697,14 +962,22 @@ export function decide(previous, event, now) {
697
962
  const nudges = current.dispatch_nudges ?? (current.dispatch_nudged ? 1 : 0);
698
963
  // The follow-up is for live evidence; a few small local files are fine read inline.
699
964
  const allowed = evidence && (current.live_calls ?? 0) > 0 ? MAX_DISPATCH_NUDGES : 1;
700
- if ((current.planned_shards ?? 0) >= 2 && current.subagents_started === 0 && !current.inline_reason
965
+ if (!event.dispatch && (current.planned_shards ?? 0) >= 2 && current.subagents_started === 0 && !current.inline_reason
701
966
  && nudges < allowed && current.main_work_calls >= step * (nudges + 1)) {
702
967
  current.dispatch_nudged = true;
968
+ current.nudged_at_calls = current.main_work_calls;
703
969
  current.dispatch_nudges = nudges + 1;
704
970
  output = nudges === 0
705
971
  ? { additionalContext: dispatchNudgeFor(undefined, current.planned_shards, current.task_type), kind: 'dispatch', planned: current.planned_shards, taskType: current.task_type }
706
972
  : { additionalContext: dispatchFollowupFor(undefined, current.planned_shards, current.task_type), kind: 'dispatch_followup', planned: current.planned_shards, taskType: current.task_type };
707
973
  }
974
+ // One reminder per call: a tool this run should have used by now, unless the user skipped it.
975
+ if (output?.kind === 'routing') return { session, output, history };
976
+ if (!output) {
977
+ const state = current.tool_use ?? (current.tool_use = emptyToolUse());
978
+ const rule = dueToolUse(state, { taskType: current.task_type, workCalls: current.main_work_calls, skips: event.skips });
979
+ if (rule) output = { additionalContext: toolUseNudgeFor(undefined, rule), kind: 'tool_use', rule };
980
+ }
708
981
  return { session, output, history };
709
982
  }
710
983
  // Following the entrypoint: discovery reads before the run opens are step 2–3, not a skip.
@@ -866,13 +1139,15 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
866
1139
  if (event.kind === 'other') return null;
867
1140
  // Subagent tool calls change nothing (they work under the parent's run), so they
868
1141
  // take no lock and do no I/O — a busy subagent must not starve the parent's events.
869
- if (event.kind === 'tool' && event.isSubagent) return null;
1142
+ // A subagent's tool call changes nothing — unless it used a tool the run must use, which counts for the run.
1143
+ if (event.kind === 'tool' && event.isSubagent && !(event.use?.satisfies.length > 0)) return null;
870
1144
  // Before any ledger I/O: an opted-out project gets no `.orchestrator-run/` at all.
871
1145
  const engagement = await projectEngagement(project, { env, home });
872
1146
  if (engagement.state === 'opted_out') return null;
873
1147
  // An explicit run command opts a directory in; anything else needs it to be a project.
874
1148
  if (!event.run && !engagement.engaged) return null;
875
1149
  if (event.kind === 'stop') event.noContinue = envFlag(env, 'LLM_ORCHESTRATOR_NO_CONTINUE');
1150
+ if (event.kind === 'tool' || event.kind === 'stop') event.noEnforce = envFlag(env, 'LLM_ORCHESTRATOR_NO_ENFORCE');
876
1151
  const directory = await ensureLedger(engagement.root);
877
1152
  const path = join(directory, 'sessions', sessionFileName(event.session));
878
1153
  const result = await withSessionLock(path, async () => {
@@ -884,6 +1159,10 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
884
1159
  session = emptySession(event.session);
885
1160
  }
886
1161
  const before = JSON.stringify(session);
1162
+ // Skips are read only when a reminder could fire: a typed run is open.
1163
+ if (event.kind === 'tool' && session.run && !session.run.trivial) {
1164
+ event.skips = await skipSet(engagement.root, { env, stateRoot: env.LLM_ORCHESTRATOR_STATE ?? (env.XDG_STATE_HOME ? join(env.XDG_STATE_HOME, 'portable-orchestrator') : join(home, '.local', 'state', 'portable-orchestrator')) });
1165
+ }
887
1166
  const next = decide(session, event, now);
888
1167
  const after = JSON.stringify(next.session);
889
1168
  if (event.kind === 'session_end') {
@@ -901,11 +1180,23 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
901
1180
  });
902
1181
  if (!result.output) return null;
903
1182
  if (result.output.kind === 'continue') return { decision: 'block', reason: continueNudgeFor(cli) };
1183
+ // Claude Code and Codex read the same PreToolUse denial; the OpenCode/Kilo plugin turns it into a thrown error.
1184
+ if (result.output.kind === 'deny') {
1185
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: denialFor(cli, result.output.why, result.output) } };
1186
+ }
1187
+ if (result.output.kind === 'ask_native') return { decision: 'block', reason: askNativelyFor() };
904
1188
  if (result.output.kind === 'resume') {
905
1189
  return { hookSpecificOutput: { hookEventName: String(payload.hook_event_name), additionalContext: resumeNoticeFor(cli, result.output) } };
906
1190
  }
1191
+ if (result.output.kind === 'entrypoint') {
1192
+ // Once per session, with the notice: the tools this project declares for itself.
1193
+ const brief = await projectToolBrief(engagement.root, cli).catch(() => null);
1194
+ return { hookSpecificOutput: { hookEventName: String(payload.hook_event_name), additionalContext: brief ? `${ENTRYPOINT_NOTICE}\n${brief}` : ENTRYPOINT_NOTICE } };
1195
+ }
907
1196
  // decide() speaks in the default CLI spelling; the hook swaps in the runnable path.
908
- const text = result.output.kind === 'dispatch' ? dispatchNudgeFor(cli, result.output.planned, result.output.taskType)
1197
+ const text = result.output.kind === 'tool_use' ? (result.output.rules ?? [result.output.rule]).map((rule) => toolUseNudgeFor(cli, rule)).join('\n')
1198
+ : result.output.kind === 'routing' ? routingNudgeFor(cli)
1199
+ : result.output.kind === 'dispatch' ? dispatchNudgeFor(cli, result.output.planned, result.output.taskType)
909
1200
  : result.output.kind === 'dispatch_followup' ? dispatchFollowupFor(cli, result.output.planned, result.output.taskType)
910
1201
  : result.output.kind === 'overreach' ? (result.output.live ? overreachLiveNudgeFor(cli, result.output.live)
911
1202
  : result.output.calls ? overreachWorkNudgeFor(cli, result.output.calls) : overreachNudgeFor(cli, result.output.files))
@@ -959,6 +1250,21 @@ export function adherenceSummary(lines) {
959
1250
  inline_after_nudge: lines.filter((line) => line.inline_after_nudge).length,
960
1251
  trivial_overreach: lines.filter((line) => line.trivial && line.overreach).length,
961
1252
  forced_continues: lines.reduce((sum, line) => sum + (line.stop_continues ?? 0), 0),
1253
+ dispatch_calls: lines.reduce((sum, line) => sum + (line.dispatch_calls ?? 0), 0),
1254
+ unrouted_dispatches: lines.reduce((sum, line) => sum + (line.unrouted_dispatches ?? 0), 0),
1255
+ denied_dispatches: lines.reduce((sum, line) => sum + (line.denied_dispatches ?? 0), 0),
1256
+ plain_questions: lines.reduce((sum, line) => sum + (line.plain_questions ?? 0), 0),
1257
+ frontier_uses: lines.reduce((sum, line) => sum + (line.frontier_uses ?? 0), 0),
1258
+ strategy_captures: lines.reduce((sum, line) => sum + (line.captures ?? 0), 0),
1259
+ runs_closed_incomplete: lines.filter((line) => (line.closed_without ?? []).length > 0).length,
1260
+ runs_dispatching_without_decide: lines.filter((line) => (line.dispatch_calls ?? 0) > 0 && (line.decide_calls ?? 0) === 0).length,
1261
+ tool_reminders: lines.reduce((sum, line) => sum + (line.tool_nudges?.length ?? 0), 0),
1262
+ tool_reminders_followed: lines.reduce((sum, line) => sum + (line.tool_followed?.length ?? 0), 0),
1263
+ tool_skips_applied: lines.reduce((sum, line) => sum + (line.tool_skipped?.length ?? 0), 0),
1264
+ tool_use: lines.reduce((totals, line) => {
1265
+ for (const [id, count] of Object.entries(line.tool_use ?? {})) totals[id] = (totals[id] ?? 0) + count;
1266
+ return totals;
1267
+ }, {}),
962
1268
  role_dispatches: lines.reduce((sum, line) => sum + (line.role_dispatches ?? 0), 0),
963
1269
  generic_dispatches: lines.reduce((sum, line) => sum + (line.generic_dispatches ?? 0), 0),
964
1270
  runs_without_roles: lines.filter((line) => (line.subagents_started ?? 0) > 0 && line.role_dispatches === 0 && (line.generic_dispatches ?? 0) > 0).length,