Session Discipline

DOCTRINE

Session Discipline

Overview

The Mandatory Session Discipline Protocol ensures that every development session on the Prismatic Platform is tracked, committed continuously, and pushed to remote. No work is ever lost, no changes go untracked, and every session produces a complete audit trail from issue creation through implementation to final push. This protocol governs all development activity across the platform's 99 umbrella applications and 2.8 million lines of code.

Session Discipline addresses a class of failures that no amount of code quality enforcement can prevent: work loss due to uncommitted changes, untracked sessions that produce orphaned code, and knowledge loss when session context is not preserved. These failures are particularly insidious because they are invisible until the damage is done -- a power failure, a system crash, or simply ending a session without pushing can result in hours of lost work.

The protocol integrates with Quality Gates for commit validation, Telemetry Integration for session tracking, and the NO MERCY doctrine's enforcement infrastructure to create an unbypassable workflow discipline that protects both the developer and the platform.

Session Lifecycle

Every development session follows a mandatory three-phase lifecycle with specific requirements at each phase. The lifecycle is enforced through automated tooling and cannot be bypassed.

Phase 1: Session Initialization

RequirementDescriptionEnforcement
GitLab IssueCreate or link to existing GitLab issue for work itemsMANDATORY - session blocked without ticket
Context LoadingLoad latest session context from .claude/session-context/AUTOMATIC - loaded at session start
Branch CreationCreate feature branch from main if neededRECOMMENDED for feature work
Baseline CheckRun mix autoheal.baseline for quality baselineMANDATORY per evolution protocol
Status CheckRun mix autoevolve status --brief for platform stateMANDATORY per evolution protocol
defmodule PrismaticClaude.SessionLifecycle do
  @moduledoc """
  Manages the development session lifecycle.
  Enforces Session Discipline Protocol requirements at each phase.
  """

  use GenServer

  @type session_state :: :initialized | :active | :completing | :closed

  defstruct [
    :session_id,
    :gitlab_issue,
    :branch,
    :started_at,
    :commits: [],
    :files_modified: [],
    :state: :initialized
  ]

  @spec start_session(gitlab_issue :: String.t()) ::
    {:ok, session_id :: String.t()} | {:error, term()}
  def start_session(gitlab_issue) do
    with :ok <- validate_gitlab_issue(gitlab_issue),
         {:ok, context} <- load_latest_context(),
         {:ok, baseline} <- run_quality_baseline() do
      session_id = generate_session_id()

      {:ok, session_id}
    else
      {:error, :no_gitlab_issue} ->
        {:error, "Session BLOCKED: GitLab issue required"}

      {:error, reason} ->
        {:error, "Session initialization failed: #{reason}"}
    end
  end

  defp validate_gitlab_issue(nil), do: {:error, :no_gitlab_issue}
  defp validate_gitlab_issue(""), do: {:error, :no_gitlab_issue}
  defp validate_gitlab_issue(_issue), do: :ok

  defp load_latest_context do
    context_dir = ".claude/session-context/"

    case File.ls(context_dir) do
      {:ok, files} ->
        latest = files |> Enum.sort() |> List.last()
        {:ok, File.read!(Path.join(context_dir, latest))}

      {:error, _} ->
        {:ok, "No previous session context found"}
    end
  end

  defp run_quality_baseline do
    case System.cmd("mix", ["autoheal.baseline"], stderr_to_stdout: true) do
      {output, 0} -> {:ok, output}
      {output, _} -> {:error, "Baseline check failed: #{output}"}
    end
  end

  defp generate_session_id do
    date = Date.utc_today() |> Date.to_iso8601()
    random = :crypto.strong_rand_bytes(4) |> Base.encode16(case: :lower)
    "#{date}-#{random}"
  end
end

Phase 2: Active Development

During active development, the protocol enforces continuous commits and immediate push to remote:

RequirementDescriptionEnforcement
Atomic commitsOne logical change per commitMANDATORY - batching forbidden
Local testingRun tests before every commitMANDATORY - untested commits blocked
Immediate commitCommit as soon as tests passMANDATORY - no accumulation
Immediate pushPush to remote after each commitRECOMMENDED after each, MANDATORY at session end
Progress trackingUpdate GitLab issue with progressMANDATORY - tracked automatically
Hook complianceAll pre-commit hooks must passMANDATORY - --no-verify forbidden

Phase 3: Session Completion

RequirementDescriptionEnforcement
All commits pushedVerify no unpushed commits remainMANDATORY - session cannot close with unpushed work
Context savedSave session context to .claude/session-context/MANDATORY - preserves knowledge
GitLab updatedClose or update GitLab issue with final statusMANDATORY - tracked completion
Evolution triggeredRun mix autoheal.cycle && mix autoevolve.megaMANDATORY per evolution protocol

Commit Standards

The Session Discipline Protocol enforces strict standards for every commit to ensure traceability, atomicity, and quality.

Conventional Commits Format

All commits must follow the Conventional Commits specification:

type(scope): subject

[optional body explaining the "why"]

Co-Authored-By: Claude <noreply@anthropic.com>
TypeUsageExample
featNew featurefeat(perimeter): add NIS2 compliance checker
fixBug fix (requires regression test)fix(api): handle nil response in endpoint discovery
refactorCode restructuringrefactor(storage): extract adapter trait
testTest additions or modificationstest(perimeter): add property-based rating tests
docsDocumentation updatesdocs(claude): update session context
perfPerformance improvementperf(git-trees): optimize regex matching
choreMaintenance taskschore(deps): update Phoenix to 1.7.18
ciCI/CD changesci(gitlab): add Dialyzer stage

Atomicity Requirements

Each commit must contain exactly one logical change. The following patterns are explicitly forbidden:

