llm-orchestrator 1.6.0 → 1.7.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/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,109 @@ 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
+ // Codex reports some tools with their namespace (`collaboration.spawn_agent`); the last segment is the tool.
502
+ function isDispatchTool(toolName) {
503
+ return DISPATCH_TOOLS.has(String(toolName).toLowerCase().split(/[.:/]/).pop());
504
+ }
505
+
506
+ export function routingNudgeFor(cli = 'llm-orchestrator') {
507
+ return `This dispatch was not routed: nothing chose its model or recorded it. Before each dispatch run `
508
+ + `\`${cli} dispatch --task-type <TYPE> --phase <phase> --role <role> --tags <a,b>\`. It answers in one brief: `
509
+ + `the tier, thinking level and model — the cheapest that clear the risk floor; `
510
+ + `whether a strategy card distilled from an earlier run of this kind exists (inject it and stay on the cheap tier), `
511
+ + `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. `
512
+ + `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.`;
513
+ }
514
+
404
515
  export function parseRunArgs(args) {
405
516
  const [action, ...rest] = args;
406
517
  if (action === 'close') return { action: 'close' };
@@ -469,6 +580,9 @@ export function normalizePayload(raw) {
469
580
  || Boolean(path && /orchestrate(-core)?\/SKILL\.md$/.test(path))
470
581
  || Boolean(command && /orchestrate(-core)?\/SKILL\.md/.test(command));
471
582
  const readOnly = READ_ONLY_TOOLS.has(toolName.toLowerCase()) || isReadOnlyCommand(command);
583
+ const edited = editedPaths(toolName, input);
584
+ const role = typeof input?.subagent_type === 'string' ? input.subagent_type : typeof input?.agent_type === 'string' ? input.agent_type : null;
585
+ const use = toolUseFacts({ toolName, skill, role, command, path, paths: edited });
472
586
  return {
473
587
  kind: 'tool',
474
588
  session,
@@ -481,7 +595,19 @@ export function normalizePayload(raw) {
481
595
  loadsEntrypoint,
482
596
  readOnly,
483
597
  live: isLiveSource(command),
484
- edits: editedPaths(toolName, input).map((editedPath) => ({ hash: pathHash(editedPath), test: TEST_PATH.test(editedPath) })),
598
+ edits: edited.map((editedPath) => ({ hash: pathHash(editedPath), test: TEST_PATH.test(editedPath) })),
599
+ command,
600
+ dispatch: isDispatchTool(toolName),
601
+ // Claude Code's Agent tool: a dispatch with no role, or a built-in generic type.
602
+ // A frontier-tier subagent: the advisor role, or a frontier model named in the call.
603
+ frontier: isDispatchTool(toolName) && (/(^|:)advisor$/i.test(String(input?.subagent_type ?? input?.agent_type ?? ''))
604
+ || /fable|astra/i.test(String(input?.model ?? ''))),
605
+ genericAgent: toolName.toLowerCase() === 'agent' && (typeof input?.subagent_type !== 'string' || GENERIC_AGENT.test(input.subagent_type.trim())),
606
+ nativeQuestion: NATIVE_QUESTION_TOOLS.has(toolName.toLowerCase()),
607
+ routing: parseRoutingCalls(command),
608
+ use,
609
+ // Memory, reasoning, documentation and symbol lookups serve the flow; they are not work that skips it.
610
+ support: use.satisfies.length > 0 && edited.length === 0 && !isDispatchTool(toolName),
485
611
  };
486
612
  }
487
613
 
@@ -512,6 +638,20 @@ function historyLine(session, fields, now) {
512
638
  role_dispatches: fields.role_dispatches ?? 0,
513
639
  generic_dispatches: fields.generic_dispatches ?? 0,
514
640
  stop_continues: fields.stop_continues ?? 0,
641
+ dispatch_calls: fields.dispatch_calls ?? 0,
642
+ denied_dispatches: fields.denied_dispatches ?? 0,
643
+ plain_questions: fields.plain_questions ?? 0,
644
+ frontier_uses: fields.frontier_uses ?? 0,
645
+ captures: fields.captures ?? 0,
646
+ closed_without: fields.closed_without ?? [],
647
+ unrouted_dispatches: fields.unrouted_dispatches ?? 0,
648
+ route_calls: fields.route_calls ?? 0,
649
+ decide_calls: fields.decide_calls ?? 0,
650
+ spend_calls: fields.spend_calls ?? 0,
651
+ tool_use: fields.tool_use?.used ?? {},
652
+ tool_nudges: (fields.tool_use?.nudged ?? []).filter((id) => !(fields.tool_use?.skipped ?? []).includes(id)),
653
+ tool_followed: fields.tool_use?.followed ?? [],
654
+ tool_skipped: fields.tool_use?.skipped ?? [],
515
655
  closed_by: fields.closed_by,
516
656
  };
517
657
  }
@@ -567,7 +707,10 @@ export function decide(previous, event, now) {
567
707
  }, now));
568
708
  }
569
709
  if (session.run) session.run.stop_continues_prompt = 0;
710
+ session.asked_natively = false;
711
+ session.ask_nudged = false;
570
712
  session.prompt_started_at = now;
713
+ delete session.pre_tool_use;
571
714
  session.nudged = false;
572
715
  session.entrypoint_loaded = false;
573
716
  session.worked_without_run = false;
@@ -605,6 +748,13 @@ export function decide(previous, event, now) {
605
748
  run.stop_continues = (run.stop_continues ?? 0) + 1;
606
749
  output = { kind: 'continue' };
607
750
  }
751
+ // A typed run ended its turn on a plain-text question: once per prompt, ask through the question tool.
752
+ if (!output && run && !run.trivial && !event.isSubagent && !event.noEnforce && event.signal === 'asks'
753
+ && !session.asked_natively && !session.ask_nudged) {
754
+ session.ask_nudged = true;
755
+ run.plain_questions = (run.plain_questions ?? 0) + 1;
756
+ output = { kind: 'ask_native' };
757
+ }
608
758
  return { session, output, history };
609
759
  }
610
760
 
@@ -627,6 +777,51 @@ export function decide(previous, event, now) {
627
777
  if (event.kind !== 'tool') return { session, output, history };
628
778
  // Work resumed: the turn-end allowance is whole again.
629
779
  if (session.run && !event.isSubagent && session.run.stop_continues_prompt) session.run.stop_continues_prompt = 0;
780
+ if (event.nativeQuestion && !event.isSubagent) session.asked_natively = true;
781
+ if (event.loadsEntrypoint) session.entrypoint_seen = true;
782
+
783
+ // Refusals: what a model otherwise skips by habit. Off with LLM_ORCHESTRATOR_NO_ENFORCE.
784
+ const deny = (why, detail = {}) => {
785
+ session.denials = { ...(session.denials ?? {}), [why]: ((session.denials ?? {})[why] ?? 0) + 1 };
786
+ return { session, output: { kind: 'deny', why, ...detail }, history };
787
+ };
788
+ if (!event.isSubagent && !event.noEnforce) {
789
+ if (event.run?.action === 'start' && !event.run.trivial) {
790
+ if (!session.entrypoint_seen) return deny('no_skill');
791
+ if (event.run.inline && (event.run.shards ?? 1) > 1) return deny('inline_shards', { shards: event.run.shards });
792
+ }
793
+ const current = session.run;
794
+ if (current?.trivial && current.overreach_nudged && event.edits.length > 0) return deny('trivial_edit');
795
+ if (!current && session.nudged && !event.run && !event.instruction && !event.orchestratorCall && !event.nonWork
796
+ && !event.loadsEntrypoint && !event.support && !event.dispatch && !event.readOnly
797
+ && (event.edits.length > 0 || typeof event.command === 'string')) return deny('no_run_work');
798
+ if (event.dispatch && current && !current.trivial && event.genericAgent) return deny('generic_role');
799
+ if (current && !current.trivial) {
800
+ const change = event.edits.length > 0 || (typeof event.command === 'string' && !event.readOnly && !event.orchestratorCall);
801
+ // A mandatory tool reminded and still unused: changes wait for it (or for a recorded skip).
802
+ if (change && !event.support) {
803
+ const rule = requiredToolUse(current.tool_use ?? emptyToolUse(), { workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
804
+ if (rule) return deny('tool_required', { rule });
805
+ }
806
+ // A plan of several shards that the main thread keeps building itself, after the reminders.
807
+ const nudges = current.dispatch_nudges ?? (current.dispatch_nudged ? 1 : 0);
808
+ if (event.edits.length > 0 && nudges > 0 && (current.planned_shards ?? 0) >= 2 && current.subagents_started === 0 && !current.inline_reason
809
+ && (current.main_work_calls ?? 0) >= (current.nudged_at_calls ?? 0) + UNDISPATCHED_GRACE) return deny('undispatched', { shards: current.planned_shards });
810
+ // Closing: verification, the memory checkpoint and — after a frontier answer — the strategy card. Sent back once.
811
+ if (event.run?.action === 'close' && !current.close_bounced) {
812
+ const missing = missingAtClose(current.tool_use ?? emptyToolUse(), { taskType: current.task_type, workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
813
+ const capture = (current.frontier_uses ?? 0) > 0 && (current.captures ?? 0) === 0;
814
+ if (missing.length > 0 || capture) {
815
+ current.close_bounced = true;
816
+ current.closed_without = [...missing, ...(capture ? ['strategy.capture'] : [])];
817
+ // Said here; the close that follows does not repeat them as reminders.
818
+ const state = current.tool_use ?? (current.tool_use = emptyToolUse());
819
+ state.nudged = [...new Set([...state.nudged, ...missing])];
820
+ return deny('close_incomplete', { missing, capture });
821
+ }
822
+ }
823
+ }
824
+ }
630
825
 
631
826
  if (event.run?.action === 'start') {
632
827
  if (session.run) history.push(closeRun(session, now, 'succession'));
@@ -653,12 +848,33 @@ export function decide(previous, event, now) {
653
848
  stop_continues_prompt: 0,
654
849
  live_calls: 0,
655
850
  inline_after_nudge: Boolean(event.run.inline && session.run?.dispatch_nudged),
851
+ // Tools used before the run opened count for it; a reopened run keeps what it used and was told.
852
+ tool_use: inheritToolUse({ before: session.pre_tool_use, previous: session.run?.tool_use, session: session.tool_session ?? [] }),
656
853
  };
854
+ delete session.pre_tool_use;
657
855
  // The work already done is accounted for on the run itself now.
658
856
  session.worked_without_run = false;
659
857
  return { session, output, history };
660
858
  }
661
859
  if (event.run?.action === 'close') {
860
+ if (session.run && !session.run.trivial && !event.isSubagent) {
861
+ // The close call is the last chance: every rule due at close is sent together.
862
+ const state = session.run.tool_use ?? (session.run.tool_use = emptyToolUse());
863
+ const due = [];
864
+ for (;;) {
865
+ const rule = dueToolUse(state, { when: 'close', taskType: session.run.task_type, workCalls: session.run.main_work_calls ?? 0, skips: event.skips });
866
+ if (!rule) break;
867
+ due.push(rule);
868
+ }
869
+ if (due.length > 0) output = { additionalContext: due.map((rule) => toolUseNudgeFor(undefined, rule)).join('\n'), kind: 'tool_use', rule: due[0], rules: due };
870
+ }
871
+ if (session.run?.closed_without) {
872
+ // What is still missing when the run actually closes.
873
+ const current = session.run;
874
+ const stillMissing = missingAtClose(current.tool_use ?? emptyToolUse(), { taskType: current.task_type, workCalls: current.main_work_calls ?? 0, skips: event.skips ?? new Set() });
875
+ const capture = (current.frontier_uses ?? 0) > 0 && (current.captures ?? 0) === 0;
876
+ current.closed_without = [...stillMissing, ...(capture ? ['strategy.capture'] : [])];
877
+ }
662
878
  if (session.run) history.push(closeRun(session, now, 'run_close'));
663
879
  session.run = null;
664
880
  return { session, output, history };
@@ -668,7 +884,60 @@ export function decide(previous, event, now) {
668
884
  session.entrypoint_loaded = true;
669
885
  session.entrypoint_seen = true;
670
886
  }
671
- if (event.isSubagent || event.instruction || event.orchestratorCall || event.nonWork || event.loadsEntrypoint) {
887
+ // A subagent start must be routed: a typed run is open and a `dispatch` paid for it.
888
+ // Enforced (denied) unless LLM_ORCHESTRATOR_NO_ENFORCE is set, which turns it back into a reminder.
889
+ if (event.dispatch && !event.isSubagent && !event.noEnforce) {
890
+ const typed = session.run && !session.run.trivial;
891
+ if (!typed) {
892
+ session.denied_dispatches = (session.denied_dispatches ?? 0) + 1;
893
+ return { session, output: { kind: 'deny', why: 'no_run' }, history };
894
+ }
895
+ const current = session.run;
896
+ const calls = event.routing ?? {};
897
+ if (calls.spend) current.spend_credit = (current.spend_credit ?? 0) + calls.spend;
898
+ if ((current.spend_credit ?? 0) <= 0) {
899
+ current.denied_dispatches = (current.denied_dispatches ?? 0) + 1;
900
+ return { session, output: { kind: 'deny', why: 'unrouted' }, history };
901
+ }
902
+ }
903
+ // Routing steps and dispatches of a typed run: every dispatch should be paid for by a `budget spend`.
904
+ if (session.run && !session.run.trivial && !event.isSubagent) {
905
+ const current = session.run;
906
+ const calls = event.routing ?? {};
907
+ if (calls.route) current.route_calls = (current.route_calls ?? 0) + calls.route;
908
+ if (calls.advisor) current.frontier_uses = (current.frontier_uses ?? 0) + calls.advisor;
909
+ if (calls.capture) current.captures = (current.captures ?? 0) + calls.capture;
910
+ if (event.dispatch && event.frontier) current.frontier_uses = (current.frontier_uses ?? 0) + 1;
911
+ if (calls.decide) current.decide_calls = (current.decide_calls ?? 0) + calls.decide;
912
+ if (calls.spend) {
913
+ current.spend_calls = (current.spend_calls ?? 0) + calls.spend;
914
+ current.spend_credit = (current.spend_credit ?? 0) + calls.spend;
915
+ }
916
+ if (event.dispatch) {
917
+ current.dispatch_calls = (current.dispatch_calls ?? 0) + 1;
918
+ if ((current.spend_credit ?? 0) > 0) current.spend_credit -= 1;
919
+ else {
920
+ current.unrouted_dispatches = (current.unrouted_dispatches ?? 0) + 1;
921
+ if (!current.routing_nudged) {
922
+ current.routing_nudged = true;
923
+ output = { additionalContext: routingNudgeFor(), kind: 'routing' };
924
+ }
925
+ }
926
+ }
927
+ }
928
+ // A subagent's tool calls count for the run it works under: what it used is used.
929
+ if (event.isSubagent && session.run && !session.run.trivial && event.use?.satisfies.length > 0) {
930
+ session.run.tool_use = recordToolUse(session.run.tool_use ?? emptyToolUse(), { satisfies: event.use.satisfies, due: [], codeSearch: false }, session.run.task_type);
931
+ return { session, output, history };
932
+ }
933
+ if (!event.isSubagent && event.use && (event.use.satisfies.length > 0 || event.use.due.length > 0 || event.use.codeSearch)) {
934
+ const holder = session.run ?? session;
935
+ const key = session.run ? 'tool_use' : 'pre_tool_use';
936
+ holder[key] = recordToolUse(holder[key] ?? emptyToolUse(), event.use, session.run?.task_type ?? null);
937
+ const lasting = sessionRules().filter((id) => event.use.satisfies.includes(id));
938
+ if (lasting.length > 0) session.tool_session = [...new Set([...(session.tool_session ?? []), ...lasting])];
939
+ }
940
+ if (event.isSubagent || event.instruction || event.orchestratorCall || event.nonWork || event.loadsEntrypoint || event.support) {
672
941
  return { session, output, history };
673
942
  }
674
943
  if (session.run) {
@@ -697,14 +966,22 @@ export function decide(previous, event, now) {
697
966
  const nudges = current.dispatch_nudges ?? (current.dispatch_nudged ? 1 : 0);
698
967
  // The follow-up is for live evidence; a few small local files are fine read inline.
699
968
  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
969
+ if (!event.dispatch && (current.planned_shards ?? 0) >= 2 && current.subagents_started === 0 && !current.inline_reason
701
970
  && nudges < allowed && current.main_work_calls >= step * (nudges + 1)) {
702
971
  current.dispatch_nudged = true;
972
+ current.nudged_at_calls = current.main_work_calls;
703
973
  current.dispatch_nudges = nudges + 1;
704
974
  output = nudges === 0
705
975
  ? { additionalContext: dispatchNudgeFor(undefined, current.planned_shards, current.task_type), kind: 'dispatch', planned: current.planned_shards, taskType: current.task_type }
706
976
  : { additionalContext: dispatchFollowupFor(undefined, current.planned_shards, current.task_type), kind: 'dispatch_followup', planned: current.planned_shards, taskType: current.task_type };
707
977
  }
978
+ // One reminder per call: a tool this run should have used by now, unless the user skipped it.
979
+ if (output?.kind === 'routing') return { session, output, history };
980
+ if (!output) {
981
+ const state = current.tool_use ?? (current.tool_use = emptyToolUse());
982
+ const rule = dueToolUse(state, { taskType: current.task_type, workCalls: current.main_work_calls, skips: event.skips });
983
+ if (rule) output = { additionalContext: toolUseNudgeFor(undefined, rule), kind: 'tool_use', rule };
984
+ }
708
985
  return { session, output, history };
709
986
  }
710
987
  // Following the entrypoint: discovery reads before the run opens are step 2–3, not a skip.
@@ -866,13 +1143,15 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
866
1143
  if (event.kind === 'other') return null;
867
1144
  // Subagent tool calls change nothing (they work under the parent's run), so they
868
1145
  // 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;
1146
+ // A subagent's tool call changes nothing — unless it used a tool the run must use, which counts for the run.
1147
+ if (event.kind === 'tool' && event.isSubagent && !(event.use?.satisfies.length > 0)) return null;
870
1148
  // Before any ledger I/O: an opted-out project gets no `.orchestrator-run/` at all.
871
1149
  const engagement = await projectEngagement(project, { env, home });
872
1150
  if (engagement.state === 'opted_out') return null;
873
1151
  // An explicit run command opts a directory in; anything else needs it to be a project.
874
1152
  if (!event.run && !engagement.engaged) return null;
875
1153
  if (event.kind === 'stop') event.noContinue = envFlag(env, 'LLM_ORCHESTRATOR_NO_CONTINUE');
1154
+ if (event.kind === 'tool' || event.kind === 'stop') event.noEnforce = envFlag(env, 'LLM_ORCHESTRATOR_NO_ENFORCE');
876
1155
  const directory = await ensureLedger(engagement.root);
877
1156
  const path = join(directory, 'sessions', sessionFileName(event.session));
878
1157
  const result = await withSessionLock(path, async () => {
@@ -884,6 +1163,10 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
884
1163
  session = emptySession(event.session);
885
1164
  }
886
1165
  const before = JSON.stringify(session);
1166
+ // Skips are read only when a reminder could fire: a typed run is open.
1167
+ if (event.kind === 'tool' && session.run && !session.run.trivial) {
1168
+ 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')) });
1169
+ }
887
1170
  const next = decide(session, event, now);
888
1171
  const after = JSON.stringify(next.session);
889
1172
  if (event.kind === 'session_end') {
@@ -901,11 +1184,23 @@ export async function handleHook({ payload, project, now = Date.now(), cli = 'll
901
1184
  });
902
1185
  if (!result.output) return null;
903
1186
  if (result.output.kind === 'continue') return { decision: 'block', reason: continueNudgeFor(cli) };
1187
+ // Claude Code and Codex read the same PreToolUse denial; the OpenCode/Kilo plugin turns it into a thrown error.
1188
+ if (result.output.kind === 'deny') {
1189
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: denialFor(cli, result.output.why, result.output) } };
1190
+ }
1191
+ if (result.output.kind === 'ask_native') return { decision: 'block', reason: askNativelyFor() };
904
1192
  if (result.output.kind === 'resume') {
905
1193
  return { hookSpecificOutput: { hookEventName: String(payload.hook_event_name), additionalContext: resumeNoticeFor(cli, result.output) } };
906
1194
  }
1195
+ if (result.output.kind === 'entrypoint') {
1196
+ // Once per session, with the notice: the tools this project declares for itself.
1197
+ const brief = await projectToolBrief(engagement.root, cli).catch(() => null);
1198
+ return { hookSpecificOutput: { hookEventName: String(payload.hook_event_name), additionalContext: brief ? `${ENTRYPOINT_NOTICE}\n${brief}` : ENTRYPOINT_NOTICE } };
1199
+ }
907
1200
  // 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)
1201
+ const text = result.output.kind === 'tool_use' ? (result.output.rules ?? [result.output.rule]).map((rule) => toolUseNudgeFor(cli, rule)).join('\n')
1202
+ : result.output.kind === 'routing' ? routingNudgeFor(cli)
1203
+ : result.output.kind === 'dispatch' ? dispatchNudgeFor(cli, result.output.planned, result.output.taskType)
909
1204
  : result.output.kind === 'dispatch_followup' ? dispatchFollowupFor(cli, result.output.planned, result.output.taskType)
910
1205
  : result.output.kind === 'overreach' ? (result.output.live ? overreachLiveNudgeFor(cli, result.output.live)
911
1206
  : result.output.calls ? overreachWorkNudgeFor(cli, result.output.calls) : overreachNudgeFor(cli, result.output.files))
@@ -959,6 +1254,21 @@ export function adherenceSummary(lines) {
959
1254
  inline_after_nudge: lines.filter((line) => line.inline_after_nudge).length,
960
1255
  trivial_overreach: lines.filter((line) => line.trivial && line.overreach).length,
961
1256
  forced_continues: lines.reduce((sum, line) => sum + (line.stop_continues ?? 0), 0),
1257
+ dispatch_calls: lines.reduce((sum, line) => sum + (line.dispatch_calls ?? 0), 0),
1258
+ unrouted_dispatches: lines.reduce((sum, line) => sum + (line.unrouted_dispatches ?? 0), 0),
1259
+ denied_dispatches: lines.reduce((sum, line) => sum + (line.denied_dispatches ?? 0), 0),
1260
+ plain_questions: lines.reduce((sum, line) => sum + (line.plain_questions ?? 0), 0),
1261
+ frontier_uses: lines.reduce((sum, line) => sum + (line.frontier_uses ?? 0), 0),
1262
+ strategy_captures: lines.reduce((sum, line) => sum + (line.captures ?? 0), 0),
1263
+ runs_closed_incomplete: lines.filter((line) => (line.closed_without ?? []).length > 0).length,
1264
+ runs_dispatching_without_decide: lines.filter((line) => (line.dispatch_calls ?? 0) > 0 && (line.decide_calls ?? 0) === 0).length,
1265
+ tool_reminders: lines.reduce((sum, line) => sum + (line.tool_nudges?.length ?? 0), 0),
1266
+ tool_reminders_followed: lines.reduce((sum, line) => sum + (line.tool_followed?.length ?? 0), 0),
1267
+ tool_skips_applied: lines.reduce((sum, line) => sum + (line.tool_skipped?.length ?? 0), 0),
1268
+ tool_use: lines.reduce((totals, line) => {
1269
+ for (const [id, count] of Object.entries(line.tool_use ?? {})) totals[id] = (totals[id] ?? 0) + count;
1270
+ return totals;
1271
+ }, {}),
962
1272
  role_dispatches: lines.reduce((sum, line) => sum + (line.role_dispatches ?? 0), 0),
963
1273
  generic_dispatches: lines.reduce((sum, line) => sum + (line.generic_dispatches ?? 0), 0),
964
1274
  runs_without_roles: lines.filter((line) => (line.subagents_started ?? 0) > 0 && line.role_dispatches === 0 && (line.generic_dispatches ?? 0) > 0).length,