> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/phases/phase_18/session_04_idle_lifecycle_engine_parity.md).

# Session 04: Idle Lifecycle Engine Parity

**Session ID**: `phase18-session04-idle-lifecycle-engine-parity` **Package**: apps/server **Status**: Not Started **Estimated Tasks**: \~12-25 **Estimated Duration**: 2-4 hours

***

## Objective

Wire automatic idle-suggestion generation to hero-idle status transitions with transcript context, modified-file awareness, cooldown, in-flight guards, timeouts, and deterministic fallbacks, storing typed results in the SuggestionManager.

***

## Scope

### In Scope (MVP)

* Trigger on hero status transition to idle (not mission-complete callbacks), invoking generation for the hero's session
* Transcript-aware context: read recent session messages (about 30) from the current session/message infrastructure, with an in-memory message fallback when no transcript source exists for the provider
* Modified-file extraction from transcript/context for prompt grounding
* In-flight session guard and a 60-second cooldown so repeated idle transitions do not stack generations
* Generation timeout (about 18 seconds) with cleanup of pending work; no orphaned requests after shutdown
* Pattern-based fallback suggestions when the LLM path is unavailable, fails, or returns nothing; fallback output must be schema-valid typed suggestions (fixing the current fallback-shape mismatch noted in the audit)
* Existing guardrails preserved: forbidden generic-suggestion filtering, max 3 suggestions, `llmPrivacy` rules, and two-level provider opt-in
* Results stored through SuggestionManager as typed suggestions (title, category, priority retained); `POST /llm/idle-suggestion` kept working against the new engine
* Unit tests with fixture LLM responses: trigger, cooldown, in-flight, timeout, fallback, and parsing paths

### Out of Scope

* Session summaries and follow-ups (Session 05)
* Web rendering of typed cards (Session 09)

***

## Prerequisites

* [ ] Sessions 02-03 complete (manager and snapshot emission available)
* [ ] Hero status transition source identified in current server code

***

## Deliverables

1. Hero-idle lifecycle trigger wired to the upgraded idle engine
2. Transcript/context builder with modified-file extraction
3. Cooldown, in-flight, timeout, and cleanup behavior
4. Schema-valid deterministic fallback path and tests

***

## Success Criteria

* [ ] A hero going idle produces typed suggestions in the snapshot without any manual route call
* [ ] Cooldown and in-flight guards provably suppress duplicate generation
* [ ] LLM failure or absence still yields valid fallback suggestions
* [ ] Server test suite passes with new coverage included

***

## Historical Evidence (EXAMPLES References)

Preserved from the 2026-06-07 parity audit (full audit in `PRD_phase_18.md` Appendix A). Evidence only; never import, copy, or transform historical code.

* `EXAMPLES/package-0.4.1/server/dist/idleSuggestionEngine.js:1` - the engine evidence:
  * `generateSuggestions(sessionId, heroId, force=true, spawnFn, inMemoryMessages)` with cooldown and in-flight guard.
  * Fields `inFlightSessions`, `lastGenerationTime`, `COOLDOWN_MS=6e4` (60 seconds).
  * Fields `activeHaikuProcesses`, `CLAUDE_TIMEOUT_MS=18e3` (18 seconds), with process cleanup in `cleanup()`.
  * `readTranscript` / `buildContext` for transcript-aware context; a top-level modified-file extraction regex feeds `buildContext`.
  * `generateLlmSuggestions` / `parseSuggestions` for guardrails (concrete next-step work only, no generic "run tests/review code/improve performance", max 3 suggestions).
  * `analyzeContextForSuggestion` pattern-based fallback suggestions and the fallback branch inside `generateSuggestions`.
  * `parseCombinedResponse` storing `followUps` (handed to Session 05).
* `EXAMPLES/package-0.4.1/server/dist/index.js:1` - trigger wiring: the `s==="idle"&&o.sessionId` branch fires generation on a hero status transition to `"idle"` (not a mission-complete callback). The `spawnFn` is executor-aware (`mr(executorType, workingDir)`); for `opencode`/`cursor` executors an in-memory message slice (`getMessages(sessionId, 30)`) serves as the transcript fallback.
* `EXAMPLES/package-0.4.1/server/dist/transcriptReader.js:1` - `readTranscript(sessionId, _, 30)`; `transcriptMiner.js:1` adjacent.
* Engine runtime evidence (informs timeout/turn budgets only, not the implementation): Haiku with `--max-turns 1`, spawned as `claude -p` with env `AGENTCRAFT_HAIKU_SUBPROCESS=1` and `CLAUDECODE` deleted from the child env. Current work must use `llmClient` instead.
* Findings: `EXAMPLES/findings/architecture.md:261` (idle lifecycle); `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:9` (automatic trigger); `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:13` and `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:28` (guardrails, max 3); `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:15` (transcript context); `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:17` (modified files); `EXAMPLES/findings/llm-prompts/idle-suggestion-engine.md:42` (throttling).

## Current-Code Touchpoints (Audit Snapshot 2026-06-07)

* `apps/server/src/routes/llm.ts:158` - `POST /llm/idle-suggestion`; `:159` requires caller-provided `lastUserTask`/`recentActivity`; `:172` returns strings only, so `title`, `category`, and `priority` are dropped.
* `apps/server/src/llm/engines/idleSuggestionEngine.ts:5` forbidden patterns; `:30` cap of 3; `:35` request-body-only prompt; `:43` `complete()` without timeout or cleanup; `:53` `safeParseArray` rejects the canned `llmClient` fallback object shape, so the fallback path currently yields no suggestions (bug to fix this session).
* `apps/server/src/llm/prompts/idle-suggestion-engine.md:1` and `:4` - prompt doc describes mission-complete triggering, throttling, card clicks, and keyboard shortcuts not implemented in runtime; reconcile the doc with shipped behavior (closeout check in Session 11).
* `apps/server/src/managers/mockEventGenerator.ts:198` - the only automatic-looking idle-suggestion source today is mock data.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/phases/phase_18/session_04_idle_lifecycle_engine_parity.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
