Skip to content

About

Based on Contract-Style-Comments (CSC), Spec-Driven System-Maintenance is a means of governing your system.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

🏛️ Spec-Driven System Maintenance

The Agentic Trivium – Contract-Style Comments

▶️ Governance-first system maintenance for human-AI collaboration - Complete walkthrough course

Purpose

Spec-Driven System Maintenance (SDSM) is a governance framework that enables stateless AI agents to perform system maintenance tasks with precision, accountability, and full alignment with human intent. It treats documentation as executable law, not as an afterthought.

In system maintenance contexts—where environments are complex, configurations drift, and dependencies age—traditional ad-hoc approaches fail. SDSM provides the control plane that transforms maintenance from reactive fire-fighting into a governed, auditable process.


The Core Philosophy

A maintained system is a governed system. Without explicit specifications, AI agents operate on assumptions that may be incorrect, outdated, or contradictory. SDSM establishes:

  1. Invariants as Law: What must never break, regardless of who performs maintenance
  2. Operational Truth as Map: How the system actually runs, where components live, and how to verify integrity
  3. Resource Integrity as Contract: Presentation and binary assets treated with the same rigor as code
  4. Audit Trail as Memory: Every change recorded, every decision traceable

This is not documentation for humans to read. This is the control plane for human-AI maintenance collaboration.


The Governance Architecture

SDSM organizes system knowledge into a Triumvirate of governing artifacts, supported by supplements:

The Triumvirate (Law)

Artifact Role Rate of Change
CONTRACT.md — The Law Defines system invariants, architectural boundaries, and absolute prohibitions. What the system IS and what must NEVER break. Lowest — changes only when fundamental system constraints change
WHY.md — The Reasoning Explains the relationship between governing artifacts and governance rules. How to update system law and operations docs correctly. Low — changes when governance relationships evolve
QUICKSTART.md — The Map The empirical interface for operational verification. How to verify system integrity, where critical components live, and how to prove the system works. High — changes as the system evolves

Supplements (Support)

Artifact Role Rate of Change
ASSETS.md — The Resource Law Governs presentation invariants, static assets, binary dependencies, and model weights. Prevents silent regressions when visual or binary resources change. Medium
FUTURE.md — The Roadmap Non-binding queue for planned maintenance priorities and deferred work. Captures intent without corrupting present-tense truth. Variable
DELEGATION.md — Role Registry Multi-agent assignment table. Defines who is ACTIVE, their role, silo, and scope. Read first to determine your authority. Per-session
DELTALOG.md — The Change Log Proposal queue and merge record for governance changes. Every meaningful change gets an entry here. Per-change

Quick Start

For System Owners

  1. Clone this repository into a ./contract/ directory located where you wish. E.g. /home/$USER/contract
  2. cd $HOME
    git clone git@github.com:ajaxStardust/spec-driven-system-maintenance.git ./contract
  3. Command the AI to customize the governance artifacts to reflect the system's actual state. E.g. "Perform a brief diagnostic of your host system for purpose of replacing all contract boilerplate with a governance model for this host system. Proceed with replacing the boilerplate after the brief system diagnosis."
  4. rm -rv /home/$USER/contract/.git
    cd /home/$USER/contract
    git init
    git add .
    git commit
  5. Commit and push the customized specification if a remote upstream exists.
  6. At the start of every maintenance session, use the Phase 1 prompt below.

For AI Agents

This file teaches you how to operate as a Steward. Read it before you touch anything else. The three phases below are not runbooks — they are operating constraints. Each phase is a gate. You do not proceed to Phase 2 until Phase 1 is complete. You do not execute maintenance until Phase 2 is complete. You do not close the session until Phase 3 is complete.


The Three Phases

You are entering a governed environment. The system has a Contract — a set of files under a contract root directory (typically ~/contract/ or ./contract/) that define what the system IS, what it MUST do, and what it MUST NOT do. These files are present-tense law, not history. Git holds chronology; the Contract holds current constraints.

Your job is to:

  1. Read the Contract before you do anything
  2. Verify the live system matches the Contract
  3. Reconcile discrepancies — either fix the system, update the Contract, or record the exception

You do not skip steps. You do not batch steps. Each phase is a gate, and you do not pass through a gate until the prior phase is complete.


Phase 1: Ingestion

Purpose: Ingest the Contract so your decisions are grounded in the system's actual governance, not assumptions from training data. This prevents contextual drift — the condition where an agent makes confident decisions based on incomplete or outdated system knowledge.

What happens in this phase:

  1. Determine your role. Read DELEGATION.md first. It tells you your role (Steward, Auditor, Implementer, Orchestrator, or Recovery), your silo (write boundary), your status (ACTIVE / SUSPENDED / PENDING), and how many other agents are active. If your status is not ACTIVE, you have no authority — halt and notify the human.

  2. Read the Contract in order. Each file builds on the previous:

    • CONTRACT.md → What must never break
    • WHY.md → How to update the Contract correctly
    • QUICKSTART.md → How to verify the system works
    • ASSETS.md → What resources exist and where they live
    • FUTURE.md → What is planned (non-binding)
    • DELTALOG.md → What changes are in flight or recently merged
  3. Acknowledge. After ingestion, respond exactly: "Contract ingested. Role: [your role]. Silo: [your silo]. Acknowledged as source of truth." Then cease all output until the human issues a Phase 2 command.

Constraints during Phase 1:

  • No system probes, privileged commands, or runtime state inspection.
  • No scanning of config directories.
  • No hardcoded paths — use paths from CONTRACT.md and ASSETS.md.
  • If a file read fails: list the contract directory, check the file line count, retry with explicit start/end lines.
  • Confirm all 7 files exist and are readable. If DELTALOG.md is missing, report structural sync failure and halt.
  • Note the top 3 structural concerns where the live system might conflict with CONTRACT.md invariants — but do not verify them yet. Just flag them for Phase 2.

Bootstrap gap: If this is the very first session on a freshly cloned template, DELEGATION.md will have no ACTIVE rows — only [AGENT-ID] placeholders. In this case, the human is acting as the Orchestrator and has implicitly assigned you the Steward role with full read access. Use Scenario A below. You will populate DELEGATION.md with your own row during Phase 3.

Signature awareness: You will see LAST REVIEWED stamps with signatures like SIGNATURE: pi-coding-agent (MiniMax-M3). These represent prior maintainers. You are not forging signatures during Phase 1. You will add your own signature only during Phase 3, after you have done real work.

📋 Copy-Paste Prompt — Phase 1: Ingestion

Pick the scenario that matches your situation and paste it verbatim as the first message of your session.

┌─────────────────────────────────────────────────────────────────────────┐
│                                                                         │
│  SCENARIO A — Fresh template bootstrap (first session after git clone)  │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

This is a fresh CSC template cloned at <CONTRACT_ROOT> (e.g. ~/contract).
Every governance file is still boilerplate and DELEGATION.md has no agent
rows yet.

Act as Steward operating under my command (I am the Human Supreme-Steward
for this bootstrap). Perform Phase 1 ingestion of <CONTRACT_ROOT> in the
required order (CONTRACT → WHY → QUICKSTART → ASSETS → FUTURE → DELTALOG;
DELEGATION is empty by design at this stage). Emit the Phase 1
acknowledgment. Then, on my go-ahead, run a Phase 2 host audit (read-only,
platform-native probes only) and a Phase 3 reconciliation that replaces the
boilerplate with law tailored to this host — updating only the narrowest
owning artifact per finding. Do not probe the system or write any file
until I confirm.

┌─────────────────────────────────────────────────────────────────────────┐
│                                                                         │
│  SCENARIO B — Ongoing governed session (Contract already customized)    │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘

<CONTRACT_ROOT> holds the active Contract for this host. Act as Steward.
Perform Phase 1 ingestion: read DELEGATION.md FIRST to determine your role,
silo, and status, then CONTRACT → WHY → QUICKSTART → ASSETS → FUTURE →
DELTALOG in order. Emit the Phase 1 acknowledgment ("Contract ingested.
Role: … Silo: … Acknowledged as source of truth."). Then cease output and
await my task. Do not probe or modify anything until I issue a Phase 2
command.

Phase 2: Primary Audit

Purpose: Probe the live system, compare findings against the Contract, classify every discrepancy, and produce an evidence trail. This is where the agent earns its authority — not by acting on assumptions, but by verifying against ground truth.

Precondition check: Before you run any probe, confirm Phase 1 is complete, your role is ACTIVE, and you know your silo and authority. If any of these are false, halt and notify the human.

Execution model:

  • Single-agent default. You do not deploy a Swarm unless DELEGATION.md shows multiple ACTIVE assignments and the work is genuinely parallelizable and the coordination overhead is less than the time saved.
  • Role-gated probes. What you are allowed to probe depends on your role:
    • Steward / Auditor: All read-only probes.
    • Implementer: Probes within your silo only. Request scope extension for anything outside.
    • Orchestrator: All probes. No self-approval needed.

The Audit Loop — for each check, follow this sequence:

  1. Query the Contract. What does CONTRACT.md or ASSETS.md say about this component?
  2. Probe the live system. Use the platform-native command (see mapping tables below).
  3. Compare. Does the live state match the Contract?
  4. Classify. If there is a gap:
    • Contract violation — system state violates an explicit invariant. Highest severity.
    • System drift — system has changed since the Contract was last updated. Contract may need update.
    • Intentional exception — deviation was deliberate and recorded in DELTALOG.md. Lowest severity.
  5. Record. Every probe, every finding, every classification goes under <CONTRACT_ROOT>/evidence/ with a timestamped directory.

Critical caveat — learned the hard way: The human's description of a symptom is a hypothesis, not ground truth. A user-facing warning may name one component while the actual fault lives in another. Before acting on any human-provided diagnosis, corroborate it with a first-party probe — a log line, a process check, a config inspection. Acting on an unverified diagnosis can consume an entire session on the wrong subsystem and still fail to fix the actual problem. (See CONTRACT.md §7: Symptom Hypothesis Precondition.)

Probe Categories:

1. Host Identity & Hardware

What to verify Where it's defined Probe strategy
Distro, kernel, architecture CONTRACT.md §Host Identity Platform-native hardware inventory
CPU, RAM, disk layout CONTRACT.md §Hardware Constraints Platform-native hardware inventory
Disk headroom CONTRACT.md §Hardware Constraints Platform-native disk free command

Platform mappings for hardware inventory:

OS Command Fallback if missing
Linux inxi -b cat /etc/os-release, uname -a, lscpu, free -h, lsblk
macOS system_profiler SPSoftwareDataType SPHardwareDataType SPStorageDataType sysctl hw.model hw.ncpu hw.physmem
BSD dmidecode (if permitted) or sysctl hw.model hw.ncpu hw.physmem + geom disk list + df -h Same as primary — BSD has no inxi equivalent

Platform mappings for disk free:

OS Command Detail
Linux/macOS/BSD df -h Universal — always works
Linux lsblk Block device layout
macOS diskutil list APFS/APFS GUID layout
BSD geom disk list

2. Package State

What to verify Where it's defined Probe strategy
Installed packages ASSETS.md or CONTRACT.md Capture baseline if none exists
Held / pinned packages CONTRACT.md §Holds Platform-native hold list
Pending upgrades CONTRACT.md §Upgrades Platform-native update check
Package log CONTRACT.md §Log Path Verify log exists and is readable

Platform mappings:

OS Manifest Holds Updates Log
Debian/Ubuntu dpkg --get-selections apt-mark showhold apt list --upgradable /var/log/apt/history.log
RPM (RHEL/Fedora) rpm -qa yum versionlock list or dnf versionlock list yum check-update or dnf check-update /var/log/dnf.log or /var/log/yum.log
Arch pacman -Q Pin in /etc/pacman.conf pacman -Qu /var/log/pacman.log
macOS (Homebrew) brew list --versions brew list --pinned brew outdated ~/Library/Logs/Homebrew/brew.log
macOS (Ports) port installed Variants in /opt/local/etc/macports/variants.conf port outdated Port uses flat registry
BSD (pkg) pkg info pkg lock -l pkg version -v /var/log/messages
BSD (ports) pkg_info /usr/local/etc/pkg/repos.conf pkg_version -v /var/log/messages

Failure rule: If the package manager is not one of the above, use the platform-native equivalent. Do not halt — record "unknown package manager" and continue.

3. Critical Services

Service Probe strategy
SSH / remote access Platform-native service check
Network (default route) Platform-native route check
Internet connectivity ICMP to a public resolver
Display server $XDG_SESSION_TYPE or $DISPLAY

Platform mappings:

OS SSH Route ICMP
Linux (systemd) systemctl is-active ssh ip route show default ping -c 1 1.1.1.1
Linux (OpenRC) rc-service sshd status ip route show default ping -c 1 1.1.1.1
macOS launchctl list com.openssh.sshd route -n get default ping -c 1 8.8.8.8
BSD service sshd status netstat -rn ping -c 1 8.8.8.8

4. Resource Registry (ASSETS.md)

For each entry in ASSETS.md §Resource Invariants, verify:

  1. Does the binary/file exist at the path listed?
  2. Does it execute? (version flag or --help)
  3. Is the version recorded in ASSETS.md still current?

For GPU compute frameworks, probe with timeout:

Framework Probe command Record
PyTorch (CUDA) timeout 30 python3 -c "import torch; print(torch.cuda.is_available())" Pass / Fail / Hang
PyTorch (ROCm) timeout 30 python3 -c "import torch; print(torch.version.hip)" Pass / Fail / Hang
NVIDIA (no PyTorch) nvidia-smi Active / Not found
AMD ROCm (no PyTorch) rocm-smi --showid Active / Not found
Apple Silicon system_profiler SPDisplaysDataType Metal capable / Not found

Platform note for timeout: GNU coreutils timeout uses timeout 30s command. BSD/macOS timeout is not in base — use gtimeout (coreutils via brew) or perl -e 'alarm 30; exec @ARGV' command.

5. Configuration & Backups

  • Validate package repositories are reachable (platform-native update check without installing).
  • Identify timestamped backups: *.bak, *.bak.YYYY-MM-DD, *.YYYYMMDD in /etc/, /www/, $HOME/.
  • Locate rollback/restart scripts in $HOME/bin/, /usr/local/bin/, and any restart-* or rollback-* patterns.

6. Recovery Tooling

Probe every recovery mechanism named in CONTRACT.md or ASSETS.md:

Tool Check command
Timeshift sudo timeshift --list
Snapper snapper list
Btrfs sudo btrfs subvolume list /
ZFS sudo zfs list -t snapshot
Time Machine tmutil listbackups
APFS snapshots tmutil listlocalsnapshots /

Rule: If the tool is not installed, record "not installed" and continue. Do not halt.

Summary report — at the end of Phase 2, produce:

  1. 2-sentence summary — overall system health versus the Contract.
  2. Top 3 concerns — actionable discrepancies, each classified as Contract violation / System drift / Intentional exception.
  3. Verified pipelines — what is actually running and confirmed.
  4. Rollback scripts — paths found and their apparent purpose.
  5. DELEGATION status — your role, any scope requests filed, any conflicts detected.

Caveat: Tailor every command suggestion to the detected host OS and hardware constraints. Do not emit Linux-only commands on a BSD or macOS host.

📋 Copy-Paste Prompt — Phase 2: Primary Audit

Phase 1 ingestion is complete. I now authorize a Phase 2 Primary Audit.

Run read-only, platform-native probes against this host. For each probe:
query the Contract first, probe the live system, compare, classify any gap
(Contract violation / System drift / Intentional exception), and record the
finding. Do not modify system state — if a probe has side effects, it is an
action, not a probe, and requires explicit authorization.

If I have described a symptom or given you a diagnosis, treat it as a
hypothesis, not ground truth. Corroborate it with a first-party probe (log,
config check, process inspection) before acting on it. A user-facing warning
may name one component while the actual fault lives in another.

Produce the Phase 2 summary report when done: 2-sentence health summary, top
3 concerns with classification, verified pipelines, rollback scripts found,
and your DELEGATION status. Await my authorization before any Phase 3 work.

Phase 3: Session Closure Handshake

Purpose: Reconcile the session's discoveries and changes into the Contract. You are not done until the Contract reflects what you found and did. This phase is a handshake — you propose, the human disposes. You do not self-close. The human closes the session.

What happens in this phase:

Step 1: Classify Your Changes

For every action taken in Phase 2 (or any implementation work), classify it:

Change type Update target Example
Invariant / boundary change CONTRACT.md "Disk headroom invariant changed from 10% to 15%"
Operational command / check QUICKSTART.md "Added ZFS snapshot recovery command"
Binary / resource change ASSETS.md "Updated Ollama version from 0.18.0 to 0.20.0"
Governance rule change WHY.md "Updated reading order to include DELEGATION.md earlier"
Roadmap item FUTURE.md "Moved 'Timeshift setup' from FUTURE to active concern"
Agent assignment DELEGATION.md "Updated timestamp for own row; filed scope extension"
Proposed / merged change DELTALOG.md "DELTA-057: Mark Timeshift as not installed on ext4 system"

Rule: Update the narrowest file that owns the change. If a disk headroom finding changes both a CONTRACT invariant AND a QUICKSTART check, update both — but each update is its own decision, not a batch operation. Batch updates are how drift accumulates.

Step 2: Write the Evidence

For every discrepancy found in Phase 2:

  1. Create a timestamped directory under <CONTRACT_ROOT>/evidence/YYYY-MM-DD-QUALIFIER/.
  2. Write a finding.md containing: what was expected (from Contract), what was found (from probe), classification, and proposed resolution.
  3. If you updated a Contract file to resolve the discrepancy, reference the update in the finding.

Step 3: Update DELTALOG.md

For every meaningful change:

  1. Add an entry in DELTALOG.md following the existing format.
  2. If the change is a proposal (not yet approved), mark it PROPOSED.
  3. If you are an Orchestrator merging your own proposal, mark it APPROVED and MERGED in the same entry.
  4. If you are a Steward proposing a change that requires Orchestrator approval, leave it PROPOSED and notify the human.

Step 4: Signature Convention

Every LAST REVIEWED or LAST UPDATED stamp you write must follow this format:

YYYY-MM-DD-QUALIFIER SIGNATURE: <your identity>
  • YYYY-MM-DD is today's date in UTC.
  • QUALIFIER is a semantic label describing what changed: DISCOVERY, STEWARDSHIP, HARDWARE-AUDIT, KERNEL-FLAG, DB-SCHEMA-SYNC.
  • SIGNATURE is your actual identity: Cline (AI coding agent), claude-haiku-4.5, Human maintainer.

Never:

  • A bare date with no qualifier (ambiguous).
  • A past date you did not live through (forgery).
  • A future date (violates chronology).
  • A signature that impersonates another model or human.

Step 5: DELEGATION.md Session Update

Before closing, update your own row in DELEGATION.md:

  • You MAY: Update your Timestamp (UTC) to today's date. Update your Status from ACTIVE to SUSPENDED (session ending). Append a one-line note: "Phase 2 audit complete; top concern: stale kernels."
  • You MAY NOT: Add, remove, or reassign rows. Modify another agent's row without their explicit consent recorded in DELTALOG.md. Release a lock held by another ACTIVE agent. Only the Orchestrator or Human may release cross-agent locks.

Lock handoff: If you are an Orchestrator releasing a Worker's lock after verifying their proof of work, record the release in DELTALOG.md as a closure entry before setting their status.

Step 6: Final Review

Before you close:

  1. Accuracy check: Do Contract files reflect only present-tense law? Remove any historical prose that reads like a changelog.
  2. Decoupling check: Is the contract directory independent of version control? Git holds history. Contract holds law. They should not duplicate each other.
  3. Completeness check: Did you update every artifact that owns a piece of what you discovered? Use the Narrowest-Scope table.
  4. Evidence check: Does every discrepancy have a file under the evidence directory?

Step 7: Exit

  1. Present a diff summary to the human: what changed, why, and in which files.
  2. Await explicit confirmation: "Session closed" or equivalent.
  3. Do not self-close. The human closes the session.

📋 Copy-Paste Prompt — Phase 3: Session Closure Handshake

Phase 2 audit is complete. I now authorize Phase 3 Session Closure.

Reconcile all findings into the Contract. For each change, classify it and
update only the narrowest owning artifact — not batch updates. Write evidence
files for every discrepancy. File DELTALOG.md entries for every meaningful
change. Update your signature on every artifact you touched, following the
YYYY-MM-DD-QUALIFIER SIGNATURE convention. Update your own row in
DELEGATION.md (timestamp + status to SUSPENDED + one-line note).

Before requesting session closure, present a diff summary: what changed, why,
and in which files. I will close the session — do not self-close.

Platform-Agnostic Principles

These are not phase-specific — they apply everywhere:

Strategy over Syntax

You are told what to discover, not which command to run. Read CONTRACT.md to find the package manager, paths, and tooling for the host you are on. Do not assume apt unless the Contract says so.

Graceful Degradation

If a tool is not installed (inxi, snapper, timeshift, btrfs), record "not installed" and move on. Do not halt the audit. Do not emit an error that stops subsequent checks.

Contract-First Discovery

Every path, every binary, every service name comes from the Contract or the live probe — not from this prompt. If the prompt mentions a path, it is an example. The Contract's path is the authority.

Idempotent Probes

Every Phase 2 check is safe to re-run. No probe modifies system state. If a probe has side effects, it is not a probe — it is an action, and it belongs in a later phase with explicit human authorization.


Multi-Agent Maintenance (The Swarm)

When multiple agents collaborate on system maintenance, SDSM prevents agent collision through strict role separation:

Role Persona Responsibility Scope
Orchestrator Cue Control plane: adjudicates scope, resolves conflicts, finalizes judgment Governance artifacts only
Archivist Stores-It Memory keeper: maintains context, records, and governance state Document updates
Auditor Solves-It Investigator: verifies claims, checks cross-references, hunts drift Read-only verification
Implementer Builder Executor: performs maintenance within delegated scope Assigned silo only
Recovery Rescues-It Repair agent: handles incident response and contract repair Emergency scope

Golden Rule: Workers propose, Orchestrator disposes. No Worker may modify governance artifacts without Orchestrator approval.


The Agentic Handshake

Using SDSM transforms your relationship with AI from "tool user" to "system governor":

  1. Stewardship: The AI agent is authorized—and expected—to act as a Governance Steward during maintenance sessions
  2. Responsibility: No maintenance change is complete until the corresponding documentation artifact has been updated
  3. Surfacing Axioms: If the agent discovers an undocumented system assumption, it must immediately surface it in CONTRACT.md
  4. Falsifiability: Every claim must be testable or disprovable by evidence

Anti-Patterns (What Not To Do)

These are the failures this governance model exists to prevent:

  1. Governance theater: Asking the human to paste blocks into Contract files. If you can write the Contract, write it. The human reviews via git diff, not by editing raw Markdown in a terminal.
  2. Single-agent amnesia: Forgetting you read DELEGATION.md in Phase 1 and treating Phase 2 as if you have no role. You always have a role. Re-read DELEGATION.md if you lose track.
  3. Batch updates: Touching all seven Contract files because "they're all governance." No. Each change goes to the narrowest owning file. Batch updates are how drift accumulates.
  4. Forged signatures: Writing SIGNATURE: <other model> because you think it looks better. Signatures are audit evidence. Forge one and you corrupt the entire governance history.
  5. Reflexive swarm: Deploying a Swarm because it seems impressive. Swarms have coordination overhead. Single-agent is faster for sequential work.
  6. History in law: Letting CONTRACT.md accumulate prose about what used to be true. If it is not true now, delete it or update it. If it needs to be remembered, it belongs in Git.
  7. Ignored exceptions: Finding a Contract violation and silently working around it. Document it. Classify it. File a Delta. An undocumented exception is a secret loophole.
  8. Unverified symptom action: Acting on the human's description of a symptom as if it were the root cause. The human's commands are law; their diagnoses are hypotheses. Always corroborate a human-provided diagnosis with a first-party probe (log, config check, process inspection) before acting. A plausible-sounding misdiagnosis can waste an entire session on the wrong subsystem.

Contributing

This framework evolves through governance itself. To contribute:

  1. Open an issue describing the governance gap or improvement
  2. Submit a Delta proposal in DELTALOG.md format
  3. Wait for Orchestrator approval before modifying Triumvirate artifacts

License

This framework is provided for the advancement of human-AI collaboration in system maintenance. Use it to make your systems more maintainable, auditable, and resilient.


Spec-Driven System Maintenance — Because maintained systems deserve governed maintenance.

About

Based on Contract-Style-Comments (CSC), Spec-Driven System-Maintenance is a means of governing your system.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors