NW-DISCUSS: Jobs-to-be-Done Analysis, UX Journey Design, and Requirements Gathering
Wave: DISCUSS (wave 2 of 6) | Agent: Luna (nw-product-owner) | Command: /nw:discuss
Overview
Execute DISCUSS wave through Luna's integrated workflow: JTBD analysis|UX journey discovery|emotional arc design|shared artifact tracking|requirements gathering|user story creation|acceptance criteria definition. Luna uncovers jobs users accomplish, maps to journeys and requirements, handles complete lifecycle from user motivations through DoR-validated stories ready for DESIGN. Establishes ATDD foundation.
For greenfield projects (no src/ code, no docs/feature/ history), Luna proposes Walking Skeleton as Feature 0.
Interactive Decision Points
Decision 1: Feature Type
Question: What type of feature is this?
Options:
User-facing -- UI/UX functionality visible to end users
Grounds all subsequent artifacts in real user motivations.
Job Discovery: Ask user what users are trying to accomplish. Capture in job story format: "When [situation], I want to [motivation], so I can [outcome]."
Job Dimensions: For each job — functional (practical task)|emotional (desired feeling)|social (desired perception)
Four Forces Analysis: For each primary job:
Push (current frustration): "What frustrated users enough to request this?"
Pull (desired future): "What could they do that they cannot now?"
Anxiety (adoption concerns): "What concerns about adopting this?"
Habit (current behavior): "What behavior must change?"
If interview transcripts|support tickets|analytics exist, extract forces from those instead of relying solely on user description.
Opportunity Scoring (multiple jobs): Rank by importance vs. satisfaction gap. High importance + low satisfaction = strongest opportunities. Produce scored table.
JTBD-to-Story Bridge: Each job story feeds into user stories and acceptance criteria in Phase 3. Every user story must trace to at least one job.
Luna runs deep discovery (mental model|emotional arc|shared artifacts|error paths) informed by JTBD, produces visual journey + YAML schema + Gherkin scenarios. Each journey maps to one or more identified jobs.
Artifact
Path
Visual Journey
docs/ux/{epic}/journey-{name}-visual.md
Journey Schema
docs/ux/{epic}/journey-{name}.yaml
Gherkin Scenarios
docs/ux/{epic}/journey-{name}.feature
Artifact Registry
docs/ux/{epic}/shared-artifacts-registry.md
Phase 3 -- Requirements and User Stories:
Luna crafts LeanUX stories informed by JTBD + journey artifacts. Every story traces to at least one job story. Validates against DoR, invokes peer review, prepares handoff.
Artifact
Path
Requirements
docs/requirements/requirements.md
User Stories
docs/requirements/user-stories.md
Acceptance Criteria
docs/requirements/acceptance-criteria.md
DoR Checklist
docs/requirements/dor-checklist.md
Success Criteria
JTBD analysis complete: all jobs in job story format
Job dimensions identified: functional|emotional|social per job
Four Forces mapped per job (push|pull|anxiety|habit)
Opportunity scores produced (when multiple jobs)
UX journey map with emotional arcs and shared artifacts
Every journey maps to at least one job
Discovery complete: user mental model understood, no vague steps
Happy path defined: all steps start-to-goal with expected outputs
docs/ux/{epic}/
jtbd-job-stories.md
jtbd-four-forces.md
jtbd-opportunity-scores.md (when multiple jobs)
journey-{name}-visual.md
journey-{name}.yaml
journey-{name}.feature
shared-artifacts-registry.md
docs/requirements/
requirements.md
user-stories.md (each story traces to a job)
acceptance-criteria.md
dor-checklist.md
Examples
Example 1: User-facing feature with comprehensive UX research
code
/nw:discuss first-time-setup
Orchestrator asks Decision 1-4. User selects "User-facing", "No skeleton", "Comprehensive", "Multiple jobs". Luna starts with JTBD analysis: discovers jobs like "When I first open the app, I want to feel productive immediately, so I can justify the purchase." Maps four forces for each job. Scores opportunities. Then runs journey discovery informed by JTBD, produces visual journey + YAML + Gherkin. Finally crafts stories where each traces to a job, validates DoR, and prepares handoff.
Example 2: JTBD-only invocation
code
/nw:discuss --phase=jtbd onboarding-flow
Runs only Luna's JTBD analysis phase (job discovery + dimensions + four forces + opportunity scoring). Produces JTBD artifacts without proceeding to journey design or requirements. Useful for early discovery when you need to understand user motivations before committing to UX design.
Example 3: Journey-only invocation
code
/nw:discuss --phase=journey release-nwave
Runs only Luna's journey design phases (discovery + visualization + coherence validation). Produces journey artifacts without proceeding to requirements crafting. Useful when JTBD is already done and journey design needs standalone iteration.
Runs only Luna's requirements phases (gathering + crafting + DoR validation). Assumes JTBD and journey artifacts already exist or are not needed (e.g., backend feature).
ARGUMENTS: how are we gonna handle cleanup for coding agent task delegation?
Assistant
Let me first understand the current orchestrator and agent delegation architecture before we start the JTBD analysis.
Assistant
Let me explore the orchestrator and agent delegation code to ground this discussion in the actual system.
Assistant
Excellent research. Now I have a thorough understanding of the system. Let me run the JTBD analysis as Luna.
Based on the codebase exploration, this is cross-cutting infrastructure — it spans the orchestrator lifecycle (process management), git subsystem (worktrees/branches), database (session records), and in-memory state (handle registry, SSE streams, stall detectors).
Phase 1: Jobs-to-be-Done Analysis
Job Discovery
Let me frame the jobs from the perspectives I see in this system:
Job 1 — Crash Recovery (Operator)
"When the server crashes or restarts unexpectedly while coding agents are active, I want orphaned resources to be automatically detected and cleaned up, so I can trust the system recovers without manual intervention."
Job 2 — Graceful Shutdown (Operator)
"When I deploy a new server version or need to restart, I want active agent sessions to be cleanly terminated, so I don't lose session state or leave inconsistent DB records."
Job 3 — Resource Leak Prevention (System)
"When an agent session ends abnormally (network hang, SDK exception, stall timeout edge case), I want all associated resources cleaned up regardless of the termination path, so the system doesn't accumulate orphaned state over time."
Job 4 — Re-assignability (User)
"When an agent task fails or gets stuck, I want to be able to re-assign it to a new agent without hitting 'already exists' errors, so I can keep making progress."
Before I proceed with the full four forces analysis and journey mapping — do these four jobs capture what you're thinking about, or are there other angles? For example:
Are you also thinking about worktree cleanup after accept (currently left for review — when does that get cleaned)?
Is multi-server (horizontal scaling) a concern, or is this single-process for now?
Any specific pain you've hit that triggered this question (e.g., the 800 orphaned Claude processes from observation #28769)?
Your input will shape which jobs get priority and how deep we go on each.
User
/context
context
User
no, these capture it
Assistant
Good. Let me complete the analysis.
Job Dimensions
Job
Functional
Emotional
Social
J1: Crash Recovery
Detect & clean orphaned worktrees, sessions, handles on startup
Confidence the system self-heals
Trust from team that platform is production-grade
J2: Graceful Shutdown
SIGTERM handler aborts active sessions, flushes DB, closes streams
Peace of mind during deploys
No "who left this mess" post-deploy
J3: Leak Prevention
Every termination path converges to single cleanup routine
No anxiety about "what if" edge cases
System reputation for reliability
J4: Re-assignability
Clear stale locks so tasks can be re-spawned
Unblocked flow, no frustration
Users see agents as dependable workers
Four Forces Analysis
J1: Crash Recovery
Force
Analysis
Push
Server crash leaves orphaned .brain/worktrees/agent-*, stale agent_session records with no ended_at, and git worktree add fails on next spawn attempt
Pull
Startup scan finds orphans → marks sessions as error → removes worktrees → system ready in seconds
Anxiety
False positive cleanup could delete an active worktree on a different process; race conditions during concurrent startup
Habit
Currently: manual git worktree remove + DB update. Must shift to: trust the startup scanner
J2: Graceful Shutdown
Force
Analysis
Push
SIGTERM kills process mid-session → ended_at never set, task stuck in in_progress, no observation logged
Pull
Signal handler iterates active handles, aborts each, awaits DB flush, then exits cleanly
User
/context
context
Assistant· <synthetic>
No response requested.
User
status of task should also go from "in_progress" to "pending_human_review" or something like that
Assistant
Good catch. Right now the task goes straight from in_progress to done (accept) or back to ready (abort), with no intermediate state for "agent finished, awaiting human review."
Let me check what task statuses currently exist in the schema.
User
status of task should also go from "in_progress" to "failed" or something like that
Assistant
Right — two new terminal/intermediate states for tasks:
pending_review — agent finished work, awaiting human review of the diff
failed — agent errored out or was aborted, task needs attention
Let me check the current task status definitions in the schema.
Assistant
Good — now I see the full picture. Current task statuses:
code
ASSERT $value IN ["open", "todo", "ready", "in_progress", "blocked", "done", "completed"]
Updated US-1 acceptance criteria to reflect two new task status transitions:
pending_review — agent finished its work, diff exists in worktree, awaiting human accept/reject
failed — agent errored, stalled, or was aborted; needs human attention before re-assignment
Mapping to cleanupSession() outcomes:
Outcome
orchestrator_status
Task status
Agent completed normally
completed
pending_review
User accepts diff
completed
done
User rejects diff
completed
ready
Agent error / SDK exception
error
failed
Stall timeout
aborted
failed
User abort
aborted
failed
Crash recovery (startup scan)
error
failed
This also means the ASSERT constraint in the migration needs updating to include "pending_review" and "failed".
I'll update the user stories accordingly:
US-1 updated AC (added):
gherkin
Given an agent session completes normally (SDK stream ends without error)
When cleanupSession(sessionId, "completed") is called
Then task.status transitions from "in_progress" to "pending_review"
And the worktree is preserved for human review
Given an agent session errors or is aborted
When cleanupSession(sessionId, "error"|"aborted") is called
Then task.status transitions from "in_progress" to "failed"
And the worktree is removed
US-1 accept flow updated:
gherkin
Given a task is in "pending_review" status
When the user accepts the session
Then task.status transitions to "done"
Given a task is in "pending_review" status
When the user rejects the session
Then task.status transitions to "ready"
And the worktree is removed
Does this capture what you had in mind, or do you want failed to behave differently (e.g., keep worktree for debugging)?
User
/context
context
User
depends on the failure. if its unrecoverable, such as a programming bug, then it should be reset
Assistant
Good distinction. So failed splits into two behaviors based on recoverability:
Failure Type
Example
Worktree
Task Status
Unrecoverable
Programming bug, SDK crash, spawn failure
Removed
ready (immediate reset, re-assignable)
Recoverable
Stall timeout, user abort
Preserved
failed (human decides: retry, inspect, or reset)
Rationale: an unrecoverable failure means the agent's work product is useless — no point keeping the worktree or blocking re-assignment. A recoverable failure might have partial progress worth inspecting.
Updated mapping:
Outcome
orchestrator_status
Task status
Worktree
Agent completed normally
completed
pending_review
Preserved
User accepts diff
completed
done
Preserved
User rejects diff
completed
ready
Removed
Stall timeout
aborted
failed
Preserved
User abort
aborted
failed
Preserved
SDK error / unhandled exception
error
ready
Removed
Spawn failure
error
ready
Removed
Crash recovery (startup scan)
error
ready
Removed
failed → user actions:
Retry → reset to ready, remove worktree
Inspect → view worktree diff, then accept (done) or reject (ready)
So failed is essentially a "paused, needs attention" state — similar to pending_review but for unhappy paths.
Does this feel right? Or should user abort also go straight to ready since the user explicitly chose to stop?
Every resource created during delegation must be addressed:
Resource
Cleanup Action
Idempotent?
Agent process
handle.abort()
✓ (AbortController)
Handle registry
handleRegistry.delete(sessionId)
✓ (Map.delete)
Stall detector
bridge.stop() → clearInterval
✓ (already has stopped flag)
SSE stream
cleanupStream(streamId)
✓ (already idempotent)
DB session
endAgentSession() → set ended_at
✓ (UPDATE is idempotent)
DB task status
Reset to ready (abort) or done (accept)
✓
Git worktree
removeWorktree()
✓ (ignores exit codes)
Git branch
git branch -D
✓ (in removeWorktree)
Emotional Arc
code
Crash/Error occurs Startup scan runs Resources cleaned Task re-assignable
😰 ──────────→ 😐 ──────────────→ 😌 ──────────────→ 😊
"what broke?" "system is checking" "all clear" "back to work"
Phase 3: Requirements
User Stories
US-1: Idempotent Session Cleanup (enables all others)
As the orchestrator, when a session ends by any path, I want a single cleanupSession(sessionId, outcome) function that idempotently cleans all resources, so cleanup logic isn't duplicated across 4+ code paths.
Traces to: J3
Acceptance Criteria:
gherkin
Given a session with all resources created (handle, worktree, DB record, SSE stream)
When cleanupSession(sessionId, "aborted") is called
Then the agent process is aborted
And the handle registry entry is removed
And the stall detector is stopped
And the SSE stream is cleaned up
And the DB session has ended_at set
And the worktree and branch are removed
Given cleanupSession has already run for a session
When cleanupSession is called again for the same session
Then no errors are thrown
And no side effects occur
US-2: Startup Recovery Scan
As an operator, when the server starts, I want it to scan for orphaned agent sessions and worktrees from a previous crash and clean them up automatically, so I don't need manual intervention after unclean shutdowns.
Traces to: J1
Acceptance Criteria:
gherkin
Given an agent_session record with ended_at IS NULL exists in the database
And the corresponding worktree exists on disk
When the server starts
Then the session is marked as ended with status "error"
And an observation is created noting the orphaned session
And the worktree and branch are removed
And the task status is reset to "ready"
Given orphaned git worktrees exist matching pattern agent-*
But no corresponding agent_session record exists
When the server starts
Then the orphaned worktrees are removed
And orphaned branches are deleted
US-3: Graceful Shutdown
As an operator, when I send SIGTERM to the server, I want all active agent sessions to be cleanly aborted with DB state flushed before the process exits, so deploys don't leave inconsistent state.
Traces to: J2
Acceptance Criteria:
gherkin
Given 2 active agent sessions exist
When the server receives SIGTERM
Then both sessions are aborted via cleanupSession
And both agent_session records have ended_at set
And the process exits with code 0 within 10 seconds
Given an active session's abort hangs
When the graceful shutdown timeout (10s) expires
Then the process force-exits with code 1
And a warning is logged
US-4: Defensive Re-assignment Guard
As a user, when I try to assign a task that has a stale "active" handle from a previous crash, I want the system to detect the inconsistency and clear it automatically, so I can re-assign without restarting the server.
Traces to: J4
Acceptance Criteria:
gherkin
Given a task has a handle in handleRegistry
But the corresponding agent_session in DB has status "error" or "aborted"
When a new session is created for that task
Then the stale handle is cleared
And the new session proceeds normally
Given a task has a legitimately active handle and session
When a new session is created for that task
Then the request is rejected with "AGENT_ALREADY_ACTIVE"
Implementation Order & Dependencies
code
US-1 (cleanupSession)
↓
├──→ US-2 (startup scan) — calls cleanupSession per orphan
├──→ US-3 (graceful shutdown) — calls cleanupSession per active
└──→ US-4 (defensive guard) — calls cleanupSession for stale
US-1 is the keystone — the other three are consumers of it.
Shall I proceed to the DESIGN wave, or do you want to adjust any of these stories/criteria first?