> 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/sessions/phase03-session03-subagent-lineage-and-mission-graph-runtime/spec.md).

# Session Specification

**Session ID**: `phase03-session03-subagent-lineage-and-mission-graph-runtime` **Phase**: 03 - Agent Orchestration **Status**: Not Started **Created**: 2026-05-29 **Package**: Cross-cutting (`packages/protocol`, `apps/hooks`, `apps/server`) **Package Stack**: TypeScript protocol contracts, JavaScript Claude Code hooks, Express routes, in-memory server managers, WebSocket events, Vitest, Node test runners

***

## 1. Session Overview

This session promotes subagent lifecycle telemetry from bounded opaque mission events into a typed local mission graph. It starts in `packages/protocol` with lineage domain types, ingest payload contracts, mission relationship fields, and WebSocket update frames, then wires the approved behavior through `apps/hooks` and `apps/server`.

The runtime goal is parent-child mission lineage where current Claude Code hook metadata supports it. Subagent spawn and completion payloads should create or update local graph state, preserve current opaque compatibility where metadata is missing, and degrade safely for malformed, duplicate, or oversized identifiers.

This work is next because `phase03-session01-orchestration-requirements-and-safety-baseline` approved the lineage semantics and `phase03-session02-task-queue-and-agent-template-contracts` completed the protocol/server orchestration foundation. Sessions 04 through 06 depend on typed lineage before guarded action, web cockpit, and CLI diagnostic surfaces can represent subagent relationships honestly.

***

## 2. Objectives

1. Define protocol-owned subagent lineage and mission graph contracts with explicit states, safe identifier bounds, and degraded-data behavior.
2. Update hook payload shaping to send only bounded subagent metadata supported by current Claude Code hook input.
3. Implement server-side mission graph state and parent-child mission relationships without spawning, stopping, or remotely controlling subagents.
4. Emit compact WebSocket lineage updates and preserve replay, archive, and export redaction for lineage-related fields.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase03-session01-orchestration-requirements-and-safety-baseline` - provides the Phase 03 matrix, lineage safety boundary, and deferred behavior map.
* [x] `phase03-session02-task-queue-and-agent-template-contracts` - provides the protocol-first orchestration pattern, local server route discipline, and WebSocket update conventions.
* [x] `phase01-session07-runtime-contract-documentation` - provides the current REST, WebSocket, hook ingest, opaque mission event, and privacy baselines.

### Required Tools/Knowledge

* Node 20+, npm workspaces, TypeScript, JavaScript hook handlers, Express 4, `ws`, Biome, and Vitest.
* Existing protocol files in `packages/protocol/src/`, especially `ingest.ts`, `events.ts`, `missions.ts`, and `index.ts`.
* Existing hook handlers in `apps/hooks/src/factionos-subagent-spawn.js`, `apps/hooks/src/factionos-subagent-complete.js`, and shared helpers in `apps/hooks/src/_lib.js`.
* Existing server ingest and mission patterns in `apps/server/src/lib/eventIngest.ts`, `apps/server/src/routes/event.ts`, `apps/server/src/managers/missionManager.ts`, `apps/server/src/lib/sessionPrivacy.ts`, and current route tests.

### Environment Requirements

* No hosted service credentials are required.
* Local server auth, CORS, Origin, rate-limit, body-size, loopback defaults, and current hook timeout behavior must remain unchanged.
* Historical `EXAMPLES/` files remain evidence only and must not be copied into runtime code, docs, fixtures, or lineage defaults.

***

## 4. Scope

### In Scope (MVP)

* Maintainers can share subagent lineage state through protocol types - define subagent spawn, completion, parent mission links, graph snapshots, degraded states, and WebSocket update payloads.
* Hook handlers can send bounded subagent metadata where current Claude Code hook data supports it - avoid transcript paths, raw prompts, command bodies, terminal output, tokens, and broad absolute paths.
* The local server can preserve parent-child mission relationships - link child subagent activity to a parent mission when IDs are available and keep deterministic degraded state when they are not.
* Browser or future clients can receive lineage update frames - emit compact IDs, states, timestamps, counts, and safe summaries only.
* Replay, archive, export, and diagnostics can retain the existing redaction posture for new lineage fields.
* Implementers can verify typed lineage behavior with focused protocol, hook, server, export, and WebSocket tests.

### Out of Scope (Deferred)

* Actually spawning, resuming, stopping, forking, or handing off subagents from FactionOS controls - *Reason: Session 04 owns guarded local action runtime and explicit permission boundaries.*
* Web cockpit lineage visualization - *Reason: Session 05 consumes runtime lineage frames after this session ships them.*
* CLI lineage diagnostics and local recovery commands - *Reason: Session 06 owns diagnostics and recovery after state exists.*
* Cross-user lineage, War Room room sync, hosted graph persistence, public graph sharing, Docker isolation, or remote execution - *Reason: later phases require separate trust, authorization, and validation models.*
* Full transcript mining or raw transcript-path ingestion - *Reason: transcript paths and transcript contents are sensitive local developer data.*

***

## 5. Technical Approach

### Architecture

Protocol leads the change. Add lineage domain types in `packages/protocol`, extend mission and ingest contracts with optional backward-compatible lineage fields, and add compact WebSocket frame types before server or hook behavior consumes them.

Hooks continue to stay silent, timeout-bounded, and dependency-light. The subagent spawn and completion handlers should send safe identifiers and bounded metadata only, using shared helper behavior for malformed transcript paths and identifier length limits. Missing identifiers must not fail hook execution.

The server should add a small in-memory mission graph manager and connect it to the existing `/event` ingest route. Subagent spawn and completion should become typed handling paths when enough data exists, while unsupported or incomplete payloads still produce bounded opaque `mission_event` frames or explicit degraded lineage updates. Existing auth, CORS, Origin, rate-limit, body-size, and export privacy defaults stay unchanged.

### Design Patterns

* Protocol-first contracts: lineage types are defined in `packages/protocol` before server and hook code relies on them.
* Bounded local manager: mission graph state is in-memory, deterministic, capped, and local-only.
* Compatibility-preserving ingest: typed lineage is added only for approved subagent cases while unknown named events and unsupported variants retain current opaque behavior.
* Boundary-specific redaction: archive, export, replay, WebSocket, hook log, and diagnostics paths redact according to their current boundary.

### Technology Stack

* TypeScript 5.9 in `packages/protocol` and `apps/server`.
* JavaScript ESM hook handlers in `apps/hooks`.
* Express 4 route handling and existing server middleware.
* WebSocket broadcasting through `apps/server/src/ws/broadcaster.ts`.
* Vitest and Node-based package tests.

***

## 6. Deliverables

### Files to Create

| File                                       | Purpose                                                                        | Est. Lines |
| ------------------------------------------ | ------------------------------------------------------------------------------ | ---------- |
| `packages/protocol/src/lineage.ts`         | Subagent lineage, mission graph, state, event, and degraded-data contracts     | \~180      |
| `apps/server/src/managers/missionGraph.ts` | Bounded in-memory mission graph manager for parent-child mission relationships | \~220      |
| `packages/protocol/tests/lineage.test.ts`  | Protocol contract tests for lineage types and WebSocket discriminants          | \~140      |

### Files to Modify

| File                                                                                                      | Changes                                                                          | Est. Lines |
| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/index.ts`                                                                          | Export lineage contracts                                                         | \~2        |
| `packages/protocol/src/ingest.ts`                                                                         | Promote subagent spawn and completion metadata into typed ingest contracts       | \~70       |
| `packages/protocol/src/missions.ts`                                                                       | Add optional parent mission and subagent lineage references to mission state     | \~40       |
| `packages/protocol/src/events.ts`                                                                         | Add lineage update and mission graph update WebSocket frames                     | \~70       |
| `apps/hooks/src/_lib.js`                                                                                  | Harden subagent ID detection and safe identifier truncation                      | \~40       |
| `apps/hooks/src/factionos-subagent-spawn.js`                                                              | Send bounded lineage metadata without transcript paths or raw prompts            | \~45       |
| `apps/hooks/src/factionos-subagent-complete.js`                                                           | Send bounded completion metadata and degraded missing-ID behavior                | \~35       |
| `apps/hooks/tests/hookPayloads.test.js`                                                                   | Cover typed lineage payload fields and bounds                                    | \~45       |
| `apps/server/src/lib/eventIngest.ts`                                                                      | Normalize typed subagent spawn and completion ingest with safe fallback          | \~120      |
| `apps/server/src/managers/missionManager.ts`                                                              | Preserve mission parent-child links and deterministic child ordering             | \~90       |
| `apps/server/src/routes/event.ts`                                                                         | Wire typed lineage handling, graph updates, and opaque fallback paths            | \~170      |
| `apps/server/src/server.ts`                                                                               | Instantiate and pass the mission graph manager to ingest routes                  | \~20       |
| `apps/server/src/lib/sessionPrivacy.ts`                                                                   | Redact lineage fields for archive, export, replay, and diagnostics boundaries    | \~35       |
| `apps/server/src/lib/exportSession.ts`                                                                    | Include safe lineage fields in export output without sensitive metadata          | \~45       |
| `apps/server/tests/eventIngest.test.ts`                                                                   | Cover lineage spawn, completion, missing IDs, malformed IDs, and duplicates      | \~180      |
| `apps/server/tests/exportSession.test.ts`                                                                 | Cover lineage export and redaction behavior                                      | \~80       |
| `docs/api/README_api.md`                                                                                  | Document typed local lineage status and deferred controls                        | \~35       |
| `docs/api/event-api-hook-contracts.md`                                                                    | Update hook ingest mapping from opaque subagent events to typed lineage behavior | \~60       |
| `.spec_system/specs/phase03-session03-subagent-lineage-and-mission-graph-runtime/implementation-notes.md` | Implementation log, commands run, and validation notes                           | \~100      |
| `.spec_system/specs/phase03-session03-subagent-lineage-and-mission-graph-runtime/security-compliance.md`  | Session privacy, security, and GDPR posture                                      | \~90       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Subagent spawn and completion protocol types are exported and covered by focused tests.
* [ ] Hook handlers emit bounded lineage metadata when current hook data provides usable identifiers.
* [ ] Server ingest produces typed lineage updates when identifiers are available.
* [ ] Missing, malformed, duplicate, or oversized lineage metadata degrades without crashes or raw sensitive output.
* [ ] Existing opaque compatibility behavior remains available for unsupported named events and unsupported subagent variants.
* [ ] WebSocket lineage frames expose only compact local graph state and safe summaries.

### Testing Requirements

* [ ] `npm --workspace packages/protocol run typecheck` passes.
* [ ] `npm --workspace apps/server run typecheck` passes.
* [ ] Focused protocol, hooks, server ingest, export, and WebSocket tests pass.
* [ ] Manual validation confirms no lineage response or frame exposes raw prompts, transcript paths, command bodies, tokens, terminal output, or broad absolute paths.

### Non-Functional Requirements

* [ ] Lineage graph state remains local, in-memory, bounded, and non-executing.
* [ ] Existing auth, CORS, Origin, rate-limit, body-size, loopback, and hook timeout defaults are unchanged.
* [ ] Graph snapshots and list-like responses use bounded limits and deterministic ordering.
* [ ] Error and degraded-state outputs remain compact and do not leak sensitive developer data.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.

***

## 8. Implementation Notes

### Key Considerations

* Session 03 is a lineage runtime session, not a subagent control session.
* Current hook data can support safe IDs and bounded descriptions, but transcript paths and transcript contents must not be surfaced.
* The existing `mission_event` fallback is still valuable for unsupported or incomplete payloads and should not be removed.
* Mission graph state should be easy to include in later CLI diagnostics, browser controls, trusted reset, and erasure workflows.

### Potential Challenges

* ID quality: transcript-derived subagent IDs may be absent, malformed, or duplicated. Mitigation: validate and truncate IDs, then emit degraded state or preserve opaque fallback.
* Mission mapping: a parent mission may not exist when a subagent event arrives. Mitigation: link to the active hero mission when available and otherwise record a bounded unknown-parent state.
* Privacy drift: lineage could accidentally expose prompts or transcript paths. Mitigation: keep hook payloads bounded, update session privacy tests, and avoid copying raw historical fixtures.
* Contract drift: server and hooks could invent local-only lineage shapes. Mitigation: import and use protocol-owned types and discriminants.

### Relevant Considerations

* \[P01] **Redaction is boundary-specific**: lineage, export, replay, adapter, archive, hook log, and future external-transfer paths must reuse the existing privacy posture before data leaves a local boundary.
* \[P01-apps/server] **Local server boundary must stay conservative**: typed lineage work inherits loopback, auth, CORS, Origin, rate-limit, body-size, validation, and explicit failure defaults.
* \[P01-packages/protocol] **Protocol leads cross-package work**: lineage shapes must be protocol-owned before server, hooks, CLI, or web packages consume them.
* \[P01] **Bounded opaque compatibility**: unsupported or incomplete subagent payloads are safest as bounded opaque frames or degraded lineage state, not broad historical parsers.
* \[P01-apps/hooks+apps/cli] **Lifecycle state is local and file-based**: hook lineage additions must keep quiet failure, timeout bounds, and crash recovery behavior intact.
* \[P01] **Unified erasure still missing**: new local lineage state should remain bounded and resettable by later trusted erasure work.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Subagent events could arrive out of order, duplicated, or without usable IDs.
* New WebSocket and export fields could expose transcript-derived identifiers, raw prompts, paths, or command previews.
* Typed lineage handling could accidentally break current opaque mission event compatibility for unsupported hook variants.

***

## 9. Testing Strategy

### Unit Tests

* Protocol tests for lineage states, degraded reasons, graph snapshot shapes, optional mission relationship fields, and WebSocket discriminants.
* Hook payload fixture tests for bounded spawn and completion fields, absent transcript paths, malformed transcript paths, and safe ID truncation.
* Mission graph manager tests through server ingest coverage for duplicate events, deterministic ordering, and degraded parent or child IDs.

### Integration Tests

* Server `/event` tests for typed subagent spawn and completion, opaque fallback behavior, missing heroes, missing missions, oversized metadata, malformed IDs, and WebSocket frame emission.
* Export and archive privacy tests for new lineage fields and nested graph payloads.

### Manual Testing

* Fire representative subagent spawn and completion payloads against a local server and inspect emitted events for compact lineage frames.
* Confirm current non-subagent hook flows still produce the same mission, tool, input, permission, and opaque events as before.

### Edge Cases

* Spawn arrives before a parent mission exists.
* Completion arrives before spawn.
* Subagent ID is absent, malformed, duplicated, or longer than the configured bound.
* Parent subagent ID exists but cannot be resolved to a mission.
* Payload contains transcript-like paths, prompts, tokens, URLs, or command previews that must be redacted or omitted.

***

## 10. Dependencies

### External Libraries

* No new runtime dependency is expected.

### Internal Modules

* `packages/protocol/src/ingest.ts`, `events.ts`, `missions.ts`, and new `lineage.ts`.
* `apps/hooks/src/_lib.js`, `factionos-subagent-spawn.js`, and `factionos-subagent-complete.js`.
* `apps/server/src/lib/eventIngest.ts`, `routes/event.ts`, `managers/missionManager.ts`, new `managers/missionGraph.ts`, `lib/sessionPrivacy.ts`, and `lib/exportSession.ts`.

### Other Sessions

* **Depends on**: `phase03-session01-orchestration-requirements-and-safety-baseline`, `phase03-session02-task-queue-and-agent-template-contracts`.
* **Depended by**: `phase03-session04-guarded-local-action-runtime`, `phase03-session05-web-orchestration-cockpit-controls`, `phase03-session06-cli-diagnostics-and-recovery-controls`.

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# 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/sessions/phase03-session03-subagent-lineage-and-mission-graph-runtime/spec.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.
