-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sentinel_scribe.py
More file actions
692 lines (573 loc) · 24.9 KB
/
test_sentinel_scribe.py
File metadata and controls
692 lines (573 loc) · 24.9 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
"""Tests for sentinel_scribe.py — no Ollama required."""
import json
import os
import sys
import tempfile
import hashlib
import time
from datetime import datetime, timezone
import pytest
import yaml
sys.path.insert(0, os.path.dirname(__file__))
@pytest.fixture
def scribe_dir(tmp_path):
"""Create a temp directory structure mimicking .sentinel/scribe/."""
scribe = tmp_path / "scribe"
scribe.mkdir()
return str(scribe)
@pytest.fixture
def config_dir(tmp_path):
"""Create a temp .claude/sentinel/ config dir with drafts/."""
sentinel_dir = tmp_path / ".claude" / "sentinel"
sentinel_dir.mkdir(parents=True)
rules_dir = sentinel_dir / "rules"
rules_dir.mkdir()
drafts_dir = sentinel_dir / "drafts"
drafts_dir.mkdir()
return str(sentinel_dir)
@pytest.fixture
def base_config(config_dir):
import sentinel_scribe
return sentinel_scribe.load_config(config_dir)
def test_load_config_has_scribe_defaults(base_config):
import sentinel_scribe
scribe = base_config.get("scribe", {})
assert scribe.get("enabled") is True
assert scribe.get("model") is None
assert scribe.get("guidance") is None
assert scribe["thresholds"]["extraction_confidence"] == 0.7
assert scribe["thresholds"]["draft_confidence"] == 0.8
assert scribe["transcript_budget_chars"] == 4000
assert scribe["notification"]["max_age_days"] == 7
assert "CLAUDE.md" in scribe["doc_globs"]
def test_load_config_merges_user_overrides(config_dir):
import sentinel_scribe
config_path = os.path.join(config_dir, "config.yaml")
with open(config_path, "w") as f:
yaml.dump({"scribe": {"guidance": "focus on security", "transcript_budget_chars": 8000}}, f)
cfg = sentinel_scribe.load_config(config_dir)
assert cfg["scribe"]["guidance"] == "focus on security"
assert cfg["scribe"]["transcript_budget_chars"] == 8000
assert cfg["scribe"]["thresholds"]["extraction_confidence"] == 0.7
def test_append_observation(scribe_dir):
import sentinel_scribe
obs = {
"ts": "2026-03-31T10:01:23Z",
"source": "user_prompt",
"session_id": "abc123",
"statement": "Don't modify billing directly",
"scope_hint": "src/core/billing",
"trigger_hint": "file_write",
"confidence": 0.91,
"evidence": "don't touch billing",
"drafted": False,
}
sentinel_scribe.append_observation(scribe_dir, obs)
obs_path = os.path.join(scribe_dir, "observations.jsonl")
assert os.path.exists(obs_path)
with open(obs_path) as f:
lines = f.readlines()
assert len(lines) == 1
parsed = json.loads(lines[0])
assert parsed["statement"] == "Don't modify billing directly"
def test_append_observation_creates_dir(tmp_path):
import sentinel_scribe
scribe_dir = str(tmp_path / "nonexistent" / "scribe")
obs = {"ts": "T", "source": "user_prompt", "statement": "test"}
sentinel_scribe.append_observation(scribe_dir, obs)
assert os.path.exists(os.path.join(scribe_dir, "observations.jsonl"))
def test_is_dismissed_empty(scribe_dir):
import sentinel_scribe
assert sentinel_scribe.is_dismissed(scribe_dir, "src/billing/**", "file_write") is False
def test_dismiss_and_check(scribe_dir):
import sentinel_scribe
sentinel_scribe.add_dismissal(scribe_dir, "src/billing/**", "file_write", "test statement")
assert sentinel_scribe.is_dismissed(scribe_dir, "src/billing/**", "file_write") is True
assert sentinel_scribe.is_dismissed(scribe_dir, "src/api/**", "file_write") is False
def test_dismiss_uses_scope_trigger_match(scribe_dir):
import sentinel_scribe
sentinel_scribe.add_dismissal(scribe_dir, "src/billing/**", "file_write", "billing protection")
assert sentinel_scribe.is_dismissed(scribe_dir, "src/billing/**", "bash") is False
def test_build_doc_prompt():
import sentinel_scribe
prompt = sentinel_scribe.build_doc_extraction_prompt(
content="Never commit .env files", source_type="CLAUDE.md", guidance=None
)
assert "Source type: CLAUDE.md" in prompt
assert "Never commit .env" in prompt
def test_parse_extraction_response_valid():
import sentinel_scribe
response = '{"conventions": [{"statement": "No billing edits", "scope_hint": "src/billing", "trigger_hint": "file_write", "confidence": 0.9, "evidence": "don\'t touch billing"}]}'
result = sentinel_scribe.parse_extraction_response(response)
assert len(result) == 1
assert result[0]["statement"] == "No billing edits"
def test_parse_extraction_response_empty():
import sentinel_scribe
result = sentinel_scribe.parse_extraction_response('{"conventions": []}')
assert result == []
def test_parse_extraction_response_malformed():
import sentinel_scribe
result = sentinel_scribe.parse_extraction_response("not json at all")
assert result == []
def test_parse_extraction_response_with_stray_text():
import sentinel_scribe
response = 'Here is my analysis:\n{"conventions": [{"statement": "test", "scope_hint": "src/", "trigger_hint": "bash", "confidence": 0.8, "evidence": "evidence"}]}\nDone.'
result = sentinel_scribe.parse_extraction_response(response)
assert len(result) == 1
def test_normalize_trigger_hint_pipe_separated():
"""Should extract first valid trigger from pipe-separated values."""
import sentinel_scribe
assert sentinel_scribe._normalize_trigger_hint("file_write|read|modify") == "file_write"
assert sentinel_scribe._normalize_trigger_hint("bash|mcp|unknown") == "bash"
assert sentinel_scribe._normalize_trigger_hint("read|modify") == "unknown"
assert sentinel_scribe._normalize_trigger_hint("mcp") == "mcp"
assert sentinel_scribe._normalize_trigger_hint("") == "unknown"
assert sentinel_scribe._normalize_trigger_hint("file_write") == "file_write"
def test_parse_extraction_normalizes_trigger():
"""parse_extraction_response should normalize trigger_hint values."""
import sentinel_scribe
response = json.dumps({"conventions": [{
"statement": "test",
"scope_hint": "src/billing",
"trigger_hint": "file_write|read|modify",
"confidence": 0.9,
"evidence": "test",
}]})
result = sentinel_scribe.parse_extraction_response(response)
assert len(result) == 1
assert result[0]["trigger_hint"] == "file_write"
def test_write_draft_yaml(config_dir):
"""Should write a valid draft YAML with _draft metadata."""
import sentinel_scribe
drafts_dir = os.path.join(config_dir, "drafts")
draft = {
"id": "no-billing-edits",
"trigger": "file_write",
"severity": "block",
"scope": ["src/billing/**"],
"exclude": ["**/*.test.ts"],
"prompt": "Test prompt {{file_path}}",
}
draft_meta = {
"source": "user_prompt",
"observed": 1,
"first_seen": "2026-03-31",
"evidence": ["don't touch billing"],
"confidence": 0.91,
"synthesized": "2026-03-31T10:01:45Z",
"model": "gemma3:4b",
}
sentinel_scribe.write_draft(drafts_dir, draft, draft_meta)
path = os.path.join(drafts_dir, "no-billing-edits.draft.yaml")
assert os.path.exists(path)
with open(path) as f:
loaded = yaml.safe_load(f)
assert loaded["id"] == "no-billing-edits"
assert loaded["trigger"] == "file_write"
assert loaded["_draft"]["source"] == "user_prompt"
assert loaded["_draft"]["confidence"] == 0.91
def test_build_synthesis_prompt():
import sentinel_scribe
observation = {
"statement": "Never edit billing directly",
"scope_hint": "src/billing",
"trigger_hint": "file_write",
"evidence": "don't touch billing",
}
prompt = sentinel_scribe.build_synthesis_prompt(
observation=observation,
matched_files=["src/billing/invoice.ts", "src/billing/payment.ts"],
sample_rules=[{"id": "test-rule", "trigger": "bash", "scope": ["git *"], "prompt": "test"}],
)
assert "Never edit billing directly" in prompt
assert "src/billing/invoice.ts" in prompt
assert "test-rule" in prompt
assert "file_write" in prompt
assert "ACTUAL files" in prompt or "REAL paths" in prompt
from unittest.mock import patch, MagicMock
def test_learn_scans_documentation(tmp_path, config_dir):
"""Learn should scan doc files and extract conventions."""
import sentinel_scribe
project_root = os.path.dirname(os.path.dirname(config_dir))
claude_md = os.path.join(project_root, "CLAUDE.md")
with open(claude_md, "w") as f:
f.write("# Rules\n\nNever commit .env files.\nAlways run tests before pushing.")
config = sentinel_scribe.load_config(config_dir)
scribe_dir = str(tmp_path / "scribe")
session_dir = str(tmp_path / "sessions" / "test")
extraction_response = json.dumps({"conventions": [{
"statement": "Never commit .env files",
"scope_hint": "**/.env",
"trigger_hint": "file_write",
"confidence": 0.95,
"evidence": "Never commit .env files",
}]})
synthesis_response = """id: no-env-commit
trigger: file_write
severity: block
scope:
- "**/.env"
prompt: |
Test {{file_path}}
"""
call_count = {"n": 0}
def mock_ollama(prompt, system_prompt, model, backend, cfg, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return extraction_response
return synthesis_response
with patch.object(sentinel_scribe, "call_llm", side_effect=mock_ollama):
with patch("sentinel_lock.acquire_lock", return_value=99):
with patch("sentinel_lock.release_lock"):
result = sentinel_scribe.learn(
config=config, config_dir=config_dir,
scribe_dir=scribe_dir, session_dir=session_dir,
)
assert result["files_scanned"] >= 1
assert result["conventions_found"] >= 1
def test_check_pending_drafts_returns_notification(config_dir, tmp_path):
"""Should return notification text when recent drafts exist."""
import sentinel_scribe
drafts_dir = os.path.join(config_dir, "drafts")
draft = {
"id": "test-draft",
"trigger": "file_write",
"scope": ["src/**"],
"prompt": "test",
"_draft": {
"source": "user_prompt",
"synthesized": datetime.now(timezone.utc).isoformat(),
},
}
with open(os.path.join(drafts_dir, "test-draft.draft.yaml"), "w") as f:
yaml.dump(draft, f)
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
notification = sentinel_scribe.check_pending_drafts(
drafts_dir=drafts_dir,
session_dir=session_dir,
max_age_days=7,
)
assert notification is not None
assert "draft" in notification.lower()
assert "/sentinel-drafts" in notification
def test_check_pending_drafts_skips_if_already_notified(config_dir, tmp_path):
"""Should return None if already notified this session."""
import sentinel_scribe
drafts_dir = os.path.join(config_dir, "drafts")
draft = {
"id": "test-draft",
"trigger": "file_write",
"scope": ["src/**"],
"prompt": "test",
"_draft": {"source": "user_prompt", "synthesized": datetime.now(timezone.utc).isoformat()},
}
with open(os.path.join(drafts_dir, "test-draft.draft.yaml"), "w") as f:
yaml.dump(draft, f)
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
n1 = sentinel_scribe.check_pending_drafts(drafts_dir, session_dir, 7)
assert n1 is not None
n2 = sentinel_scribe.check_pending_drafts(drafts_dir, session_dir, 7)
assert n2 is None
def test_check_pending_drafts_skips_old_drafts(config_dir, tmp_path):
"""Should not notify for drafts older than max_age_days."""
import sentinel_scribe
drafts_dir = os.path.join(config_dir, "drafts")
old_time = "2026-03-01T10:00:00+00:00"
draft = {
"id": "old-draft",
"trigger": "bash",
"scope": ["*"],
"prompt": "test",
"_draft": {"source": "user_prompt", "synthesized": old_time},
}
with open(os.path.join(drafts_dir, "old-draft.draft.yaml"), "w") as f:
yaml.dump(draft, f)
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
notification = sentinel_scribe.check_pending_drafts(drafts_dir, session_dir, 7)
assert notification is None
def test_read_compacted_transcript(tmp_path):
"""Should read and compact full transcript with budget truncation."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
entries = [
{"type": "user", "message": {"role": "user", "content": "Add a login page"}, "timestamp": "T1"},
{"type": "assistant", "message": {"role": "assistant", "content": [
{"type": "tool_use", "name": "Write", "input": {"file_path": "src/login.py"}}
]}, "timestamp": "T2"},
{"type": "user", "message": {"role": "user", "content": json.dumps([
{"tool_use_id": "tu_1", "type": "tool_result", "content": "File written"}
])}, "timestamp": "T3"},
{"type": "user", "message": {"role": "user", "content": "never use eval"}, "timestamp": "T4"},
]
with open(transcript, "w") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
result = sentinel_scribe.read_compacted_transcript(str(transcript), budget_chars=10000)
assert "[human] Add a login page" in result
assert "[assistant]" in result
assert "[result]" in result
assert "[human] never use eval" in result
def test_read_compacted_transcript_truncation(tmp_path):
"""Should truncate long transcripts keeping head + tail."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
entries = [
{"type": "user", "message": {"role": "user", "content": f"message {i}" * 20}, "timestamp": f"T{i}"}
for i in range(50)
]
with open(transcript, "w") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
result = sentinel_scribe.read_compacted_transcript(str(transcript), budget_chars=500)
assert len(result) <= 600 # some tolerance for the truncation marker
assert "truncated" in result.lower()
def test_read_compacted_transcript_missing_file():
"""Should return empty string for missing transcript."""
import sentinel_scribe
result = sentinel_scribe.read_compacted_transcript("/nonexistent/path.jsonl")
assert result == ""
def test_build_transcript_extraction_prompt():
import sentinel_scribe
transcript_text = "[human] Add login\n[assistant] [tools: Write(src/login.py)]\n[result] → OK\n[human] never use eval"
summary = {"task_scope": "Building auth", "progress": "Started", "current_focus": "Login"}
prompt = sentinel_scribe.build_transcript_extraction_prompt(
transcript_text=transcript_text,
summary=summary,
guidance=None,
)
assert "never use eval" in prompt
assert "Building auth" in prompt
assert "agent_self_correction" in prompt
assert "HUMAN-EXPRESSED RULES" in prompt
def test_build_transcript_extraction_prompt_no_summary():
import sentinel_scribe
transcript_text = "[human] fix the bug"
prompt = sentinel_scribe.build_transcript_extraction_prompt(
transcript_text=transcript_text,
summary=None,
guidance="Focus on security",
)
assert "fix the bug" in prompt
assert "PRIORITY GUIDANCE" in prompt
def test_build_validation_prompt():
import sentinel_scribe
observation = {
"statement": "Never edit billing directly",
"scope_hint": "src/billing",
"trigger_hint": "file_write",
"evidence": "agent tried to edit billing, got corrected",
"source": "user_feedback",
}
existing_rules = [
{"id": "no-eval", "trigger": "file_write", "scope": ["**"], "prompt": "Check for eval usage"}
]
matched_files = ["src/billing/invoice.ts", "src/billing/payment.ts"]
prompt = sentinel_scribe.build_validation_prompt(
observation=observation,
existing_rules=existing_rules,
matched_files=matched_files,
)
assert "Never edit billing directly" in prompt
assert "no-eval" in prompt
assert "src/billing/invoice.ts" in prompt
assert "redundant" in prompt.lower()
def test_parse_validation_response_redundant():
import sentinel_scribe
response = '{"redundant": true, "reason": "Already covered by no-billing-edits rule"}'
result = sentinel_scribe.parse_validation_response(response)
assert result is not None
assert result["redundant"] is True
def test_parse_validation_response_new_rule():
import sentinel_scribe
response = """id: no-billing-edits
trigger: file_write
severity: block
scope:
- "src/billing/**"
prompt: |
Test {{file_path}}
"""
result = sentinel_scribe.parse_validation_response(response)
assert result is not None
assert result.get("redundant") is not True
assert result["rule"]["id"] == "no-billing-edits"
assert result["rule"]["prompt"] is not None
def test_parse_validation_response_malformed():
import sentinel_scribe
result = sentinel_scribe.parse_validation_response("garbage output")
assert result is None
def test_reflect_pipeline_extracts_and_drafts(tmp_path, config_dir):
"""Full --reflect pipeline: extract from transcript, validate, write draft."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
entries = [
{"type": "user", "message": {"role": "user", "content": "Add a login page"}, "timestamp": "T1"},
{"type": "assistant", "message": {"role": "assistant", "content": [
{"type": "tool_use", "id": "tu_1", "name": "Bash", "input": {"command": "npm test"}}
]}, "timestamp": "T2"},
{"type": "user", "message": {"role": "user", "content": json.dumps([
{"tool_use_id": "tu_1", "type": "tool_result", "is_error": True, "content": "Error: eval is not allowed"}
])}, "timestamp": "T3"},
{"type": "assistant", "message": {"role": "assistant", "content": [
{"type": "text", "text": "I see, eval is forbidden. Let me fix this."}
]}, "timestamp": "T4"},
]
with open(transcript, "w") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
config = sentinel_scribe.load_config(config_dir)
scribe_dir = str(tmp_path / "scribe")
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
extraction_response = json.dumps({"conventions": [{
"statement": "Never use eval() in this codebase",
"scope_hint": "**",
"trigger_hint": "file_write",
"confidence": 0.9,
"evidence": "eval is not allowed",
"source": "agent_self_correction",
}]})
validation_response = """id: no-eval-usage
trigger: file_write
severity: block
scope:
- "**"
prompt: |
Check if this file uses eval(). File: {{file_path}}
Content: {{content_snippet}}
Respond ONLY with JSON: {"violation": true/false, "confidence": 0.0-1.0, "reason": "one line"}
"""
call_count = {"n": 0}
def mock_ollama(prompt, system_prompt, model, backend, cfg, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return extraction_response
return validation_response
with patch.object(sentinel_scribe, "call_llm", side_effect=mock_ollama):
with patch("sentinel_lock.acquire_lock", return_value=99):
with patch("sentinel_lock.release_lock"):
sentinel_scribe.reflect(
transcript_path=str(transcript),
session_id="test-session",
config=config,
config_dir=config_dir,
scribe_dir=scribe_dir,
session_dir=session_dir,
)
# Should have stored observation
obs_path = os.path.join(scribe_dir, "observations.jsonl")
assert os.path.exists(obs_path)
with open(obs_path) as f:
obs = json.loads(f.readline())
assert obs["statement"] == "Never use eval() in this codebase"
assert obs["source"] == "agent_self_correction"
# Should have written draft
drafts_dir = os.path.join(config_dir, "drafts")
draft_files = [f for f in os.listdir(drafts_dir) if f.endswith(".draft.yaml")]
assert len(draft_files) == 1
with open(os.path.join(drafts_dir, draft_files[0])) as f:
draft = yaml.safe_load(f)
assert draft["_draft"]["source"] == "agent_self_correction"
def test_reflect_skips_redundant_conventions(tmp_path, config_dir):
"""Should not write draft if validation says redundant."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
entries = [
{"type": "user", "message": {"role": "user", "content": "never use eval"}, "timestamp": "T1"},
]
with open(transcript, "w") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
# Create an existing rule
rules_dir = os.path.join(config_dir, "rules")
with open(os.path.join(rules_dir, "no-eval.yaml"), "w") as f:
yaml.dump({"id": "no-eval", "trigger": "file_write", "scope": ["**"], "prompt": "no eval"}, f)
config = sentinel_scribe.load_config(config_dir)
scribe_dir = str(tmp_path / "scribe")
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
extraction_response = json.dumps({"conventions": [{
"statement": "Do not use eval",
"scope_hint": "**",
"trigger_hint": "file_write",
"confidence": 0.9,
"evidence": "never use eval",
"source": "user_feedback",
}]})
validation_response = '{"redundant": true, "reason": "Covered by existing no-eval rule"}'
call_count = {"n": 0}
def mock_ollama(prompt, system_prompt, model, backend, cfg, **kwargs):
call_count["n"] += 1
if call_count["n"] == 1:
return extraction_response
return validation_response
with patch.object(sentinel_scribe, "call_llm", side_effect=mock_ollama):
with patch("sentinel_lock.acquire_lock", return_value=99):
with patch("sentinel_lock.release_lock"):
sentinel_scribe.reflect(
transcript_path=str(transcript),
session_id="test-session",
config=config,
config_dir=config_dir,
scribe_dir=scribe_dir,
session_dir=session_dir,
)
# Should have stored observation but NOT written draft
obs_path = os.path.join(scribe_dir, "observations.jsonl")
assert os.path.exists(obs_path)
drafts_dir = os.path.join(config_dir, "drafts")
draft_files = [f for f in os.listdir(drafts_dir) if f.endswith(".draft.yaml")]
assert len(draft_files) == 0
def test_reflect_no_conventions(tmp_path, config_dir):
"""Should do nothing when no conventions extracted."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
entries = [
{"type": "user", "message": {"role": "user", "content": "add a login page"}, "timestamp": "T1"},
]
with open(transcript, "w") as f:
for e in entries:
f.write(json.dumps(e) + "\n")
config = sentinel_scribe.load_config(config_dir)
scribe_dir = str(tmp_path / "scribe")
session_dir = str(tmp_path / "sessions" / "test")
os.makedirs(session_dir, exist_ok=True)
with patch.object(sentinel_scribe, "call_llm", return_value='{"conventions": []}'):
with patch("sentinel_lock.acquire_lock", return_value=99):
with patch("sentinel_lock.release_lock"):
sentinel_scribe.reflect(
transcript_path=str(transcript),
session_id="test-session",
config=config,
config_dir=config_dir,
scribe_dir=scribe_dir,
session_dir=session_dir,
)
obs_path = os.path.join(scribe_dir, "observations.jsonl")
assert not os.path.exists(obs_path)
def test_main_reflect_mode(tmp_path, config_dir, monkeypatch):
"""--reflect mode should invoke reflect() with transcript from stdin."""
import sentinel_scribe
transcript = tmp_path / "transcript.jsonl"
with open(transcript, "w") as f:
f.write(json.dumps({"type": "user", "message": {"role": "user", "content": "hello"}, "timestamp": "T1"}) + "\n")
stdin_data = json.dumps({
"session_id": "test-session",
"transcript_path": str(transcript),
})
monkeypatch.setattr("sys.argv", ["sentinel_scribe.py", "--reflect"])
monkeypatch.setattr("sys.stdin", __import__("io").StringIO(stdin_data))
monkeypatch.setenv("SENTINEL_CONFIG_DIR", config_dir)
reflect_called = {"called": False}
def mock_reflect(**kwargs):
reflect_called["called"] = True
assert kwargs["session_id"] == "test-session"
assert kwargs["transcript_path"] == str(transcript)
monkeypatch.setattr(sentinel_scribe, "reflect", mock_reflect)
with pytest.raises(SystemExit) as exc_info:
sentinel_scribe.main()
assert exc_info.value.code == 0
assert reflect_called["called"]