Forbidden PatternCorrect Approach
Multiple features in one commitSeparate commits per feature
Fix + refactor in one commitSeparate fix commit and refactor commit
Format changes mixed with logicFormat commit, then logic commit
Test + implementation in one commitAcceptable when TDD (test-first)
Unrelated file changes groupedSeparate commits per concern

Forbidden Actions

The following actions are absolutely forbidden under the Session Discipline Protocol. Any attempt to execute these actions triggers an L4 violation escalation:

Forbidden ActionReasonEnforcement
git commit --no-verifyBypasses quality gatesL4 SUPREME REVIEW
git push --no-verifyBypasses push hooksL4 SUPREME REVIEW
git push --force to mainDestroys repository historyL4 SUPREME REVIEW
git reset --hard without confirmationDestroys uncommitted workL3 REJECTION
git checkout . without confirmationDiscards all changesL3 REJECTION
Batching multiple changes in one commitViolates atomicityL2 BLOCK
Committing without local test verificationViolates quality requirementL2 BLOCK
Working without GitLab ticketNo traceabilityL3 REJECTION
Session end without push to remoteWork loss riskL2 BLOCK
Skipping session context saveKnowledge lossL2 BLOCK

Session Context Preservation

Session context is saved to .claude/session-context/ at session end (and recommended every 30 minutes during long sessions). The context file preserves the knowledge graph of the session for future sessions to build upon.

Context File Format

# Session Context: YYYY-MM-DD Description

## Objectives
- Primary objective description
- Secondary objectives if any

## Actions Taken
1. Action with file references
2. Action with commit hashes

## Files Modified
- `path/to/file.ex` - Description of changes
- `path/to/test_file.exs` - Tests added

## Key Decisions
- Decision description with rationale
- Alternative considered and why rejected

## Deliverables
- Feature/fix delivered with description
- Tests added with coverage summary

## Next Steps
- Recommended follow-up actions
- Outstanding items for future sessions

## GitLab Issues
- #ISSUE_NUMBER - Status and summary

Context Loading

At session start, the most recent context file is loaded automatically, providing continuity across sessions:

defmodule PrismaticClaude.SessionContext do
  @moduledoc """
  Manages session context persistence and loading.
  Ensures knowledge continuity across development sessions.
  """

  @context_dir ".claude/session-context/"

  @spec save_context(session_id :: String.t(), content :: String.t()) :: :ok | {:error, term()}
  def save_context(session_id, content) do
    filename = "#{session_id}-session.md"
    path = Path.join(@context_dir, filename)

    File.mkdir_p!(@context_dir)
    File.write!(path, content)

    # Also update the LATEST_SESSION.md symlink
    latest_path = Path.join(@context_dir, "LATEST_SESSION.md")
    File.write!(latest_path, content)

    :ok
  end

  @spec load_latest_context() :: {:ok, String.t()} | {:error, :no_context}
  def load_latest_context do
    latest_path = Path.join(@context_dir, "LATEST_SESSION.md")

    case File.read(latest_path) do
      {:ok, content} -> {:ok, content}
      {:error, _} -> {:error, :no_context}
    end
  end
end

Violation Protocol

Session Discipline violations follow an escalation protocol aligned with the platform's enforcement framework:

ViolationSeverityResponseRecovery
Session without GitLab ticketL3 REJECTIONSession blocked until ticket createdCreate ticket, restart session
Unpushed commits at session endL2 BLOCKPush required before session closesExecute git push
--no-verify flag usageL4 SUPREME REVIEWImmediate escalation, audit trailReview, correction, new commit
Failed hooks bypassedL4 SUPREME REVIEWPlatform integrity investigationFull review of bypassed commits
Batch commit (multiple changes)L2 BLOCKCommit rejected, must splitgit reset --soft HEAD~1, separate commits
Missing session context saveL2 BLOCKContext must be saved before closeSave context, update LATEST_SESSION.md
Commit without local testsL2 BLOCKCommit rejected by pre-commit hookRun tests, fix failures, recommit

Telemetry and Tracking

Every session lifecycle event emits telemetry for monitoring and audit purposes:

# Session lifecycle telemetry events
:telemetry.execute([:prismatic_claude, :session_lifecycle, :start], %{}, %{
  session_id: session_id,
  gitlab_issue: issue_number,
  timestamp: DateTime.utc_now()
})

:telemetry.execute([:prismatic_claude, :session_lifecycle, :commit], %{count: 1}, %{
  session_id: session_id,
  commit_hash: hash,
  commit_type: :feat
})

:telemetry.execute([:prismatic_claude, :session_lifecycle, :end], %{
  duration: session_duration_ms,
  commit_count: total_commits
}, %{
  session_id: session_id,
  files_modified: file_count,
  pushed: true
})

Integration Points

Session Discipline integrates with the broader platform infrastructure to ensure workflow compliance:

  • NO MERCY: Session Discipline is an enforcement mechanism of the zero-tolerance doctrine
  • NO DOUBTS: Context loading ensures investigation builds on prior session knowledge
  • Quality Gates: Pre-commit hooks validate every commit during the session
  • Regression Tests: Bug fix commits require regression tests per session protocol
  • Telemetry Integration: Session events tracked through telemetry pipeline
  • Real-Time Monitoring: Session health visible in monitoring dashboards
  • AIAD Standard: Agent sessions follow the same discipline requirements
  • Trinity Gate: Critical session decisions may require Trinity validation
  • Autonomous Self-Healing: Session anomalies can trigger auto-healing

Commands

CommandPurposeAuthority
/session-startInitialize session with GitLab trackingUniversal
/session-saveSave current session contextUniversal
/session-endComplete session with push verificationUniversal
/commitAtomic commit with session trackingUniversal
/pushPush all commits to remoteUniversal
/session-statusDisplay current session stateUniversal

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL