---
name: fluent-session
description: Track session changes and export structured audit trails. Maintains a running change log with text summaries and machine-readable JSON exports for CI/CD pipelines and compliance. Triggers on "session summary", "what did we change", "change summary", "show changes", "export audit", "session audit", "audit trail", "compliance report".
user-invocable: true
allowed-tools: Bash, Read, Write, Glob, Grep
argument-hint: [show|reset|export [--format json|jsonl] [--output <path>] [--include-readonly]]
cursor-tier: auto
---

# Session Change Tracking & Audit Export

Track ALL changes made during a session — both code modifications and Fluent Commerce environment mutations — and produce structured output on demand: human-readable text summaries or machine-readable JSON audit trails.

## Modes

| Mode | Invocation | Output |
|------|-----------|--------|
| **Show** (default) | `/fluent-session show` | Markdown tables in terminal |
| **Export JSON** | `/fluent-session export --format json` | `accounts/<PROFILE>/sessions/<sessionId>.audit.json` |
| **Export JSONL** | `/fluent-session export --format jsonl` | One JSON object per line (`.audit.jsonl`) |
| **Reset** | `/fluent-session reset` | Clears running log (e.g., when switching accounts mid-session) |

## Parameters

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `--format` | No | `json` | Export format: `json` (single document) or `jsonl` (one record per line) |
| `--output` | No | Auto-generated path | Output file path. Default: `accounts/<PROFILE>/sessions/<sessionId>.audit.json` |
| `--include-readonly` | No | `false` | Include read-only operations (queries, downloads, introspection) |
| `--profile` | No | Active profile | Profile context for the audit |

## Behaviour

This is a **cross-cutting concern**, not a phase-specific skill. It applies alongside every other skill. This skill owns the tracking protocol — it defines what to track, when to present, and all output formats (text and JSON).

### What to Track

**Fluent environment changes (live account):**
- GraphQL mutations executed (entity type, ref/id, fields changed)
- Workflows deployed or uploaded (name, version, retailer)
- Settings created or updated (key, context, value summary)
- Events sent via `event.send` (name, entity type, entity ref, sync/async, outcome)
- Modules deployed via CLI (name, version, retailer)
- Batch jobs created and sent (job name, entity type, record count, outcome)
- Entities created or updated (locations, networks, catalogues, carriers, users, orders, fulfilments, inventory positions, products, virtual catalogues, etc.)

**Code changes (local workspace):**
- Files created, modified, or deleted (path + brief description)
- Workflow JSON edits (ruleset added/removed, trigger changed, state added)
- Rule classes scaffolded or modified
- Feature assets created (screenshots, recordings, GIFs saved to `features/<slug>/assets/`)
- Git commits made (hash, message, repo)
- Git pushes (repo, branch, remote)

**Skill invocations (agent decision trail):**
- Skill name invoked (e.g., `/fluent-rule-scaffold`, `/fluent-build`)
- Invocation timestamp
- Key arguments passed (profile, retailer, entity type, module name — NOT full file contents)
- Outcome: `completed` | `failed` | `skipped` (with reason)
- Downstream skill recommended (from Handoff section, if any)

**MCP tool calls (API-level operations):**
- Tool name (e.g., `event.send`, `graphql.query`, `entity.create`, `workflow.upload`)
- Entity type and ref targeted
- Outcome: `ok: true/false`
- Whether it was a read (query/list/get) or write (mutation/send/create/update/deploy)
- Read-only tool calls are tracked when `--include-readonly` is specified; write tool calls are always tracked

**Decision trail (why the agent chose a path):**
- Decision timestamp + step id
- Trigger (user request, workflow gate, error recovery, or handoff)
- Options considered (2-4 short labels)
- Selected option + rationale
- Confidence (`high` | `medium` | `low`) and assumptions list

**Read-only operations are NOT tracked as state changes** — queries, downloads, analysis, introspection, event listing, and diagnostics do not appear in Environment/Code change counts. They can still be listed under `MCP Tool Calls` when `--include-readonly` is enabled.

### When to Present

- When the user asks: "what did we change?", "summary", "show changes", "wrap up", or invokes `/fluent-session`
- Proactively before ending a session that involved significant changes (3+ write operations)
- After completing a multi-step task (e.g., build-deploy-test cycle)

## Text Summary Format (`show`)

```markdown
## Session Change Summary

**Profile:** <PROFILE> | **Account:** <account> | **Retailer:** <RETAILER_REF> (ID <N>)
**Duration:** <first change time> - <last change time>

### Environment Changes
| # | Action | Type | Ref / Key | Details |
|---|--------|------|-----------|---------|
| 1 | Created | Setting | <SETTING_KEY_1> | context=RETAILER:<RETAILER_ID>, value=https://... |
| 2 | Created | Order | <ORDER_REF_1> | type=<ORDER_SUBTYPE>, status=CREATED |
| 3 | Sent Event | <EVENT_NAME_1> | <ENTITY_TYPE>/<ORDER_REF_1> | async, SUCCESS |

### Code Changes
| # | Action | Path | Details |
|---|--------|------|---------|
| 1 | Modified | workflows/<WORKFLOW_FILE>.json | Added ruleset <RULESET_NAME> |
| 2 | Created | src/.../<RULE_CLASS>.java | New rule class + test |

### Skill Invocations
| # | Timestamp | Skill | Arguments | Outcome | Next |
|---|-----------|-------|-----------|---------|------|
| 1 | 09:00 | /fluent-rule-scaffold | <RULE_CLASS>, <ENTITY_TYPE> | completed | /fluent-build |

### Decision Trail
| # | Timestamp | Trigger | Options | Selected | Rationale | Confidence |
|---|-----------|---------|---------|----------|-----------|------------|
| 1 | 08:58 | User asks for deployment readiness | Build only, Build+Checklist | Build+Checklist | Prevent unsafe deploy without gate evidence | high |

### MCP Tool Calls
| # | Timestamp | Tool | Target | Write? | Outcome |
|---|-----------|------|--------|--------|---------|
| 1 | 09:12 | setting.upsert | <SETTING_KEY_2> | Yes | ok |

### Totals
| Category | Count |
|----------|-------|
| GraphQL mutations | N |
| Events sent | N |
| Settings changed | N |
| Workflows deployed | N |
| Modules deployed | N |
| Batch jobs | N |
| Files modified | N |
| Git commits | N |
| Skills invoked | N |
| MCP tool calls (write) | N |
| Decision trail entries | N |

### Irreversible Actions
> List any destructive or hard-to-reverse changes here (entity deletions, workflow version overwrites, forced re-deploys). Flag prominently so the user is aware.
```

## JSON Audit Export (`export`)

For structured JSON output, see `AUDIT_SCHEMA.md` in this skill directory for the complete schema, target object shapes, rollback commands, redaction rules, and a full example.

The JSON export is designed for consumption by CI/CD pipelines, audit systems, Jira integrations, Confluence deployment records, and feedback loop scope-completion measurement.

### Export Steps

```
1. DURING THE SESSION:
   - Record write changes into changes[]
   - Record skill lifecycle into skillInvocations[]
   - Record MCP/CLI tool usage into toolCalls[]
   - Record branch choices into decisionTrail[]
   - Read-only tool calls are included only when --include-readonly is enabled

2. ON /fluent-session export:
   a. Compile changes[], skillInvocations[], toolCalls[], and decisionTrail[]
   b. Populate compliance metadata (scope, traceability, checklist) when available
   c. Assign stable 1-based sequence values per array
   d. Compute summary counts

3. WRITE to output path:
   Default: accounts/<PROFILE>/sessions/<sessionId>.audit.json
   Or: user-specified --output path

4. REPORT:
   Print output file path + aggregate counts
```

## Centralized Instrumentation Contract

All skills should emit tracking records through one shared capture path:

```
track.skillStart(skillName, argsSanitized)
track.toolCall(toolName, target, write, outcome, readonly)
track.decision(trigger, options, selected, rationale, confidence, assumptions)
track.change(category, action, target, details, reversible, outcome)
track.skillEnd(skillName, outcome, nextSkill)
```

Rules:
- Do not duplicate logs in each skill; use the shared tracker.
- Keep arguments and payloads sanitized (no secrets, no large blobs).
- Preserve chronological order across all categories.

### Tracking Protocol

1. **At skill entry:** Append a `skillInvocation.start` record with skill name + sanitized arguments.
2. **As tool calls execute:** Append `toolCall` records (write always, read only when `--include-readonly` is enabled).
3. **At decision points:** Append `decisionTrail` records whenever the agent chooses between multiple valid paths.
4. **On write operations:** Append state changes immediately. Do not reconstruct later.
5. **At skill exit:** Mark invocation outcome (`completed`/`failed`/`skipped`) and recommended next skill.
6. **On `/fluent-session show`:** Present the full text table.
7. **On `/fluent-session export`:** Write the JSON artifact (see AUDIT_SCHEMA.md).
8. **On `/fluent-session reset`:** Clear the running log.
9. **Group by account/retailer** if the session spans multiple profiles or retailers.
10. **Include outcome** where known (SUCCESS, FAILED, NO_MATCH) — especially for events.
11. **For mutations**, note the key fields changed rather than full payloads.
12. **For workflow deploys**, note the version number deployed.

## Integration with Other Skills

Every skill that performs write operations should contribute to this log:

| Skill | Tracked actions |
|-------|----------------|
| `fluent-workflow-builder` | Workflow JSON edits (local file changes) |
| `fluent-build` | Version bumps, module packaging |
| `fluent-module-deploy` | Module installs to retailers |
| `fluent-workflow-deploy` | Workflow uploads to retailers |
| `fluent-settings` | Setting create/update mutations |
| `fluent-retailer-config` | Entity creation (locations, networks, catalogues, etc.) |
| `fluent-test-data` | Test entity creation |
| `fluent-e2e-test` | Events sent, entities created during test |
| `fluent-rule-scaffold` | New Java classes and module.json changes |
| `fluent-job-batch` | Batch job creation, record sends |
| `fluent-trace` | Events sent during diagnostic re-fires |
| `fluent-custom-code` | Source code edits |
| `fluent-module-scaffold` | Module skeleton creation |
| `fluent-version-manage` | Version bumps, CHANGELOG updates, git tags |
| `fluent-pre-deploy-check` | Pre-deploy gate results |
| `fluent-rollback` | Rollback operations tracked as changes |
| `fluent-feature-status` | Complementary — feature lifecycle vs session changes |

### Skill Handoff Convention

All implementation skills should end their output with a structured "Recommended Next Steps" table:

| Priority | Skill | Reason |
|----------|-------|--------|
| 1 | `/fluent-workflow-analyzer` | Validate modified workflow |
| 2 | `/fluent-pre-deploy-check` | Run pre-deployment validation |

### Error Reporting Convention

Skills should report errors using a consistent table format:

| Severity | Code | Message | Skill | Remediation |
|----------|------|---------|-------|-------------|
| CRITICAL | DEPLOY_BLOCKED | Pre-deploy check failed | /fluent-module-deploy | Run /fluent-pre-deploy-check |

## Edge Cases

- **Dry runs:** `event.send` with `dryRun: true` and `graphql.introspect` are NOT tracked (no state change).
- **Failed writes:** Track with outcome=FAILED so the user knows what was attempted.
- **Multi-retailer sessions:** Group changes under separate retailer headers. For JSON export, produce one document per profile/retailer combination.
- **No changes made:** Report "No environment or code changes were made in this session." For JSON export, output a valid document with empty `changes` array and all summary counts at 0.
- **Skill invocations with no changes:** A skill like `/fluent-workflow-analyzer` may be invoked but produce no tracked changes (read-only). It still appears in the Skill Invocations table but contributes 0 to change counts.
- **MCP tool dryRun calls:** Tool calls with `dryRun: true` are NOT tracked as writes. They appear in tool calls only if `--include-readonly` is specified.
- **No explicit branching decision occurred:** Do not force decision records. `decisionTrail` can be empty.
- **Partial sessions:** If the agent session ends abnormally, the audit captures everything tracked up to that point.
- **No scope document:** If no scope decomposition was run, set compliance fields to null/0.
- **Setting bulk upserts:** Each individual setting in a `setting.bulkUpsert` call is tracked as a separate CONFIG change record.
- **Skill invocations with no tool calls:** Pure local file analysis appears in `skillInvocations` with `toolCallsProduced: []`.
- **Tool calls outside skill context:** Direct MCP tool calls not triggered by a named skill have `skill: undefined`.
