# agdt-initiate-work-on-jira-issue-workflow

> **General template.** Copy this file to
> `.agdt-temp/EXPECTATIONS-agdt-initiate-work-on-jira-issue-workflow.md` and
> specialize it for your exact command and flags before executing.

## TL;DR

Starts the implement-a-Jira-issue workflow. When run outside the issue's
worktree/branch, pre-flight fails and a background auto-setup creates the
worktree, opens VS Code, and starts a Copilot session. When run in-context,
the command fetches the Jira issue (retrieve step), then advances to the
planning step and renders the planning prompt. A `langchain` engine path routes
the whole workflow through the LangGraph runner (with optional resume).

## Parameters & State Keys

### CLI flags

| Flag | Effect | Default |
|------|--------|---------|
| `--issue-key` | Jira issue key to work on. Falls back to `jira.issue_key` state when omitted. | none |
| `--interactive true\|false` | Start the Copilot session attached vs background. | `false` |
| `--model <id>` | Copilot model for the session. | project config or `gpt-4o` |
| `--skip-copilot-session` | Skip starting a Copilot session (used by nested auto-execute). | off |
| `--engine langchain` | Route the workflow through the LangGraph runner. | default (non-langchain) |
| `--use-langchain` | Alias for `--engine langchain`. | off |
| `--resume` | Resume from an existing LangGraph checkpoint. Requires `--engine langchain`. | off |
| `--resume-data <json>` | JSON object payload passed as `Command(resume=...)` when resuming an interrupted or incomplete checkpoint. Requires `--resume`. | none |
| `--execution-mode` | Execution safety policy mode: `live` (default behavior), `dry_run` (simulate all external mutations), or `restricted` (block all non-read-only actions). Persisted to `orchestration.execution_mode` in state after scope is established. Honored by the `SafetyEnforcer` in `ToolExecutor`. | resolved from state/env |

### State keys

| Key | Role |
|-----|------|
| `jira.issue_key` | Issue under work (CLI value or required state). |
| `copilot.model_id` | Persisted model id for the session. |
| `orchestration.execution_mode` | Persisted `--execution-mode` value (`live`/`dry_run`/`restricted`); written after bootstrap scope is established; honored by the `SafetyEnforcer`. |
| `agdt_run_id` | Run id for the single-commit-per-run amend strategy. |
| `workflow` | Workflow state record (`work-on-jira-issue`, step `retrieve` then `planning`). |
| `background.task_id` | Background auto-setup task id (preflight-fail path). |
| `worktree_setup.*` | Parameters consumed by the background setup task. |

### Environment overrides

| Variable | Effect |
|----------|--------|
| `AGENTIC_DEVTOOLS_STATE_DIR` | Pins the state directory and skips bootstrap scope derivation. |
| `AGDT_DRY_RUN` / `dry_run` state | Preview mode honored by downstream action commands. |
| `AGDT_AUTO_TRUST_COPILOT` | Optional kill-switch for auto-trusting agdt-managed worktree folders before Copilot launch (`0`/`false`/`no`/`off` disables). |

## Decision Points / Paths

1. **Resume validation** — `--resume` requires `--engine langchain`;
   `--resume-data` requires `--resume` and must be a JSON object. Violations
   exit `1`.
2. **Issue key resolution** — from `--issue-key` or `jira.issue_key`; empty or
   missing exits `1`.
3. **Engine** — `langchain` routes to `run_langchain_workflow` (honoring
   `--resume` / `--resume-data`) and returns; otherwise the default path runs.
4. **Pre-flight** — PASS proceeds to the retrieve step in-context; FAIL spawns
   the background auto-setup.
5. **`--skip-copilot-session`** — when set on the PASS path, the command stops
   after rendering the planning prompt without starting a session.
6. **`--interactive`** — attached vs background session.
7. **Jira fetch during retrieve** — failure is non-fatal (warns and proceeds
   with limited context).
8. **Copilot folder trust seeding** — after a worktree is validated/created (not
   before), the workflow best-effort seeds Copilot CLI `trustedFolders` for that
   path (gated by `AGDT_AUTO_TRUST_COPILOT` and project flag
   `auto_trust_copilot_worktrees`).

## Execution Flow

1. Parse flags; resolve `model`; map `--use-langchain` to `--engine langchain`.
2. Validate resume flags; exit `1` on violation.
3. Resolve bootstrap scope and clear workflow tracking state; set
   `copilot.model_id` and `orchestration.execution_mode` (when
   `--execution-mode` was provided).
4. Resolve the issue key from the CLI or required state; exit `1` if empty;
   persist `jira.issue_key`.
5. **Engine `langchain`** → run the LangGraph workflow (with `resume` /
   `resume_data`) and return.
6. Run the pre-flight check.
7. **Pre-flight FAIL** → build the nested auto-execute command and call
   `perform_auto_setup(...)`; on success print the message and return.
8. **Pre-flight PASS** → execute the retrieve step: set workflow state to
   `retrieve`, fetch the Jira issue synchronously, then advance to the planning
   step and render the planning prompt.
9. When `--skip-copilot-session` is not set, start the Copilot session for the
   work-on-jira-issue workflow.

## Observable Side Effects

- **Worktree** — created on the preflight-fail path (branch
  `feature/<issue-key>/...`), with VS Code settings injected.
- **State directory** `.agdt/workflows/{identity}/{worktree_key}/` containing:
  `state.json`, `temp-get-issue-details-response.json`, and
  `temp-work-on-jira-issue-planning-prompt.md`.
- **Workflow state** always advanced to step `planning` (in-context path), even
  when the Jira fetch fails — `_execute_retrieve_step()` catches `SystemExit`/exceptions,
  prints a warning, and proceeds to planning with empty context fields.
- **Background task** record + logs (preflight-fail path).
- **Jira** — read-only fetch of the issue for planning context.
- **Process / VS Code** — a new VS Code window and a `gh copilot` session
  (in-context path, unless skipped).
- **LangGraph checkpoint** — when `--engine langchain` is used.

## Success Criteria

1. Pre-flight correctly classifies context (no `_unscoped` fallback dir).
2. On the in-context path, the Jira issue is fetched and the workflow reaches
   the `planning` step with the planning prompt rendered to the state directory.
3. On the preflight-fail path, the worktree is created and a Copilot session is
   prepared via auto-setup.
4. The engine path matches the selection (default vs langchain), and resume
   flags behave per their validation rules.
5. `agdt-get-workflow` shows `name=work-on-jira-issue` with the correct
   issue-key context.

## AI Agent Session Choreography

The initiate command is only the **bootstrap**: it prepares state, renders the
first prompt, and (unless `--skip-copilot-session`) launches a `gh copilot`
session. Everything after that is a **prompt-driven, event-advanced journey**
through the `work-on-jira-issue` state machine
([`manager.py`](../../agentic_devtools/cli/workflows/manager.py) →
`WORK_ON_JIRA_ISSUE_WORKFLOW`). Each step has a default prompt under
[`agentic_devtools/prompts/work-on-jira-issue/`](../../agentic_devtools/prompts/work-on-jira-issue/)
that is rendered to `temp-work-on-jira-issue-<step>-prompt.md` in the state
directory and printed to the console when the workflow enters that step.

### Session entrypoint

- The `gh copilot` session is opened with the **planning** prompt
  (`temp-work-on-jira-issue-planning-prompt.md`) as its first message — see
  `_start_copilot_session_for_work_on_jira_issue` in
  [`worktree_setup.py`](../../agentic_devtools/cli/workflows/worktree_setup.py)
  (`_WORKFLOW_PROMPT_FILENAMES["work-on-jira-issue"]`). The `retrieve` step has
  already run synchronously during bootstrap, so the agent starts at planning
  with the Jira issue already fetched.
- On the **preflight-fail** path the entrypoint is reached only after the
  background auto-setup creates the worktree and re-runs the command (with
  `--skip-copilot-session`) inside it; the Copilot session is then started in
  the new worktree.

### How the agent is guided between steps

Two advancement mechanisms drive the journey (see the class docstrings in
`manager.py` and the *Workflow Transition Behavior* section of the root
`copilot-instructions.md`):

- **Immediate auto-advance** (`auto_advance=True`, no `required_tasks`): the
  triggering `agdt-*` command advances the step and immediately prints the next
  step's rendered prompt, so the agent simply keeps reading and acting.
- **Deferred auto-advance** (`auto_advance=True` **with** `required_tasks`): a
  `pending_transition` is recorded; the step changes only when the agent calls
  `agdt-get-next-workflow-prompt` **and** the named background task has
  completed. Used for `commit` and `pull-request` (which fan out to
  `agdt-git-save-work` / `agdt-create-pull-request` background tasks).
- **Manual advance** (`auto_advance=False`): the agent must explicitly run
  `agdt-advance-workflow <step>` (used after planning, checklist review,
  verification, etc.).
- **Decision resolution**: when a node raises a pending decision, the agent resolves it with
  `agdt-advance-workflow --decision {approve|deny} --decision-id <ID> [--run-id <RUN_ID>]`
  instead of a step name.

### Step-by-step choreography

| Step | Prompt presented to the agent | Commands the agent is expected to run | Transition event → next step |
|------|-------------------------------|---------------------------------------|------------------------------|
| `retrieve` (bootstrap) | `default-retrieve-prompt.md` | (already executed) `agdt-get-jira-issue` runs during bootstrap; result saved to `temp-get-issue-details-response.json` | `JIRA_ISSUE_RETRIEVED` (auto) → `planning` |
| `planning` | `default-planning-prompt.md` | Analyze the issue; draft a Jira-markup plan; `agdt-set jira.comment "..."` then `agdt-add-jira-comment` (or `--jira-comment`) | `JIRA_COMMENT_ADDED` (or `MANUAL_ADVANCE`) → `checklist-creation` |
| `checklist-creation` | `default-checklist-creation-prompt.md` | `agdt-create-checklist "1. ...\|2. ..."` (or `agdt-set checklist_items` + `agdt-create-checklist`) | `CHECKLIST_CREATED` (or `MANUAL_ADVANCE`) → `implementation` |
| `implementation` | `default-implementation-prompt.md` | TDD red-green-refactor per item: `agdt-test-pattern <test> -v`, edit source, `agdt-test`/`agdt-task-wait`, `agdt-update-checklist`, `agdt-git-save-work --completed "1,2,3"` | `CHECKLIST_COMPLETE` (auto, when all items done) → `implementation-review`; or `MANUAL_ADVANCE` → `verification` (skip review) |
| `implementation-review` | `default-implementation-review-prompt.md` | Self-review code quality/tests/docs/ACs; fix and re-commit if needed (re-triggers review); `agdt-advance-workflow verification` | `MANUAL_ADVANCE` → `verification` |
| `verification` | `default-verification-prompt.md` | Run quality gates (`agdt-test` + `agdt-task-wait`, `ruff check`/`ruff format --check`, `cspell`); `agdt-advance-workflow commit` | `MANUAL_ADVANCE` → `commit` |
| `commit` | `default-commit-prompt.md` | `agdt-set commit_message "..."` then `agdt-git-save-work` (spawns the `agdt-git-save-work` background task) | `GIT_COMMIT_CREATED`/`GIT_BRANCH_PUSHED` (deferred — needs `agdt-get-next-workflow-prompt`) → `pull-request` |
| `pull-request` | `default-pull-request-prompt.md` | `agdt-set source_branch/title/description` then `agdt-create-pull-request` (background task) | `PR_CREATED` (deferred — needs `agdt-get-next-workflow-prompt`) → `completion` |
| `completion` | `default-completion-prompt.md` | `agdt-set jira.comment "h4. Work Complete ..."` + `agdt-add-jira-comment`; then `agdt-clear-workflow` | terminal step |

### Subagents

This workflow is driven primarily by the in-process state machine rather than by
spawned subagents. The custom `@agdt.work-on-jira-issue.*` Copilot Chat agents
(one per step, e.g. `@agdt.work-on-jira-issue.planning`) are thin entry points
that map to these same prompts; an auditing agent following
[`agdt.test-workflow`](../../.github/prompts/agdt.test-workflow.prompt.md) also
spawns a **rubber-duck subagent** to review the specialized expectations
document before execution (Phase 1, step 5).

## Workflow Diagram

```mermaid
flowchart TD
    Start([Command invoked]) --> Parse[Parse flags and resolve model and engine]
    Parse --> ResumeChk{Resume flags valid}
    ResumeChk -- No --> ExitResume[Print error and exit 1]
    ResumeChk -- Yes --> Scope[Bootstrap scope and clear tracking state]
    Scope --> Key{Issue key available}
    Key -- No --> ExitKey[Print error and exit 1]
    Key -- Yes --> Engine{Engine selected}
    Engine -- langchain --> LangRun[Run LangGraph workflow with optional resume]
    LangRun -.->|node raises pending decision| LangDec[Write decision to pending-decisions.json]
    LangDec -.->|agent: agdt-advance-workflow --decision approve/deny --decision-id ID| LangRun
    Engine -- default --> Preflight{In correct worktree and branch}
    Preflight -- No --> AutoSetup[Spawn background worktree auto-setup]
    AutoSetup --> Return[Print success and return]
    Preflight -- Yes --> Retrieve[Fetch Jira issue and set retrieve step]
    Retrieve --> Planning[Render planning prompt and set planning step]
    Planning --> Session{Skip copilot session set}
    Session -- Yes --> SyncDone[Return without session]
    Session -- No --> Copilot[Start Copilot session]
```

## Agent Session Choreography Diagram

This diagram shows the prompt-driven journey the Copilot agent takes **after**
the session starts, including the command that triggers each transition.

```mermaid
flowchart TD
    Entry([Copilot session opens on planning prompt]) --> Planning[planning step]
    Planning -->|agdt-add-jira-comment posts plan| ChecklistCreate[checklist-creation step]
    ChecklistCreate -->|agdt-create-checklist| Impl[implementation step]
    Impl -->|TDD loop: agdt-test-pattern, agdt-git-save-work --completed| ImplDone{All checklist items complete}
    ImplDone -- No --> Impl
    ImplDone -- Yes auto-advance --> ImplReview[implementation-review step]
    Impl -. agdt-advance-workflow verification skip review .-> Verify
    Impl -.->|orchestration node raises pending decision| PendingDec[Resolve: agdt-advance-workflow --decision approve/deny --decision-id ID]
    PendingDec -.->|execution resumes from checkpoint| Impl
    ImplReview -->|agdt-advance-workflow verification| Verify[verification step]
    Verify -->|agdt-advance-workflow commit| Commit[commit step]
    Commit -->|agdt-git-save-work then agdt-get-next-workflow-prompt| PR[pull-request step]
    PR -->|agdt-create-pull-request then agdt-get-next-workflow-prompt| Completion[completion step]
    Completion -->|agdt-add-jira-comment then agdt-clear-workflow| Done([Workflow complete])
```

---

This is a **general template**. Copy it to
`.agdt-temp/EXPECTATIONS-agdt-initiate-work-on-jira-issue-workflow.md` and
**specialize** it for your exact command and flags before executing.
