
    PL
j:                    B   d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ  ej        e          ZdZd	Z ej        d
ej                  Ze G d d                      Zd,dZd-dZd.dZd/dZd0dZd0dZd1dZd2d Z ddd!d3d'Z!dd(d4d+Z"dS )5uH  Kanban decomposer — fan a triage task out into a graph of child tasks.

Invoked by ``hermes kanban decompose [task_id | --all]`` and the
auto-decompose path in the gateway dispatcher loop. Reads the user's
profile roster (with descriptions) and asks the auxiliary LLM to
return a task graph in JSON. Then atomically creates the children,
links them under the root, and flips the root ``triage -> todo``.

The root task stays alive and becomes the parent of every leaf child,
so when the whole graph completes the root wakes back up — its
assignee (the orchestrator profile) gets a chance to judge completion
and add more tasks if the work isn't done yet.

Design notes
------------

* Mirrors the shape of ``hermes_cli/kanban_specify.py``: lazy aux
  client import inside the function, lenient response parse, never
  raises on expected failure modes.

* The system prompt sees the *configured* profile roster — names plus
  descriptions plus the default fallback. Profiles without a
  description are still listed (with a note) so the orchestrator can
  match on name as a fallback, but the user has an obvious incentive
  to describe them.

* ``fanout=false`` collapses to the same effect as ``kanban specify``:
  we tighten the body and flip ``triage -> todo`` as a single task,
  no children created. This makes ``decompose`` a strict superset of
  ``specify`` from the user's perspective.

* If the LLM picks an assignee that doesn't exist as a profile, we
  rewrite it to the configured ``default_assignee`` (or the default
  profile if unset). A child task NEVER ends up with ``assignee=None``.
    )annotationsN)	dataclass)Optional)	kanban_db)profilesu  You are the Kanban decomposer for the Hermes Agent board.

A user dropped a rough idea into the Triage column. Your job is to break it
into a small graph of concrete child tasks and route each one to the best-
matching profile from the available roster.

You will be given:
  - The original task title and body
  - The list of available profiles (each with name + description)
  - The fallback "default_assignee" used when no profile fits

Output a single JSON object with this exact shape:

  {
    "fanout": true,
    "rationale": "<one sentence on why this decomposition>",
    "tasks": [
      {
        "title": "<concrete task title, imperative voice, <= 80 chars>",
        "body":  "<detailed spec for the worker on this child task>",
        "assignee": "<profile name from the roster, or null for default>",
        "parents": [<int>, ...]
      },
      ...
    ]
  }

Rules:
  - "parents" is a list of INDICES (0-based) into this same "tasks" list,
    expressing actual data dependencies. Tasks with no parents run in
    PARALLEL. Tasks with parents wait until every parent completes.
  - Prefer parallelism. If two tasks can be done independently, give
    them no parents so the dispatcher fans them out at once.
  - Use 2-6 tasks for normal work. Don't create 20 tiny tasks. Don't
    cram everything into 1 task.
  - Pick assignees from the roster by matching the task to the profile's
    DESCRIPTION (not just the name). When nothing matches well, use null
    and the system will route to the default_assignee.
  - Each child task body is what a fresh worker will read with no other
    context — be specific about goal, approach, and acceptance criteria.

When the task is genuinely a single unit of work (no useful decomposition),
return:

  {
    "fanout": false,
    "rationale": "<one sentence>",
    "title": "<tightened title>",
    "body":  "<concrete spec for a single worker>"
  }

In that case the task stays as one work item, just with a tightened spec.

No preamble, no closing remarks, no code fences. Output only the JSON object.
zTask id: {task_id}
Title: {title}
Body:
{body}

Available profiles (assignees you may pick from):
{roster}

Default assignee (used when no profile fits a task): {default_assignee}
z^```(?:json)?\s*|\s*```$c                  `    e Zd ZU dZded<   ded<   dZded<   dZded	<   d
Zded<   d
Zded<   d
S )DecomposeOutcomez+Result of decomposing a single triage task.strtask_idboolok reasonFfanoutNzlist[str] | None	child_idsOptional[str]	new_title)	__name__
__module____qualname____doc____annotations__r   r   r   r        ?/home/kuhnn/.hermes/hermes-agent/hermes_cli/kanban_decompose.pyr	   r	   |   sn         55LLLHHHFF"&I&&&&#I######r   r	   textr
   limitintreturnc                L    t          |           |k    r| S | d |dz
           dz   S )N   u   …)len)r   r   s     r   	_truncater#      s0    
4yyE%!)u$$r   rawOptional[dict]c                   | sd S t                               d|                                           }|                    d          }|                    d          }|dk    s|dk    s||k    rd S |||dz            }	 t          j        |          }n# t          t
          j        f$ r Y d S w xY wt          |t                    sd S |S )Nr   {}r!   )	_FENCE_REsubstripfindrfindjsonloads
ValueErrorJSONDecodeError
isinstancedict)r$   strippedfirstlast	candidatevals         r   _extract_json_blobr:      s     t}}R--HMM#E>>#D{{dbjjDEMMt)*Ij##,-   ttc4   tJs   >B B-,B-c                     t           j                            d          p t           j                            d          pdS )z0Mirror of ``hermes_cli.kanban._profile_author``.HERMES_PROFILEUSER
decomposer)osenvirongetr   r   r   _profile_authorrB      s9     	
'(( 	:>>&!!	r   r4   c                 L    	 ddl m}   |             pi S # t          $ r i cY S w xY w)Nr   load_config)hermes_cli.configrE   	ExceptionrD   s    r   _load_configrH      sN    111111{}}""   			s    ##cfgc                P   t          | t                    r|                     di           ni }|                    d          pd                                }|r(	 t	          j        |          r|S n# t          $ r Y nw xY w	 t	          j                    pdS # t          $ r Y dS w xY w)zResolve which profile owns decomposition.

    Falls back to the active default profile when ``kanban.orchestrator_profile``
    is unset, so a task is never stranded for lack of an orchestrator.
    kanbanorchestrator_profiler   defaultr3   r4   rA   r,   profiles_modprofile_existsrG   get_active_profile_namerI   
kanban_cfgexplicits      r   _resolve_orchestrator_profilerU      s     +5S$*?*?G2&&&RJ566<"CCEEH 	*844    	 	 	D	355BB   yy$   A1 1
A>=A>B 
B%$B%c                P   t          | t                    r|                     di           ni }|                    d          pd                                }|r(	 t	          j        |          r|S n# t          $ r Y nw xY w	 t	          j                    pdS # t          $ r Y dS w xY w)zGResolve which profile catches child tasks the orchestrator can't route.rK   default_assigneer   rM   rN   rR   s      r   _resolve_default_assigneerY      s    *4S$*?*?G2&&&RJ1228b??AAH 	*844    	 	 	D	355BB   yyrV   tuple[list[dict], set[str]]c                    g } t                      }	 t          j                    }n6# t          $ r)}t                              d|           | |fcY d}~S d}~ww xY w|D ]m}|j        pd                                }|                     |j	        |p
d|j	        dt          |          d           |                    |j	                   n| |fS )zReturn (roster_for_prompt, valid_assignee_names).

    Each roster entry is ``{name, description, has_description}``. The
    valid-set is used after the LLM responds to rewrite invalid
    assignees to the default fallback.
    z&decompose: failed to list profiles: %sNr   z(no description; profile named ))namedescriptionhas_description)setrO   list_profilesrG   loggerwarningr^   r,   appendr]   r   add)rostervalidall_profilesexcpdescs         r   _build_rosterrl      s    FeeE#133   ?EEEu}   #**,,FP#PQV#P#P#P#Dzz
 
 	 	 	
 			!&5=s   & 
AAAArf   
list[dict]c           	         | sdS g }| D ]7}|d         rdnd}|                     d|d          | d|d                     8d	                    |          S )
Nu:     (no profiles installed — decomposer cannot route work)r_   r   u    ⚠ undescribedz  - r]   z: r^   
)rd   join)rf   linesentrytags       r   _format_rosterrt      s     LKKE J J+,Dbb2DHE&MH3HH%2FHHIIII99Ur   )authortimeoutr   ru   r   rv   Optional[int]c          	       #$ t          j                    5 }t          j        ||           }ddd           n# 1 swxY w Y   |t          | dd          S |j        dk    rt          | dd|j        d          S t                      }t          |          }t          |          }t                      \  }}		 ddl	m
}
m} nC# t          $ r6}t                              d	|           t          | dd
          cY d}~S d}~ww xY w	  |d          \  }}nC# t          $ r6}t                              d|           t          | dd
          cY d}~S d}~ww xY w||st          | dd          S t                              |j        t%          |j        pdd          t%          |j        pdd          t+          |          |          }	 |j        j                            |dt2          dd|dgdd|pd |
            pd          }nY# t          $ rL}t                              d| |           t          | ddt7          |          j                   cY d}~S d}~ww xY w	 |j        d         j        j        pd}n# t          $ r d}Y nw xY wtA          |          }|t          | dd          S tC          |"                    d                    }|ptG                      }|s|"                    d          }|"                    d          }tI          |tJ                    r(|&                                r|&                                nd}tI          |tJ                    r|&                                r|nd}||t          | dd          S t          j                    5 }t          j'        || |||           }ddd           n# 1 swxY w Y   |st          | dd!          S t          | d"d#d|$          S |"                    d%          pg $tI          $tP                    r$st          | dd&          S g }tS          $          D ]\  #}tI          |tT                    st          | dd'# d(          c S |"                    d          }tI          |tJ                    r|&                                st          | dd'# d)          c S |"                    d          }tI          |tJ                    sd}|"                    d*          }tI          |tJ                    r|&                                s|}n'||	vr!t                              d+| #||           |}n|}|"                    d,          pg } tI          | tP                    sg } #$fd-| D             }!|+                    |&                                dd.         |&                                ||!d/           	 t          j                    5 }t          j,        || |||0          }"ddd           n# 1 swxY w Y   n~# tZ          $ r}t          | dd1|           cY d}~S d}~wt          $ rK}t          .                    d2|            t          | dd3t7          |          j                   cY d}~S d}~ww xY w|"t          | dd4          S t          | d"d5t_          |"           d6d"|"7          S )8uG  Decompose a triage task into a graph of child tasks.

    Returns an outcome describing what happened. Never raises for
    expected failure modes (task not in triage, no aux client
    configured, API error, malformed response, decomposer returned
    fanout=true with empty task list) — those surface via ``ok=False``.
    NFzunknown task idtriageztask is not in triage (status=r\   r   )get_auxiliary_extra_bodyget_text_auxiliary_clientz-decompose: auxiliary client import failed: %szauxiliary client unavailablekanban_decomposerz/decompose: get_text_auxiliary_client failed: %szno auxiliary client configuredr   i  z	(no body)i  )r   titlebodyrf   rX   system)rolecontentuserg333333?   )modelmessagestemperature
max_tokensrv   
extra_bodyz&decompose: API call failed for %s (%s)zLLM error: zLLM returned malformed JSONr   r}   r~   z3decomposer returned fanout=false with no title/body)r}   r~   ru   z)task moved out of triage before promotionTzsingle task (no fanout))r   r   tasksz5decomposer returned fanout=true with empty tasks listztasks[z] is not an objectz].title is missing or emptyassigneeuY   decompose: task %s child %d picked unknown assignee %r — routing to default_assignee %rparentsc                    g | ]<}t          |t                    d |cxk    rt                    k     1n n|k    :|=S )r   )r3   r   r"   ).0rj   idx	raw_taskss     r   
<listcomp>z"decompose_task.<locals>.<listcomp>  s\    kkkqz!S/A/Aka1F]F]F]F]sS\~~F]F]F]F]F]bcgjbjbjbjbjbjr      )r}   r~   r   r   )root_assigneechildrenru   zDB rejected graph: zdecompose: DB error on task %sz
DB error: z-task moved out of triage before decompositionzdecomposed into z	 children)r   r   )0kbconnectget_taskr	   statusrH   rU   rY   rl   agent.auxiliary_clientrz   r{   rG   rb   debug_USER_TEMPLATEformatidr#   r}   r~   rt   chatcompletionscreate_SYSTEM_PROMPTinfotyper   choicesmessager   r:   r   rA   rB   r3   r
   r,   specify_triage_tasklist	enumerater4   rd   decompose_triage_taskr1   	exceptionr"   )%r   ru   rv   conntaskrI   orchestratorrX   rf   valid_namesrz   r{   ri   clientr   user_msgrespr$   parsedr   audit_authorr   new_body	title_valbody_valr   r   rr   r}   r~   r   chosenr   clean_parentsr   r   r   s%                                      @@r   decompose_taskr      s2	    
 *{4))* * * * * * * * * * * * * * *|0ABBB{hUMT[MMM
 
 	
 ..C055L055'//FKP	
 	
 	
 	
 	
 	
 	
 	
 	
  P P PDcJJJ0NOOOOOOOOPP112EFF P P PFLLL0NOOOOOOOOP ~U~0PQQQ$$
(b#..ty/K66f%%) %  HT{&--!n==H55 Ns//119T . 

 

  T T T4gs	
 	
 	
  0Rd3ii>P0R0RSSSSSSSS	Tl1o%-3     $$F~0MNNN&**X&&''F._..L 
JJw''	::f%%)3Is)C)Cc	HYHYcIOO%%%_c	)(C88WX^^=M=MW88SW!1# U   Z\\ 	T'#  B	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	# K    T4I
 
 
 	

 

7##)rIi&& 
i 
US
 
 	
 H	** # #
U%&& 	# @ @ @ @     		'""%%% 	U[[]] 	# I I I I     yy  $$$ 	D99Z(((C(( 
	0@0@ 
	%FF[((KK1h(8  
 &FFF))I&&,"'4(( 	GkkkkkGkkk[[]]4C4(JJLL$	
 
 	 	 	 	SZ\\ 	T0*!#  I	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  M M M0Kc0K0KLLLLLLLL S S S97CCC0QT#YY=O0Q0QRRRRRRRRS UK
 
 	
 C#i..CCCy   s   8<<9C 
D+C=7D=DD 
E+E
EE	>H 
IAIII"I< <J
J#O		OO,X1 ?X%X1 %X))X1 ,X)-X1 1
Z,;YZ,Z,!A Z'!Z,'Z,)tenantr   	list[str]c                    t          j                    5 }t          j        |d| d          }ddd           n# 1 swxY w Y   d |D             S )z/Return task ids currently in the triage column.ry   i  )r   r   r   Nc                    g | ]	}|j         
S r   )r   )r   rows     r   r   z#list_triage_ids.<locals>.<listcomp>  s    ###sCF###r   )r   r   
list_tasks)r   r   rowss      r   list_triage_idsr     s    	 
}	
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 $#d####s   9= =)r   r
   r   r   r   r
   )r$   r
   r   r%   )r   r
   )r   r4   )rI   r4   r   r
   )r   rZ   )rf   rm   r   r
   )r   r
   ru   r   rv   rw   r   r	   )r   r   r   r   )#r   
__future__r   r/   loggingr?   redataclassesr   typingr   
hermes_clir   r   r   rO   	getLoggerr   rb   r   r   compile	MULTILINEr*   r	   r#   r:   rB   rH   rU   rY   rl   rt   r   r   r   r   r   <module>r      s  " "H # " " " " "   				 				 ! ! ! ! ! !       & & & & & & / / / / / /		8	$	$6r	 BJ2BLAA	 $ $ $ $ $ $ $ $% % % %   $         *       2    !!	s s s s s sl 04 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$r   