Skip to content

feat: soft-enforcement delegation + simplified team mode#41

Merged
barkain merged 10 commits into
mainfrom
feature/soft-enforcement
Apr 8, 2026
Merged

feat: soft-enforcement delegation + simplified team mode#41
barkain merged 10 commits into
mainfrom
feature/soft-enforcement

Conversation

@barkain

@barkain barkain commented Apr 7, 2026

Copy link
Copy Markdown
Owner

Summary

  • Soft enforcement replaces hard blocking: require_delegation.py emits per-turn escalating stderr nudges (silent → delegate?nudge: ...WARNING: ... → strong reminder) instead of exit-2 blocks. Tracks only the 8 stable work primitives (Bash/Edit/Write/Read/Glob/Grep/MultiEdit/NotebookEdit) — new Claude Code tools never trigger nudges. No more allowlist to maintain. commands/bypass.md deleted.
  • Simplified team-mode selection: deletes the team_mode_score scoring table. One rule — TeamCreate in tools → team mode, else subagent.
  • Team-mode spawn fix: teammate Agent(team_name=...) calls must NOT use run_in_background: true (background tasks exit on completion and are not persistent swarm members, leaving the tmux session empty).
  • Lean SessionStart (from prior commits on branch): 3 hooks consolidated into inject_all.py, stub + on-demand full orchestrator, ~6.6K tokens off session start.
  • validate_task_graph_compliance / validate_task_graph_depth downgraded to advisory-only. python_posttooluse_hook.py (Ruff/Pyright) is now the only hard-blocking hook.
  • Docs updated: README, CLAUDE.md, docs/hook-debugging.md, docs/ARCHITECTURE_QUICK_REFERENCE.md.

Test plan

  • Fresh session: calculator app end-to-end with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 spawns real persistent teammates (verified in tmux swarm session), all phases PASS
  • Plan rendered correct team-mode dependency graph with parallel waves
  • Integrator caught API mismatch mid-workflow and self-corrected
  • Reviewer: verify nudge escalation by making 5+ direct tool calls in one turn
  • Reviewer: verify counter zeros on /workflow-orchestrator:delegate

🤖 Generated with Claude Code

barkain and others added 5 commits April 6, 2026 16:55
Reduces session startup overhead from ~1.1s (3x Python/uv startup) to
~0.4s (1x) by combining inject_workflow_orchestrator, inject-output-style,
and inject_token_efficiency into a single inject_all.py that reads stdin
once and merges all additionalContext into one JSON response.
Reduce per-session token overhead by trimming injected prompt files
and removing a duplicate output-style injection.

- output-styles/technical-adaptive.md: 19.1K -> 1.7K (91%). Drop all
  HTML/visual mode, mermaid integration, file tree CSS, and async
  generation patterns. Keep only terminal response rules.
- system-prompts/orchestrator_stub.md: 3.3K -> 1.2K (65%). Collapse
  redundant routing tables and Stage 1 details into a single rule.
  Stage 1 / agent return format / prohibited tools live in the
  on-demand workflow_orchestrator.md instead.
- system-prompts/token_efficient_cli.md: 7.1K -> 1.9K (73%). Drop
  per-tool REQUIRED/PROHIBITED tables that compact_run.py already
  rewrites at runtime. Keep the principle plus Read/Grep guidance
  the hooks cannot fix.
- inject_all.py: stop injecting technical-adaptive.md. Claude Code
  loads it natively from plugin.json's outputStyles field (verified
  via /config showing workflow-orchestrator:technical-adaptive
  active), so the hook injection was a duplicate.
- tests: drop obsolete test_inject_token_efficiency.py (the
  standalone script no longer exists; consolidated into inject_all.py
  in the parent branch). Update integration assertion to match the
  trimmed token_efficient_cli.md content.

Net session-start savings: ~6,600 tokens.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace hard-blocking delegation enforcement with per-turn escalating
stderr nudges (silent -> hint -> warning -> strong reminder). Track
only the 8 stable work primitives (Bash/Edit/Write/Read/Glob/Grep/
MultiEdit/NotebookEdit); new Claude Code tools never trigger nudges.
Counter resets per turn and zeros when /workflow-orchestrator:delegate
runs. Subagents immune. Removes the allowlist and commands/bypass.md.

Simplify execution mode selection to one rule: TeamCreate available
-> team mode, else subagent. Deletes team_mode_score scoring table.
Fix team-mode spawns by forbidding run_in_background on teammate
Agent calls (background tasks exit on completion and are not
persistent swarm members).

Downgrade validate_task_graph_compliance and validate_task_graph_depth
to advisory-only. Update README, CLAUDE.md, docs/hook-debugging.md,
docs/ARCHITECTURE_QUICK_REFERENCE.md to match.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

Review Summary by Qodo

Soft enforcement delegation nudges, simplified team mode, and consolidated SessionStart hooks

✨ Enhancement 🧪 Tests 📝 Documentation

Grey Divider

Walkthroughs

Description
• **Soft enforcement delegation**: Replaced hard-blocking tool usage restrictions with per-turn
  escalating stderr nudges (6 levels: silent → hint → warning → strong reminder). Tracks only 8 stable
  work primitives (Bash, Edit, Write, Read, Glob, Grep, MultiEdit, NotebookEdit); new
  Claude Code tools never trigger nudges. Removed 100+ lines of allowlist/pattern matching logic.
• **Simplified team-mode selection**: Replaced complex team_mode_score scoring table with single
  rule: TeamCreate tool available → team mode, else subagent mode. Removed 4-step routing checklist.
• **Team-mode spawn fix**: Added critical note that teammate Agent(team_name=...) calls must NOT
  use run_in_background: true (background tasks exit on completion, not persistent swarm members).
• **Consolidated SessionStart hooks**: Merged 3 separate injection scripts into single
  inject_all.py (~0.3s faster startup). Injects stub orchestrator on startup (~1.1KB), full
  orchestrator on-demand (~7.5KB), saving ~6.6K tokens at session start.
• **Downgraded validation hooks to advisory-only**: validate_task_graph_compliance and
  validate_task_graph_depth now emit one-liner hints instead of hard-blocking (exit 1). Only
  python_posttooluse_hook.py (Ruff/Pyright) remains hard-blocking.
• **Statusline performance optimization**: Added stdin-first fast path for context window and
  version caching (920ms → 0ms per render, ~1s faster context rendering).
• **Counter reset on delegation**: Per-turn nudge counter resets when
  /workflow-orchestrator:delegate runs, tracked via delegation_violations.json.
• **Comprehensive test coverage**: New 223-line test suite for soft enforcement nudges, escalation
  ladder validation, and integration tests updated for consolidated hooks.
• **Documentation updates**: README, CLAUDE.md, hook-debugging guide, architecture reference, and
  output style guide all updated to reflect soft enforcement mechanics, simplified team selection, and
  lean startup benefits.
• **Deleted files**: Removed commands/bypass.md, separate SessionStart injection scripts, and
  obsolete token efficiency tests.
Diagram
flowchart LR
  A["Hard-blocking enforcement<br/>+ allowlist logic"] -->|"Replace with soft nudges"| B["Per-turn escalating<br/>stderr messages"]
  C["Complex team_mode_score<br/>scoring table"] -->|"Simplify to one rule"| D["TeamCreate available?<br/>→ team mode"]
  E["3 separate SessionStart<br/>injection hooks"] -->|"Consolidate"| F["Single inject_all.py<br/>~6.6K tokens saved"]
  G["Hard-blocking validation<br/>hooks"] -->|"Downgrade to advisory"| H["One-liner hints<br/>on stderr"]
  I["Statusline subprocess<br/>calls"] -->|"Optimize with stdin"| J["Cached version lookup<br/>920ms → 0ms"]
  B --> K["✓ Tests + Docs<br/>updated"]
  D --> K
  F --> K
  H --> K
  J --> K
Loading

Grey Divider

File Changes

1. hooks/PreToolUse/require_delegation.py ✨ Enhancement +91/-221

Soft enforcement delegation nudges replace hard blocks

• Replaced hard-blocking enforcement with soft escalating nudges: never blocks (always returns 0),
 tracks per-turn direct work-tool calls, emits stderr messages that grow in severity
• Reduced violation set to 8 stable work primitives (Bash, Edit, Write, Read, Glob,
 Grep, MultiEdit, NotebookEdit) — new Claude Code tools never trigger nudges
• Simplified logic: removed 100+ lines of allowlist/pattern matching, delegation flags, and debug
 infrastructure
• Counter persists across tool calls within a turn, resets on new user prompt (via UserPromptSubmit
 hook)

hooks/PreToolUse/require_delegation.py


2. hooks/UserPromptSubmit/clear-delegation-sessions.py ✨ Enhancement +65/-160

Per-turn state reset and counter initialization

• Renamed from clear-delegation-sessions.sh to Python for cross-platform compatibility
• Refactored to reset per-turn nudge counter (delegation_violations.json) instead of clearing
 delegation sessions
• Consolidated cleanup logic: records turn-start timestamp, resets violations, clears
 team/delegation state files, rotates logs
• Removed debug logging infrastructure and emergency bypass flags

hooks/UserPromptSubmit/clear-delegation-sessions.py


3. tests/test_require_delegation.py 🧪 Tests +223/-0

Test suite for soft enforcement nudge system

• New comprehensive test suite for soft enforcement nudges (223 lines)
• Tests escalation ladder (6 levels from silent to strong warning), counter persistence, subagent
 immunity, and delegation_active flag suppression
• Validates that only work-tools trigger nudges while non-work tools remain silent
• Verifies token cost scales with violation count (message length grows with severity)

tests/test_require_delegation.py


View more (24)
4. hooks/PreToolUse/validate_task_graph_compliance.py ✨ Enhancement +33/-111

Task graph compliance validation downgraded to hints

• Downgraded from hard-blocking (exit 1) to advisory-only hints (always returns 0)
• Simplified error messages to one-liners on stderr instead of multi-line formatted blocks
• Removed detailed error context, examples, and action instructions
• Kept phase ID validation logic but now non-blocking

hooks/PreToolUse/validate_task_graph_compliance.py


5. scripts/statusline.py ✨ Enhancement +59/-10

Statusline performance: stdin-first, cached fallbacks

• Added fast path for context usage: reads context_window from stdin JSON instead of scanning
 JSONL files (~1s faster)
• Added version caching: reads version from stdin JSON, falls back to cached subprocess result
 with 1-hour TTL (920ms → 0ms per render)
• Refactored get_claude_version() to get_claude_version_cached() with temp file cache
• Optimized for high-frequency statusline renders by preferring stdin data over subprocess calls

scripts/statusline.py


6. hooks/SessionStart/inject_all.py ✨ Enhancement +142/-0

Consolidated SessionStart hooks into single script

• New consolidated SessionStart hook combining 3 separate Python scripts into one (saves ~0.3s
 startup per hook)
• Injects orchestrator routing stub (orchestrator_stub.md) and optional token-efficiency guide
 (token_efficient_cli.md)
• Reads stdin once, outputs merged additionalContext in single JSON response
• Includes debug logging and safe file-read helpers with fallback search paths

hooks/SessionStart/inject_all.py


7. hooks/PostToolUse/validate_task_graph_depth.py ✨ Enhancement +16/-69

Task graph depth validation downgraded to hints

• Downgraded from hard-blocking (exit 1) to advisory-only hints (always returns 0)
• Simplified error output to single-line hint instead of multi-line formatted block with examples
• Removed detailed validation messages, WHY explanations, and ACTION REQUIRED sections
• Kept depth-3 validation logic but now non-blocking

hooks/PostToolUse/validate_task_graph_depth.py


8. hooks/PostToolUse/remind_skill_continuation.py ✨ Enhancement +43/-2

Reset nudge counter on delegation invocation

• Added _zero_violations_counter() function to reset per-turn nudge counter when
 /workflow-orchestrator:delegate runs
• Added _is_delegate_invocation() helper to detect delegate command across different
 Skill/SlashCommand field variations
• Integrated counter reset into main PostToolUse flow: when delegate runs, violations counter resets
 to 0
• Increments delegations counter to track successful delegation invocations

hooks/PostToolUse/remind_skill_continuation.py


9. tests/test_integration.py 🧪 Tests +12/-9

Integration tests updated for consolidated SessionStart hook

• Updated test class name from TestInjectTokenEfficiencyIntegration to TestInjectAllIntegration
 (reflects consolidated hook)
• Modified test expectations: CLAUDE_TOKEN_EFFICIENCY=0 now omits token content from merged
 context instead of producing empty stdout
• Updated assertion to check for compact_run.py instead of git status -sb (reflects actual
 token-efficiency content)
• Clarified test docstrings to reflect consolidated hook behavior

tests/test_integration.py


10. docs/hook-debugging.md 📝 Documentation +246/-262

Hook debugging guide updated for soft enforcement

• Rewrote SessionStart debugging section: now documents inject_all.py consolidated hook instead of
 separate shell scripts
• Updated PreToolUse debugging to explain soft enforcement nudges, escalation ladder, and work-tool
 reference
• Simplified PostToolUse debugging: removed detailed validation stages, focused on Ruff/Pyright
 rules and skip options
• Consolidated SubagentStop and Stop hook sections with clearer problem/diagnosis/solution format
• Added end-to-end integration test walkthrough with soft enforcement testing steps

docs/hook-debugging.md


11. output-styles/technical-adaptive.md 📝 Documentation +26/-479

Output style guide simplified and streamlined

• Drastically simplified from 500+ lines to ~40 lines (removed HTML generation templates, Mermaid
 rules, CSS layout guidelines)
• Removed agent-delegated HTML generation pattern and async implementation details
• Kept core principles: ultra-concise default mode, detailed mode on /ask, expert-level brevity,
 no fluff
• Removed table usage guidelines, file tree visualization rules, and performance metrics sections

output-styles/technical-adaptive.md


12. system-prompts/orchestrator_stub.md 📝 Documentation +11/-58

Orchestrator stub simplified to single-rule routing

• Simplified from 68 lines to 21 lines (removed detailed routing checklist and execution stage
 instructions)
• Replaced 4-step routing check with single rule: TeamCreate available → team mode, else subagent
 mode
• Removed team_mode_score scoring table and complexity factors
• Kept core: delegation requirement, team mode detection, pure Q&A exception

system-prompts/orchestrator_stub.md


13. commands/delegate.md 📝 Documentation +10/-31
 Delegate command simplified: one-rule execution mode, team spawn fix

commands/delegate.md


14. hooks/plugin-hooks.json ⚙️ Configuration changes +1/-11

Plugin hooks consolidated for faster startup

• Consolidated SessionStart hooks: removed separate inject_workflow_orchestrator.py,
 inject-output-style.py, and inject_token_efficiency.py commands
• Now single inject_all.py command in SessionStart hooks array
• Reduced from 3 hook commands to 1 (saves ~0.9s startup overhead)

hooks/plugin-hooks.json


15. CHANGELOG.md 📝 Documentation +8/-0

Changelog entry for 1.17.0 release

• Added [1.17.0] entry documenting SessionStart consolidation, statusline stdin optimization, and
 version caching
• Noted performance improvements: ~0.7s faster startup (consolidated hooks), 920ms → 0ms version
 lookup, ~1s faster context rendering

CHANGELOG.md


16. .claude-plugin/plugin.json ⚙️ Configuration changes +1/-1

Version bump to 1.17.0

• Bumped version from 1.16.0 to 1.17.0

.claude-plugin/plugin.json


17. README.md ✨ Enhancement +61/-46

Soft enforcement nudges, simplified team selection, lean injection

• Replaced hard-blocking enforcement with adaptive per-turn nudges (silent → hint → warning → strong
 reminder) that never block tool usage
• Simplified team-mode selection from scoring-based (team_mode_score) to single rule: if
 TeamCreate available → team mode, else subagent
• Consolidated SessionStart injection from 3 hooks into 1 (inject_all.py): stub orchestrator
 (~1.1KB) on startup, full orchestrator (~7.5KB) on-demand, output style loaded natively
• Updated documentation to reflect soft enforcement mechanics, nudge escalation levels, and lean
 startup token savings (~6.6K tokens)

README.md


18. CLAUDE.md 📝 Documentation +35/-54

Soft enforcement policy, simplified team activation rules

• Changed delegation policy from mandatory hard blocks to soft nudges that escalate by per-turn
 violation count
• Removed /workflow-orchestrator:bypass toggle command from documented commands (now only for
 emergency access)
• Simplified team-mode activation from complex scoring rules to single check: TeamCreate tool
 availability
• Updated hook descriptions to reflect advisory-only validation and soft nudge mechanics with
 per-turn counter reset

CLAUDE.md


19. docs/ARCHITECTURE_QUICK_REFERENCE.md 📝 Documentation +85/-72

Removed scoring logic, simplified team mode decision tree

• Removed team_mode_score calculation flowchart; replaced with simple binary decision:
 TeamCreate available → team mode
• Updated state file reference from delegated_sessions.txt to delegation_violations.json with
 per-turn nudge counter format
• Changed hook execution table to reflect soft nudges, advisory-only validation, and counter reset
 on delegation
• Removed team mode scoring calculator; added simplified ONE RULE reference for mode selection

docs/ARCHITECTURE_QUICK_REFERENCE.md


20. system-prompts/token_efficient_cli.md 📝 Documentation +25/-131

Simplified token efficiency guidance to principles

• Removed mandatory rules prefix and binding constraint language; reframed as principles and
 guidance
• Condensed detailed command-by-command rules (git, search, file inspection, JSON, Python, JS/TS,
 Rust, Docker, Kubernetes, GitHub CLI, network, dependencies) into concise bullet-point principles
• Simplified file reading guidance to focus on partial reads, search-first strategy, and avoiding
 large config files
• Added note that PreToolUse hook handles compact flags automatically for common tools (git, pytest,
 cargo, npm, eslint, etc.)

system-prompts/token_efficient_cli.md


21. .claude-plugin/marketplace.json ⚙️ Configuration changes +1/-1

Version bump for soft enforcement release

• Bumped version from 1.16.0 to 1.17.0 to reflect soft enforcement and lean injection changes

.claude-plugin/marketplace.json


22. commands/bypass.md Additional files +0/-41

...

commands/bypass.md


23. hooks/SessionStart/inject-output-style.py Additional files +0/-52

...

hooks/SessionStart/inject-output-style.py


24. hooks/SessionStart/inject_token_efficiency.py Additional files +0/-68

...

hooks/SessionStart/inject_token_efficiency.py


25. hooks/SessionStart/inject_workflow_orchestrator.py Additional files +0/-126

...

hooks/SessionStart/inject_workflow_orchestrator.py


26. tests/conftest.py Additional files +0/-9

...

tests/conftest.py


27. tests/test_inject_token_efficiency.py Additional files +0/-171

...

tests/test_inject_token_efficiency.py


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1)   📘 Rule violations (2)   📎 Requirement gaps (0)   🎨 UX Issues (0)
🐞\ ☼ Reliability (1)
📘\ ≡ Correctness (2)

Grey Divider


Action required

1. Hardcoded /tmp debug log📘
Description
remind_skill_continuation.py writes debug logs to a hardcoded /tmp/... path, which is
non-portable and bypasses tempfile.gettempdir(). This can break on Windows and violates the
required temp-path construction pattern.
Code

hooks/PostToolUse/remind_skill_continuation.py[R27-33]

DEBUG = os.environ.get("DEBUG_DELEGATION_HOOK", "0") == "1"
if DEBUG:
logging.basicConfig(
-        filename="/tmp/delegation_hook_debug.log",
+        filename="/tmp/delegation_hook_debug.log",  # noqa: S108
   level=logging.DEBUG,
   format="%(asctime)s - remind_skill_continuation - %(message)s",
)
Evidence
PR Compliance ID 62792 requires temp paths to be built from Path(tempfile.gettempdir()) rather
than hardcoding /tmp. The changed line configures
logging.basicConfig(filename="/tmp/delegation_hook_debug.log").

Rule 62792: Construct temporary file paths using tempfile.gettempdir and pathlib.Path
hooks/PostToolUse/remind_skill_continuation.py[27-33]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`hooks/PostToolUse/remind_skill_continuation.py` hardcodes `/tmp/delegation_hook_debug.log` for debug logging, which is not cross-platform and violates the temp-path construction compliance rule.
## Issue Context
This hook runs via `uv run --script` and should work on Windows/macOS/Linux.
## Fix Focus Areas
- hooks/PostToolUse/remind_skill_continuation.py[27-33]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. print() used in hook📘
Description
remind_skill_continuation.py uses print(...) for output instead of using logging or direct
sys.stdout.write. This violates the no-print policy for Python modules/scripts outside
explicitly approved exceptions.
Code

hooks/PostToolUse/remind_skill_continuation.py[R65-69]

       "additionalContext": CONTINUATION_CONTEXT,
   }
}
-    print(json.dumps(output, ensure_ascii=False))
+    print(json.dumps(output, ensure_ascii=False))  # noqa: T201 — hook stdout JSON
+
Evidence
PR Compliance ID 62796 disallows print in Python modules and requires logging instead. The changed
line uses print(json.dumps(...)) to emit output.

Rule 62796: Disallow print statements in Python modules; use logging instead
hooks/PostToolUse/remind_skill_continuation.py[64-69]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A hook script uses `print(...)`, which violates the repo policy to avoid `print` and use logging/structured output mechanisms.
## Issue Context
This hook needs to emit JSON to stdout; that can be done with `sys.stdout.write(...)` (and a trailing newline) while keeping diagnostic output on stderr via logging.
## Fix Focus Areas
- hooks/PostToolUse/remind_skill_continuation.py[64-69]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. require_delegation exits 0 on exception📘
Description
require_delegation.py catches all exceptions and exits with code 0, masking unexpected failures as
success. This violates the standardized hook exit-code policy requiring 1 for unexpected errors.
Code

hooks/PreToolUse/require_delegation.py[R149-154]

if __name__ == "__main__":
try:
   sys.exit(main())
-    except Exception as e:
-        debug_log(f"UNCAUGHT EXCEPTION: {e}")
-        # Exit 1 for internal errors (distinct from 0=allow, 2=block)
-        logger.error("Hook internal error: %s", e)
-        sys.exit(1)
+    except Exception as e:  # noqa: BLE001
+        logger.error("require_delegation hook error: %s", e)
+        sys.exit(0)  # Never block, even on internal errors
Evidence
PR Compliance ID 62802 requires hooks to use exit code 1 for unexpected errors/exceptions. The
changed exception handler explicitly calls sys.exit(0) even on errors.

Rule 62802: Standardize hook script exit codes
hooks/PreToolUse/require_delegation.py[149-154]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`hooks/PreToolUse/require_delegation.py` exits with code `0` even when an exception occurs, which hides internal failures and violates the exit-code standardization rule.
## Issue Context
Even if the hook is “soft enforcement”, unexpected internal errors must still surface via exit code `1` (hook error) per policy.
## Fix Focus Areas
- hooks/PreToolUse/require_delegation.py[149-154]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (4)
4. Missing PEP 723 in validate hook📘
Description
validate_task_graph_compliance.py is executed via uv run --script but lacks a PEP 723 `# ///
script` metadata block. This violates the required dependency-metadata convention for standalone
scripts.
Code

hooks/PreToolUse/validate_task_graph_compliance.py[R1-9]

#!/usr/bin/env python3
"""
-PreToolUse Hook: Validate Task Graph Compliance (cross-platform)
+PreToolUse Hook: Task Graph Compliance Hint (cross-platform)
-Validates that when an active task graph exists, Task invocations
-include valid phase IDs that match the current execution wave.
-
-This Python version works on Windows, macOS, and Linux.
+Soft enforcement: never blocks. When an active task graph exists and an
+Agent/Task spawn doesn't match the current wave, write a hint to stderr.
+The model can self-correct on the next call. Wave/dependency violations no
+longer halt execution.
"""
Evidence
PR Compliance ID 62801 requires modified standalone scripts run via uv run --script to include a
PEP 723 inline metadata header starting with # /// script. The file starts with a shebang and
docstring but no PEP 723 block.

Rule 62801: Use PEP 723 inline script metadata for Python script dependencies
hooks/PreToolUse/validate_task_graph_compliance.py[1-9]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`hooks/PreToolUse/validate_task_graph_compliance.py` is run as a standalone `uv run --script` hook but is missing the required PEP 723 inline metadata block.
## Issue Context
Other hook scripts in this repo use the `# /// script` format with `requires-python`.
## Fix Focus Areas
- hooks/PreToolUse/validate_task_graph_compliance.py[1-9]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Removed team_mode_score fallback logic 📘
Description
Execution-mode selection was simplified to always choose team mode whenever TeamCreate is
available, removing the required team_mode_score <= -3 fallback to subagent mode. This violates
the required mode-selection behavior when experimental teams are enabled.
Code

commands/delegate.md[R15-17]

+## EXECUTION MODE (ONE RULE)
-### Step 0: Team/Collaboration Detection (CHECK FIRST)
+**If `TeamCreate` is in your available tools -> `execution_mode: "team"`. Otherwise -> `"subagent"`.** No scoring, no exceptions. Do not run Bash to check env vars -- tool availability is the signal.
Evidence
PR Compliance ID 106549 requires defaulting to team mode when experimental teams are enabled AND
TeamCreate is available, but only falling back to subagent when team_mode_score <= -3. The updated
docs/instructions explicitly state “No scoring, no exceptions,” and the orchestrator stub likewise
defaults to team mode solely based on tool availability.

Rule 106549: Default to team mode when experimental agent teams flag is enabled
commands/delegate.md[15-17]
system-prompts/orchestrator_stub.md[13-17]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Mode-selection instructions now remove `team_mode_score` entirely and do not implement the required fallback to subagent mode when `team_mode_score <= -3`.
## Issue Context
Compliance requires:
- if `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` and `TeamCreate` is available: default to team
- only fall back to subagent when `team_mode_score <= -3`
## Fix Focus Areas
- commands/delegate.md[15-17]
- system-prompts/orchestrator_stub.md[13-17]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. No team_mode_active auto-create 📘
Description
The PreToolUse flow no longer auto-creates .claude/state/team_mode_active when experimental teams
are enabled and a team tool is invoked. This breaks the required team-mode marker behavior and can
prevent other hooks from recognizing team mode.
Code

hooks/PreToolUse/require_delegation.py[R131-133]

+    tool_name = str(data.get("tool_name", ""))
+    if tool_name not in WORK_TOOLS:
+        return 0
Evidence
PR Compliance ID 157703 requires a PreToolUse hook to create .claude/state/team_mode_active when
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=='1' and a team tool is used. The updated
require_delegation.py immediately returns for any non-work tool (including
TeamCreate/SendMessage), so it never creates the marker file.

Rule 157703: Auto-create team_mode_active state for team tool usage when experimental teams flag is enabled
hooks/PreToolUse/require_delegation.py[131-133]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A PreToolUse hook must create `.claude/state/team_mode_active` when experimental teams are enabled and a team tool is invoked, but the current logic returns early for non-work tools and never creates the marker.
## Issue Context
This marker is used by other components/hooks to detect team mode.
## Fix Focus Areas
- hooks/PreToolUse/require_delegation.py[131-133]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Orchestrator team spawn mismatch🐞
Description
The PR updates /workflow-orchestrator:delegate docs to spawn teammates WITHOUT run_in_background,
but system-prompts/workflow_orchestrator.md (which README says is loaded on first delegation) still
instructs team spawning with run_in_background: true and still references team_mode_score, so the
actual orchestrator guidance remains inconsistent and can keep producing non-persistent teammates /
wrong mode selection.
Code

commands/delegate.md[R425-431]

+**Step 1: Execute as teammates** -- For EACH phase, spawn with `team_name` and **WITHOUT** `run_in_background`:
Evidence
commands/delegate.md now explicitly forbids run_in_background for team members, but
workflow_orchestrator.md still tells the orchestrator to use run_in_background: true for team mode
and to use subagent mode when team_mode_score < 5. README states workflow_orchestrator.md is loaded
on first delegation, so this inconsistency can directly drive runtime behavior.

commands/delegate.md[419-431]
system-prompts/workflow_orchestrator.md[430-465]
README.md[280-292]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The system prompt `system-prompts/workflow_orchestrator.md` still contains outdated team-mode execution instructions (uses `run_in_background: true` for teammates and references `team_mode_score`). This conflicts with the PR’s updated team-mode behavior in `commands/delegate.md` and with the PR description’s “persistent teammates” fix.
## Issue Context
README indicates `workflow_orchestrator.md` is loaded on-demand when `/workflow-orchestrator:delegate` runs, so stale instructions here can override the corrected guidance elsewhere.
## Fix Focus Areas
- system-prompts/workflow_orchestrator.md[430-470]
- commands/delegate.md[419-448]
- README.md[280-292]
## What to change
- In `workflow_orchestrator.md` team-mode section, remove `run_in_background: true` from teammate spawn example and align wording with `commands/delegate.md` (persistent teammates).
- Remove/replace any `team_mode_score`-based fallback logic with the new single rule: `TeamCreate` available => team mode, else subagent.
- Ensure team-mode instructions mention parallelism comes from concurrent teammates (not background tasks).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

8. delegation_active never set 🐞
Description
hooks/PreToolUse/require_delegation.py suppresses nudges when .claude/state/delegation_active
exists, but the PR no longer creates this flag anywhere, so suppression cannot trigger and the
documented/tested behavior is unreachable.
Code

hooks/PreToolUse/require_delegation.py[R119-122]

+    # If a delegation is active in this session, the main agent is steering
+    # subagents — direct tool use is fine.
+    if (state_dir / "delegation_active").exists():
   return 0
Evidence
require_delegation.py checks for delegation_active to bypass nudges, and the per-turn reset hook
deletes delegation_active at the start of each user prompt, but no production hook shown creates it;
tests only simulate it by touching the file. CLAUDE.md also documents delegation_active as a real
lifecycle flag.

hooks/PreToolUse/require_delegation.py[117-123]
hooks/UserPromptSubmit/clear-delegation-sessions.py[99-114]
tests/test_require_delegation.py[211-223]
CLAUDE.md[181-187]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`require_delegation.py` contains a suppression path based on `.claude/state/delegation_active`, but nothing in the current codebase appears to create that flag anymore. This makes the suppression mechanism non-functional and undermines the documented state model.
## Issue Context
- `clear-delegation-sessions.py` deletes `delegation_active` at the start of each user prompt.
- `tests/test_require_delegation.py` manually `touch()`es the file to test suppression, implying it should exist in real workflows.
## Fix Focus Areas
- hooks/PreToolUse/require_delegation.py[117-123]
- hooks/PostToolUse/remind_skill_continuation.py[91-124]
- hooks/UserPromptSubmit/clear-delegation-sessions.py[99-114]
- CLAUDE.md[181-187]
## What to change
- Create/touch `.claude/state/delegation_active` when `/workflow-orchestrator:delegate` is invoked (likely in `remind_skill_continuation.py` alongside the existing delegate-detection logic), and optionally remove it when the workflow finishes.
- Alternatively, if the flag is no longer part of the design, remove the check from `require_delegation.py` and update docs/tests accordingly.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Advisory comments

9. Docs reference removed hook🐞
Description
CLAUDE.md still instructs users to verify SessionStart injection via
inject_workflow_orchestrator.py, but SessionStart is now wired to inject_all.py, which can mislead
debugging and installation steps.
Code

hooks/plugin-hooks.json[R84-89]

   "hooks": [
     {
       "type": "command",
-            "command": "uv run --no-project --script \"${CLAUDE_PLUGIN_ROOT}/hooks/SessionStart/inject_workflow_orchestrator.py\"",
+            "command": "uv run --no-project --script \"${CLAUDE_PLUGIN_ROOT}/hooks/SessionStart/inject_all.py\"",
       "timeout": 20
-          },
-          {
-            "type": "command",
-            "command": "uv run --no-project --script \"${CLAUDE_PLUGIN_ROOT}/hooks/SessionStart/inject-output-style.py\"",
-            "timeout": 10
-          },
-          {
-            "type": "command",
-            "command": "uv run --no-project --script \"${CLAUDE_PLUGIN_ROOT}/hooks/SessionStart/inject_token_efficiency.py\"",
-            "timeout": 10
     }
Evidence
plugin-hooks.json shows SessionStart now runs inject_all.py, while CLAUDE.md troubleshooting text
still references inject_workflow_orchestrator.py for ensuring workflow_orchestrator.md injection.

hooks/plugin-hooks.json[81-90]
CLAUDE.md[272-274]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Docs still reference `inject_workflow_orchestrator.py` for SessionStart troubleshooting, but the plugin now uses `inject_all.py`.
## Issue Context
This can send users to a non-existent/unused hook when diagnosing missing orchestration behavior.
## Fix Focus Areas
- CLAUDE.md[272-274]
- hooks/plugin-hooks.json[81-90]
## What to change
- Replace references to `inject_workflow_orchestrator.py` with `inject_all.py` and adjust the explanation to reflect the new “stub on SessionStart, full prompt on-demand” behavior.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

Comment thread hooks/PostToolUse/remind_skill_continuation.py
Comment thread hooks/PostToolUse/remind_skill_continuation.py
Comment thread hooks/PreToolUse/require_delegation.py Outdated
Comment thread hooks/PreToolUse/validate_task_graph_compliance.py
Comment thread commands/delegate.md
Comment on lines +15 to +17
## EXECUTION MODE (ONE RULE)

### Step 0: Team/Collaboration Detection (CHECK FIRST)
**If `TeamCreate` is in your available tools -> `execution_mode: "team"`. Otherwise -> `"subagent"`.** No scoring, no exceptions. Do not run Bash to check env vars -- tool availability is the signal.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

5. Removed team_mode_score fallback logic 📘 Rule violation ≡ Correctness

Execution-mode selection was simplified to always choose team mode whenever TeamCreate is
available, removing the required team_mode_score <= -3 fallback to subagent mode. This violates
the required mode-selection behavior when experimental teams are enabled.
Agent Prompt
## Issue description
Mode-selection instructions now remove `team_mode_score` entirely and do not implement the required fallback to subagent mode when `team_mode_score <= -3`.

## Issue Context
Compliance requires:
- if `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` and `TeamCreate` is available: default to team
- only fall back to subagent when `team_mode_score <= -3`

## Fix Focus Areas
- commands/delegate.md[15-17]
- system-prompts/orchestrator_stub.md[13-17]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +131 to +133
tool_name = str(data.get("tool_name", ""))
if tool_name not in WORK_TOOLS:
return 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

6. No team_mode_active auto-create 📘 Rule violation ≡ Correctness

The PreToolUse flow no longer auto-creates .claude/state/team_mode_active when experimental teams
are enabled and a team tool is invoked. This breaks the required team-mode marker behavior and can
prevent other hooks from recognizing team mode.
Agent Prompt
## Issue description
A PreToolUse hook must create `.claude/state/team_mode_active` when experimental teams are enabled and a team tool is invoked, but the current logic returns early for non-work tools and never creates the marker.

## Issue Context
This marker is used by other components/hooks to detect team mode.

## Fix Focus Areas
- hooks/PreToolUse/require_delegation.py[131-133]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread commands/delegate.md
barkain and others added 3 commits April 8, 2026 10:54
Replace workflow-demo.gif with new 4x-speed recording of the team-mode
calculator app workflow. Replace the 5 legacy subagent-flow screenshots
with 4 new ones showing plan mode, dependency graph, tmux swarm view,
and team completion. Rewrite the walkthrough text to describe the
TeamCreate + persistent teammate + SendMessage coordination flow.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- remind_skill_continuation.py: use tempfile.gettempdir() for debug log
  path (cross-platform) and sys.stdout.write instead of print (T201).
- require_delegation.py: exit 1 on unexpected exception per hook
  exit-code policy (still non-blocking for the tool call itself).
- validate_task_graph_compliance.py, validate_task_graph_depth.py: add
  PEP 723 script metadata block (required for uv run --script).
- Delete orphaned system-prompts/workflow_orchestrator.md. No Python
  code loads this file; the full orchestrator logic lives in
  commands/delegate.md, which is injected by the slash command on
  demand. Update README.md and CLAUDE.md references accordingly.

Qodo #5 (team_mode_score fallback) and #6 (team_mode_active auto-create)
are intentional / false positives and will be replied to on the PR.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@barkain

barkain commented Apr 8, 2026

Copy link
Copy Markdown
Owner Author

Addressed qodo review in 35fc5f5.

Fixed (5):

  1. remind_skill_continuation.py debug path → tempfile.gettempdir()
  2. remind_skill_continuation.pysys.stdout.write instead of print
  3. require_delegation.pysys.exit(1) on unexpected exception (still non-blocking for the tool)
  4. validate_task_graph_compliance.py + validate_task_graph_depth.py → PEP 723 # /// script block added
  5. system-prompts/workflow_orchestrator.md deleted (orphan — no Python code loaded it, confirmed via grep). README + CLAUDE.md references updated to point at commands/delegate.md, which is where the full orchestrator logic actually lives.

Rejected (2):

#5team_mode_score fallback removed. This is intentional and is the core of the PR, not a regression. The previous scoring table (8 factors, thresholds, <= -3 exception) was the specific off-ramp that caused the calculator-app bug: the planner rationalized its way into subagent mode even when TeamCreate was available. Replacing it with a one-rule decision (TeamCreate available → team mode, else subagent) was validated end-to-end on a fresh session — persistent teammates spawn into the tmux swarm and the previous sequential-waves failure mode is gone.

#6team_mode_active auto-create missing from PreToolUse hook. False positive. The marker is written by the orchestrator (main agent) during team bootstrap per commands/delegate.md §"Stage 1: Execution (Team Mode)" Step 0 and "State files" line, not by a hook. Verified data flow: orchestrator writes → validate_task_graph_compliance.py reads (to bypass itself in team mode) → clear-delegation-sessions.py clears on each new user prompt. The old hook-write path was part of the pre-soft-enforcement design where the hook also blocked team tools; both the block and the write were removed together.

barkain and others added 2 commits April 8, 2026 11:50
…e.md

The orphan system-prompts/workflow_orchestrator.md was deleted in the
previous commit. Update the four secondary docs that still referenced
it. CHANGELOG entry left untouched (historical record).

- ARCHITECTURE_QUICK_REFERENCE.md: troubleshooting checklist + multi-step
  workflow example now point at inject_all.py and the slash command.
- environment-variables.md: Related links collapsed to commands/delegate.md.
- plan-explore-parallel-processing.md: 4 architectural references updated.
- validation-schema.md: Related Documentation pointer updated.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Soft-enforcement delegation, simplified team-mode selection, lean
SessionStart injection, and team-spawn fix. See CHANGELOG.md for
the full release notes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@barkain
barkain merged commit f831fd2 into main Apr 8, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant