forked from EndogenAI/dogma
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_session.py
More file actions
293 lines (242 loc) · 10.7 KB
/
Copy pathvalidate_session.py
File metadata and controls
293 lines (242 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""scripts/validate_session.py
Post-commit scratchpad audit validator for session files.
Purpose:
Enforce a minimum structural bar on session scratchpad files (.tmp/*/*.md)
to prevent encoding drift during multi-phase sessions. Validates that
critical session metadata and checkpoint records are present.
Checks (7-point audit):
1. ## Session Start present (mandatory session initialization).
2. ## Session Start contains governing axiom citation (checks for "Governing axiom:" pattern).
3. ## Session Start contains endogenous source citation (checks for MANIFESTO.md, AGENTS.md,
docs/, or scripts/ references).
4. ## Orchestration Plan present (tracks phases scheduled for this session).
5. Phase records tracked (all planned phases have ### Phase N headings).
6. Pre-Compact Checkpoint present (mandatory pre-compaction marker).
7. ## Session Summary present (mandatory session close marker).
Inputs:
[file ...] One or more session .md files to audit (positional, optional).
--all Scan all session files in .tmp/*/*.md.
--branch Only scan files on the current git branch.
Outputs:
stdout: Human-readable pass/fail summary with specific gap list per file.
Exit codes:
0 All checks passed.
1 One or more structural checks failed.
2 Encoding drift detected (e.g., axiom not explicitly cited, source not linked).
Usage examples:
# Validate a single session file
uv run python scripts/validate_session.py .tmp/feat-branch/2026-03-11.md
# Validate all session files
uv run python scripts/validate_session.py --all
# Validate only current branch
uv run python scripts/validate_session.py --branch
"""
from __future__ import annotations
import argparse
import re
import sys
from dataclasses import dataclass
from pathlib import Path
@dataclass
class ValidationWarning:
"""A value-fidelity warning for a session file."""
message: str
severity: str # "error" | "warning"
def check_value_fidelity(session_file: Path) -> list[ValidationWarning]:
"""
Constitutional AI post-session value fidelity hook (OQ-4).
Checks:
1. Session contains a ## Session Start heading with a governing axiom sentence.
2. At least 2 MANIFESTO.md citations appear in the file.
3. If ## Session Summary exists, it contains at least one forward reference
(a next step or open question).
Returns:
List of ValidationWarning objects. Empty list means all checks passed.
"""
warnings: list[ValidationWarning] = []
if not session_file.exists():
return [ValidationWarning(f"File not found: {session_file}", severity="error")]
text = session_file.read_text(encoding="utf-8")
# --- Check 1: ## Session Start with governing axiom ---
session_start_match = re.search(r"## Session Start(.+?)(?=\n##|\Z)", text, re.DOTALL)
if not session_start_match:
warnings.append(
ValidationWarning(
"Missing '## Session Start' section — governing axiom cannot be verified",
severity="error",
)
)
else:
body = session_start_match.group(1)
if not re.search(r"Governing axiom", body, re.IGNORECASE):
warnings.append(
ValidationWarning(
"## Session Start missing 'Governing axiom' sentence "
"(required by AGENTS.md §Session-Start Encoding Checkpoint)",
severity="warning",
)
)
# --- Check 2: At least 2 MANIFESTO.md citations ---
manifesto_refs = re.findall(r"MANIFESTO\.md", text)
if len(manifesto_refs) < 2:
warnings.append(
ValidationWarning(
f"Only {len(manifesto_refs)} MANIFESTO.md citation(s) found; "
"at least 2 required for adequate encoding fidelity",
severity="warning",
)
)
# --- Check 3: ## Session Summary with forward reference ---
summary_match = re.search(r"## Session Summary(.+?)(?=\n##|\Z)", text, re.DOTALL)
if summary_match:
summary_body = summary_match.group(1)
forward_ref_patterns = [
r"next\s+session",
r"next\s+step",
r"recommended\s+next",
r"open\s+question",
r"follow.?up",
r"TODO",
r"\[ \]", # unchecked item
r"Phase\s+\d+.*pending",
r"continues?\s+(in|with|at)",
]
has_forward = any(re.search(p, summary_body, re.IGNORECASE) for p in forward_ref_patterns)
if not has_forward:
warnings.append(
ValidationWarning(
"## Session Summary lacks a forward reference "
"(next step or open question required by AGENTS.md §Agent Communication)",
severity="warning",
)
)
return warnings
def validate_session_file(file_path: Path) -> tuple[int, list[str]]:
"""
Validate a session file.
Returns:
(exit_code, list_of_messages)
exit_code:
0 = all checks passed
1 = structural checks failed (missing sections, wrong format)
2 = encoding drift detected (axiom/source not cited)
"""
messages: list[str] = []
structuralFailures = []
encodingDrift = []
if not file_path.exists():
return 1, [f"File not found: {file_path}"]
text = file_path.read_text(encoding="utf-8")
# --- Check 1: ## Session Start present ---
if "## Session Start" not in text:
structuralFailures.append("Missing '## Session Start' section")
# --- Check 2: governing axiom citation in ## Session Start ---
# Extract content between "## Session Start" and next "##" heading
session_match = re.search(r"## Session Start(.+?)(?=\n##|\Z)", text, re.DOTALL)
session_body = session_match.group(1) if session_match else ""
if session_body:
# Check for axiom citation (accepts both ** bold ** and plain formats)
if not re.search(r"\*\*Governing axiom\*\*:|Governing axiom:", session_body, re.IGNORECASE):
encodingDrift.append(
"## Session Start missing explicit 'Governing axiom:' citation "
"(required for encoding checkpoint; see AGENTS.md §Context-Sensitive-Amplification)"
)
else:
structuralFailures.append("## Session Start section is empty or malformed")
# --- Check 3: endogenous source citation in ## Session Start ---
if session_body:
endogenous_sources = (
"MANIFESTO.md",
"AGENTS.md",
"docs/",
"scripts/",
".github/",
)
if not any(source in session_body for source in endogenous_sources):
encodingDrift.append(
f"## Session Start missing endogenous source citation "
f"(expected reference to one of: {', '.join(endogenous_sources)})"
)
# --- Check 4: ## Orchestration Plan present ---
if "## Orchestration Plan" not in text:
structuralFailures.append("Missing '## Orchestration Plan' section")
# --- Check 5: Phase records tracked (Phase N headings) ---
phase_pattern = re.compile(r"^###\s+Phase\s+\d+", re.MULTILINE)
phases = phase_pattern.findall(text)
if not phases:
structuralFailures.append("No phase records found (expected ### Phase N headings)")
# --- Check 6: ## Pre-Compact Checkpoint present ---
if "## Pre-Compact Checkpoint" not in text and "## Context Window Checkpoint" not in text:
structuralFailures.append("Missing '## Pre-Compact Checkpoint' section (required before compaction)")
# --- Check 7: ## Session Summary present ---
if "## Session Summary" not in text:
structuralFailures.append("Missing '## Session Summary' section (required at session close)")
# Compile results
if structuralFailures:
messages.extend([f" ✗ {msg}" for msg in structuralFailures])
if encodingDrift:
messages.extend([f" ⚠ {msg}" for msg in encodingDrift])
# Determine exit code
exit_code = 0
if structuralFailures:
exit_code = 1
elif encodingDrift:
exit_code = 2
return exit_code, messages
def main() -> int:
parser = argparse.ArgumentParser(description="Post-commit scratchpad audit validator for session files")
parser.add_argument("files", nargs="*", help="Session .md files to validate (optional if --all is used)")
parser.add_argument("--all", action="store_true", help="Scan all session files in .tmp/*/*.md")
parser.add_argument("--branch", action="store_true", help="Only scan current branch")
parser.add_argument(
"--fidelity",
action="store_true",
help="Run constitutional AI value fidelity hook (OQ-4) on session files",
)
args = parser.parse_args()
files_to_check: list[Path] = []
if args.all:
tmp_dir = Path(".tmp")
if tmp_dir.exists():
files_to_check = sorted(tmp_dir.glob("*/*.md"))
elif args.branch:
# Get current branch name and scan only that branch's .tmp/ folder
try:
import subprocess
branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True).strip()
branch_dir = Path(f".tmp/{branch}")
if branch_dir.exists():
files_to_check = sorted(branch_dir.glob("*.md"))
except Exception as e:
print(f"Error getting current branch: {e}", file=sys.stderr)
return 1
else:
# Validate specific files passed as arguments
files_to_check = [Path(f) for f in args.files]
if not files_to_check:
print("No session files found to validate", file=sys.stderr)
return 1
overall_exit_code = 0
for file_path in files_to_check:
if args.fidelity:
fidelity_warnings = check_value_fidelity(file_path)
if fidelity_warnings:
overall_exit_code = max(overall_exit_code, 2)
print(f"{file_path}:")
for w in fidelity_warnings:
prefix = " ✗" if w.severity == "error" else " ⚠"
print(f"{prefix} [{w.severity}] {w.message}")
else:
print(f"{file_path}: ✓ fidelity OK")
else:
exit_code, messages = validate_session_file(file_path)
if exit_code > 0:
overall_exit_code = max(overall_exit_code, exit_code)
print(f"{file_path}:")
for msg in messages:
print(msg)
else:
print(f"{file_path}: ✓ OK")
return overall_exit_code
if __name__ == "__main__":
sys.exit(main())