-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathutils.py
More file actions
1597 lines (1335 loc) · 60.6 KB
/
utils.py
File metadata and controls
1597 lines (1335 loc) · 60.6 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parent
TEMPLATE_REGISTRY_PATH = REPO_ROOT / "templates" / "registry.yaml"
DEFAULT_VENUE = "neurips_2025"
MAX_STAGE_ATTEMPTS = 5
@dataclass(frozen=True)
class StageSpec:
number: int
slug: str
display_name: str
@property
def filename(self) -> str:
return f"{self.slug}.md"
@property
def stage_title(self) -> str:
return f"Stage {self.number:02d}: {self.display_name}"
@dataclass(frozen=True)
class RunPaths:
run_root: Path
user_input: Path
memory: Path
run_config: Path
run_manifest: Path
artifact_index: Path
logs: Path
logs_raw: Path
prompt_cache_dir: Path
operator_state_dir: Path
stages_dir: Path
handoff_dir: Path
workspace_root: Path
literature_dir: Path
code_dir: Path
data_dir: Path
results_dir: Path
experiment_manifest: Path
hypothesis_manifest: Path
writing_dir: Path
figures_dir: Path
artifacts_dir: Path
notes_dir: Path
reviews_dir: Path
bootstrap_dir: Path
profile_dir: Path
intake_context: Path
def stage_file(self, stage: StageSpec) -> Path:
return self.stages_dir / stage.filename
def stage_tmp_file(self, stage: StageSpec) -> Path:
return self.stages_dir / f"{stage.slug}.tmp.md"
def stage_session_file(self, stage: StageSpec) -> Path:
return self.operator_state_dir / f"{stage.slug}.session_id.txt"
def stage_session_state_file(self, stage: StageSpec) -> Path:
return self.operator_state_dir / f"{stage.slug}.session.json"
def stage_attempt_state_file(self, stage: StageSpec, attempt_no: int) -> Path:
return self.operator_state_dir / f"{stage.slug}.attempt_{attempt_no:02d}.json"
def stage_execution_marker_file(self, stage: StageSpec) -> Path:
return self.operator_state_dir / f"{stage.slug}.started_at.txt"
@dataclass(frozen=True)
class OperatorResult:
success: bool
exit_code: int
stdout: str
stderr: str
stage_file_path: Path
session_id: str | None = None
INTAKE_STAGE = StageSpec(0, "00_intake", "Research Intake")
STAGES: list[StageSpec] = [
StageSpec(1, "01_literature_survey", "Literature Survey"),
StageSpec(2, "02_hypothesis_generation", "Hypothesis Generation"),
StageSpec(3, "03_study_design", "Study Design"),
StageSpec(4, "04_implementation", "Implementation"),
StageSpec(5, "05_experimentation", "Experimentation"),
StageSpec(6, "06_analysis", "Analysis"),
StageSpec(7, "07_writing", "Writing"),
StageSpec(8, "08_dissemination", "Dissemination"),
]
REQUIRED_STAGE_HEADINGS = [
"Objective",
"Previously Approved Stage Summaries",
"What I Did",
"Key Results",
"Files Produced",
"Decision Ledger",
"Suggestions for Refinement",
"Your Options",
]
FIXED_STAGE_OPTIONS = [
"1. Use suggestion 1",
"2. Use suggestion 2",
"3. Use suggestion 3",
"4. Refine with your own feedback",
"5. Approve and continue",
"6. Abort",
]
APPROVED_STAGE_ENTRY_PATTERN = re.compile(r"^#{1,6}\s*Stage\s+(\d{2}):.*$", flags=re.MULTILINE)
DEFAULT_REFINEMENT_SUGGESTIONS = [
"Tighten the scope or decision criteria for this stage before continuing.",
"Strengthen the evidence quality, artifacts, or justification produced in this stage.",
"Clarify the main risks, assumptions, and next-step implications before continuing.",
]
PLACEHOLDER_PATTERNS = [
r"\[in progress[^\]]*\]",
r"\[pending[^\]]*\]",
r"\[todo[^\]]*\]",
r"\[to be determined[^\]]*\]",
r"\[placeholder[^\]]*\]",
r"\[to be populated[^\]]*\]",
]
MACHINE_DATA_SUFFIXES = {".json", ".jsonl", ".csv", ".tsv", ".parquet", ".yaml", ".yml"}
RESULT_SUFFIXES = {".json", ".jsonl", ".csv", ".tsv", ".parquet", ".npz", ".npy"}
FIGURE_SUFFIXES = {".png", ".pdf", ".svg", ".jpg", ".jpeg"}
LATEX_SUFFIXES = {".tex"}
PDF_SUFFIXES = {".pdf"}
BIB_SUFFIXES = {".bib"}
TYPED_HYPOTHESIS_HEADINGS = [
"Theoretical Propositions",
"Empirical Hypotheses",
"Paper Claims (Provisional)",
]
def create_run_root(runs_dir: Path) -> Path:
runs_dir.mkdir(parents=True, exist_ok=True)
base = datetime.now().strftime("%Y%m%d_%H%M%S")
candidate = runs_dir / base
counter = 1
while candidate.exists():
candidate = runs_dir / f"{base}_{counter:02d}"
counter += 1
return candidate
def build_run_paths(run_root: Path) -> RunPaths:
workspace_root = run_root / "workspace"
return RunPaths(
run_root=run_root,
user_input=run_root / "user_input.txt",
memory=run_root / "memory.md",
run_config=run_root / "run_config.json",
run_manifest=run_root / "run_manifest.json",
artifact_index=run_root / "artifact_index.json",
logs=run_root / "logs.txt",
logs_raw=run_root / "logs_raw.jsonl",
prompt_cache_dir=run_root / "prompt_cache",
operator_state_dir=run_root / "operator_state",
stages_dir=run_root / "stages",
handoff_dir=run_root / "handoff",
workspace_root=workspace_root,
literature_dir=workspace_root / "literature",
code_dir=workspace_root / "code",
data_dir=workspace_root / "data",
results_dir=workspace_root / "results",
experiment_manifest=workspace_root / "results" / "experiment_manifest.json",
hypothesis_manifest=workspace_root / "notes" / "hypothesis_manifest.json",
writing_dir=workspace_root / "writing",
figures_dir=workspace_root / "figures",
artifacts_dir=workspace_root / "artifacts",
notes_dir=workspace_root / "notes",
reviews_dir=workspace_root / "reviews",
bootstrap_dir=workspace_root / "bootstrap",
profile_dir=workspace_root / "profile",
intake_context=run_root / "intake_context.json",
)
def ensure_run_layout(paths: RunPaths) -> None:
paths.run_root.mkdir(parents=True, exist_ok=True)
paths.prompt_cache_dir.mkdir(parents=True, exist_ok=True)
paths.operator_state_dir.mkdir(parents=True, exist_ok=True)
paths.stages_dir.mkdir(parents=True, exist_ok=True)
paths.handoff_dir.mkdir(parents=True, exist_ok=True)
paths.workspace_root.mkdir(parents=True, exist_ok=True)
for directory in workspace_dirs(paths):
directory.mkdir(parents=True, exist_ok=True)
for file_path in (paths.user_input, paths.memory, paths.logs, paths.logs_raw):
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.touch(exist_ok=True)
def workspace_dirs(paths: RunPaths) -> list[Path]:
return [
paths.literature_dir,
paths.code_dir,
paths.data_dir,
paths.results_dir,
paths.writing_dir,
paths.figures_dir,
paths.artifacts_dir,
paths.notes_dir,
paths.reviews_dir,
paths.bootstrap_dir,
paths.profile_dir,
]
def write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text.rstrip() + "\n", encoding="utf-8")
def read_text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def append_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(text)
def append_log_entry(log_path: Path, heading: str, body: str) -> None:
timestamp = datetime.now().isoformat(timespec="seconds")
entry = f"\n=== {timestamp} | {heading} ===\n{body.rstrip()}\n"
append_text(log_path, entry)
def append_jsonl(path: Path, payload: dict[str, Any]) -> None:
append_text(path, json.dumps(payload, ensure_ascii=True) + "\n")
def initialize_memory(paths: RunPaths, user_goal: str, intake_summary: str | None = None) -> None:
write_text(paths.memory, build_memory_text(user_goal, [], intake_summary=intake_summary))
def initialize_run_config(
paths: RunPaths,
model: str,
venue: str | None = None,
operator: str = "claude",
approval_mode: str = "manual",
review_operator: str | None = None,
review_model: str | None = None,
) -> dict[str, Any]:
normalized_operator = operator.strip().lower() if operator.strip() else "claude"
normalized_review_operator = (
review_operator.strip().lower()
if isinstance(review_operator, str) and review_operator.strip()
else normalized_operator
)
selected_venue = resolve_venue_key(venue)
config = {
"model": model,
"operator": normalized_operator,
"venue": selected_venue,
"approval_mode": "agent" if approval_mode == "agent" else "manual",
"review_operator": normalized_review_operator,
"review_model": str(
review_model
or ("default" if normalized_review_operator == "codex" else "sonnet")
),
"created_at": datetime.now().isoformat(timespec="seconds"),
}
write_text(paths.run_config, json.dumps(config, indent=2, ensure_ascii=False))
return config
def load_run_config(paths: RunPaths) -> dict[str, Any]:
if not paths.run_config.exists():
return {
"model": "unknown",
"operator": "claude",
"venue": DEFAULT_VENUE,
"approval_mode": "manual",
"review_operator": "claude",
"review_model": "sonnet",
}
try:
payload = json.loads(read_text(paths.run_config))
except json.JSONDecodeError:
return {
"model": "unknown",
"operator": "claude",
"venue": DEFAULT_VENUE,
"approval_mode": "manual",
"review_operator": "claude",
"review_model": "sonnet",
}
if not isinstance(payload, dict):
return {
"model": "unknown",
"operator": "claude",
"venue": DEFAULT_VENUE,
"approval_mode": "manual",
"review_operator": "claude",
"review_model": "sonnet",
}
model = payload.get("model")
operator = payload.get("operator")
venue = payload.get("venue")
normalized_operator = operator.strip().lower() if isinstance(operator, str) and operator.strip() else "claude"
review_operator = payload.get("review_operator")
normalized_review_operator = (
review_operator.strip().lower()
if isinstance(review_operator, str) and review_operator.strip()
else normalized_operator
)
review_model = payload.get("review_model")
approval_mode = payload.get("approval_mode")
config = {
"model": model if isinstance(model, str) and model.strip() else "unknown",
"operator": normalized_operator,
"venue": resolve_venue_key(venue if isinstance(venue, str) else None),
"approval_mode": "agent" if approval_mode == "agent" else "manual",
"review_operator": normalized_review_operator,
"review_model": (
review_model.strip()
if isinstance(review_model, str) and review_model.strip()
else ("default" if normalized_review_operator == "codex" else "sonnet")
),
}
created_at = payload.get("created_at")
if isinstance(created_at, str) and created_at.strip():
config["created_at"] = created_at
return config
def save_run_config(paths: RunPaths, config: dict[str, Any]) -> None:
normalized_operator = str(config.get("operator") or "claude").strip().lower() or "claude"
normalized_review_operator = str(
config.get("review_operator") or normalized_operator
).strip().lower() or normalized_operator
normalized = {
"model": str(config.get("model") or "unknown"),
"operator": normalized_operator,
"venue": resolve_venue_key(str(config.get("venue") or DEFAULT_VENUE)),
"approval_mode": "agent" if config.get("approval_mode") == "agent" else "manual",
"review_operator": normalized_review_operator,
"review_model": str(
config.get("review_model")
or ("default" if normalized_review_operator == "codex" else "sonnet")
),
}
created_at = config.get("created_at")
if isinstance(created_at, str) and created_at.strip():
normalized["created_at"] = created_at
else:
normalized["created_at"] = datetime.now().isoformat(timespec="seconds")
write_text(paths.run_config, json.dumps(normalized, indent=2, ensure_ascii=False))
def ensure_run_config(
paths: RunPaths,
model: str | None = None,
venue: str | None = None,
operator: str | None = None,
approval_mode: str | None = None,
review_operator: str | None = None,
review_model: str | None = None,
) -> dict[str, Any]:
current = load_run_config(paths)
effective_operator = operator or current.get("operator") or "claude"
effective_review_operator = review_operator or current.get("review_operator") or effective_operator
updated = {
"model": model or current.get("model") or "unknown",
"operator": effective_operator,
"venue": resolve_venue_key(venue or current.get("venue")),
"approval_mode": approval_mode or current.get("approval_mode") or "manual",
"review_operator": effective_review_operator,
"review_model": review_model or current.get("review_model") or (
"default" if effective_review_operator == "codex" else "sonnet"
),
"created_at": current.get("created_at") or datetime.now().isoformat(timespec="seconds"),
}
save_run_config(paths, updated)
return updated
def selected_venue_key(paths: RunPaths) -> str:
config = load_run_config(paths)
return resolve_venue_key(config.get("venue") if isinstance(config.get("venue"), str) else None)
def selected_venue_profile(paths: RunPaths) -> dict[str, str]:
registry = _load_template_registry()
venue_key = selected_venue_key(paths)
metadata = registry.get(venue_key, {})
profile = dict(metadata)
profile["venue_key"] = venue_key
profile.setdefault("display_name", venue_key)
profile.setdefault("venue_type", "conference")
return profile
def format_venue_for_prompt(paths: RunPaths) -> str:
profile = selected_venue_profile(paths)
lines = [
f"- target venue key: `{profile['venue_key']}`",
f"- display name: {profile.get('display_name', profile['venue_key'])}",
f"- venue type: {profile.get('venue_type', 'conference')}",
]
if profile.get("page_limit"):
lines.append(f"- nominal page limit: {profile['page_limit']}")
if profile.get("citation_style"):
lines.append(f"- citation style: {profile['citation_style']}")
if profile.get("style_package"):
lines.append(f"- preferred style package: `{profile['style_package']}`")
lines.append(f"- run config: `{paths.run_config.resolve()}`")
return "\n".join(lines)
def load_prompt_template(prompt_dir: Path, stage: StageSpec) -> str:
template_path = prompt_dir / stage.filename
if not template_path.exists():
raise FileNotFoundError(f"Missing prompt template: {template_path}")
return read_text(template_path)
def format_stage_template(template: str, stage: StageSpec, paths: RunPaths) -> str:
replacements = {
"{{STAGE_NUMBER}}": f"{stage.number:02d}",
"{{STAGE_SLUG}}": stage.slug,
"{{STAGE_NAME}}": stage.display_name,
"{{RUN_ROOT}}": str(paths.run_root.resolve()),
"{{USER_INPUT_PATH}}": str(paths.user_input.resolve()),
"{{MEMORY_PATH}}": str(paths.memory.resolve()),
"{{RUN_CONFIG_PATH}}": str(paths.run_config.resolve()),
"{{LOGS_PATH}}": str(paths.logs.resolve()),
"{{LOGS_RAW_PATH}}": str(paths.logs_raw.resolve()),
"{{STAGE_OUTPUT_PATH}}": str(paths.stage_tmp_file(stage).resolve()),
"{{STAGE_FINAL_OUTPUT_PATH}}": str(paths.stage_file(stage).resolve()),
"{{WORKSPACE_ROOT}}": str(paths.workspace_root.resolve()),
"{{WORKSPACE_LITERATURE_DIR}}": str(paths.literature_dir.resolve()),
"{{WORKSPACE_CODE_DIR}}": str(paths.code_dir.resolve()),
"{{WORKSPACE_DATA_DIR}}": str(paths.data_dir.resolve()),
"{{WORKSPACE_RESULTS_DIR}}": str(paths.results_dir.resolve()),
"{{WORKSPACE_WRITING_DIR}}": str(paths.writing_dir.resolve()),
"{{WORKSPACE_FIGURES_DIR}}": str(paths.figures_dir.resolve()),
"{{WORKSPACE_ARTIFACTS_DIR}}": str(paths.artifacts_dir.resolve()),
"{{WORKSPACE_NOTES_DIR}}": str(paths.notes_dir.resolve()),
"{{WORKSPACE_REVIEWS_DIR}}": str(paths.reviews_dir.resolve()),
"{{WORKSPACE_BOOTSTRAP_DIR}}": str(paths.bootstrap_dir.resolve()),
"{{WORKSPACE_PROFILE_DIR}}": str(paths.profile_dir.resolve()),
"{{SELECTED_VENUE}}": selected_venue_key(paths),
}
formatted = template
for placeholder, value in replacements.items():
formatted = formatted.replace(placeholder, value)
return formatted
def required_stage_output_template(stage: StageSpec) -> str:
return (
f"# Stage {stage.number:02d}: {stage.display_name}\n\n"
"## Objective\n"
"[State the exact objective of this stage.]\n\n"
"## Previously Approved Stage Summaries\n"
"[Summarize approved earlier stages from memory, or write _None yet._]\n\n"
"## What I Did\n"
"[Describe what you actually did in this stage.]\n\n"
"## Key Results\n"
"[Present the main results, findings, conclusions, or concrete outputs for this stage.]\n\n"
"## Files Produced\n"
"- `[relative/path]` - [what it contains]\n\n"
"## Decision Ledger\n"
"- **Open Questions**: [unresolved questions to carry forward to later stages]\n"
"- **Locked Decisions**: [design or method decisions made in this stage, with rationale]\n"
"- **Assumptions**: [accepted assumptions that downstream stages must respect]\n"
"- **Rejected Alternatives**: [what was considered and why it was dropped]\n\n"
"## Suggestions for Refinement\n"
"1. [Suggestion 1]\n"
"2. [Suggestion 2]\n"
"3. [Suggestion 3]\n\n"
"## Your Options\n"
+ "\n".join(FIXED_STAGE_OPTIONS)
)
def build_prompt(
stage: StageSpec,
stage_template: str,
user_request: str,
approved_memory: str,
handoff_context: str = "",
revision_feedback: str | None = None,
intake_context_text: str | None = None,
) -> str:
sections = [
"# Stage Instructions",
stage_template.strip(),
"# Required Stage Summary Format",
(
"You must create or overwrite the stage summary markdown file using exactly the "
"top-level heading order below. Do not omit any section. Use exactly 3 numbered "
"refinement suggestions and exactly the fixed 6 option lines."
),
"```md\n" + required_stage_output_template(stage).strip() + "\n```",
"# Execution Discipline",
(
"1. The stage output path is a temporary draft path for the current attempt, not the final approved stage file.\n"
"2. The final approved stage file will be promoted separately by the workflow manager after validation.\n"
"3. Do not write half-finished, in-progress, placeholder, outline-only, or pending content to the stage output file.\n"
"4. If you need scratch work, drafts, notes, or temporary checkpoints, write them under the workspace directories instead of the stage output file.\n"
"5. Only write or overwrite the stage output file once you are ready to produce a complete stage summary for the current attempt.\n"
"6. If any tool, search, or subtask fails, still finish the stage by writing the best complete summary you can, clearly marking limitations in prose rather than leaving placeholders.\n"
"7. Read the stage output file back before finishing and verify every required heading is present and fully filled.\n"
"8. Do not leave placeholder text such as [In progress], [Pending], [TODO], [TBD], or similar unfinished in the final file.\n"
"9. Never leave the stage without a valid stage summary markdown file at the temporary output path."
),
"# Original User Request",
user_request.strip(),
]
if intake_context_text:
sections.extend([
"# Intake Context (User-Provided Resources and Clarifications)",
intake_context_text.strip(),
])
sections.extend([
"# Approved Memory",
approved_memory.strip() or "_None yet._",
"# Stage Handoff Context",
handoff_context.strip() or "No stage handoff summaries available yet.",
"# Revision Feedback",
revision_feedback.strip() if revision_feedback else "None.",
])
return "\n\n".join(sections).strip() + "\n"
def build_continuation_prompt(
stage: StageSpec,
stage_template: str,
paths: RunPaths,
handoff_context: str,
revision_feedback: str | None,
intake_context_text: str | None = None,
attempt_no: int = 1,
previous_validation_errors: list[str] | None = None,
) -> str:
current_draft = paths.stage_tmp_file(stage)
current_final = paths.stage_file(stage)
sections = [
"# Continue Existing Stage Conversation",
(
f"You are continuing {stage.stage_title} in the same AutoR conversation for this stage. "
"This is an incremental improvement pass inside the current stage, not a fresh restart."
),
"# Stage Instructions",
stage_template.strip(),
"# Required Stage Summary Format",
(
"You must create or overwrite the stage summary markdown file using exactly the "
"top-level heading order below. Do not omit any section. Use exactly 3 numbered "
"refinement suggestions and exactly the fixed 6 option lines."
),
"```md\n" + required_stage_output_template(stage).strip() + "\n```",
"# Continuation Discipline",
(
f"1. Read the current draft at `{current_draft.resolve()}` if it exists.\n"
f"2. Read the last promoted stage summary at `{current_final.resolve()}` if it exists.\n"
f"3. Read approved memory from `{paths.memory.resolve()}` and the original user goal from `{paths.user_input.resolve()}` if needed.\n"
f"4. Read prior handoff summaries under `{paths.handoff_dir.resolve()}` when they exist.\n"
f"4. Treat workspace artifacts already under `{paths.workspace_root.resolve()}` as part of the current stage context and reuse them.\n"
"5. Preserve all valid work already completed in this stage unless the new feedback requires changing it.\n"
"6. Fill the missing pieces, fix weak points, and update the stage summary instead of throwing away correct work.\n"
"7. Overwrite only the draft stage output path once you are ready to produce the updated complete summary.\n"
"8. Do not leave placeholder text such as [In progress], [Pending], [TODO], [TBD], or similar unfinished markers.\n"
"9. If the existing stage work is partially correct, keep the correct parts and extend them rather than replacing them blindly.\n"
"10. **Revision Delta**: Because this is a refinement pass, you MUST insert a `## Revision Delta` section "
"immediately after the top-level `# Stage ...` heading and before `## Objective`. "
"This section must contain a concise bullet-point summary of what you changed in this attempt compared to the previous version. Include:\n"
" - Which sections were modified and how\n"
" - Any files added, removed, or changed\n"
" - A one-sentence summary of the overall improvement\n"
"This block is for the human reviewer only and will be stripped before the stage summary is saved."
),
]
if intake_context_text:
sections.extend([
"# Intake Context (User-Provided Resources and Clarifications)",
intake_context_text.strip(),
])
if attempt_no >= 3 and previous_validation_errors:
error_list = "\n".join(f"- {e}" for e in previous_validation_errors)
sections.extend([
"# Recovery Context",
(
f"This is attempt {attempt_no}. The following validation errors have persisted "
f"from the previous attempt:\n{error_list}\n\n"
"If you believe these errors cannot be resolved within the current stage "
"(e.g. missing external files, impossible constraints), state that clearly "
"in your stage summary under ## What I Did so the human reviewer can decide "
"how to proceed."
),
])
sections.extend([
"# Stage Handoff Context",
handoff_context.strip() or "No stage handoff summaries available yet.",
"# New Feedback",
revision_feedback.strip()
if revision_feedback
else "Continue improving the current stage output and fix the issues from the previous attempt.",
])
return "\n\n".join(sections).strip() + "\n"
def truncate_text(text: str, max_chars: int = 12000) -> str:
stripped = text.strip()
if len(stripped) <= max_chars:
return stripped
return stripped[: max_chars - 3].rstrip() + "..."
def extract_markdown_section(markdown: str, heading: str) -> str | None:
pattern = re.compile(
rf"^## {re.escape(heading)}\s*$\n?(.*?)(?=^## |\Z)",
flags=re.MULTILINE | re.DOTALL,
)
match = pattern.search(markdown)
if not match:
return None
return match.group(1).strip()
def strip_markdown_section(markdown: str, heading: str) -> str:
pattern = re.compile(
rf"^## {re.escape(heading)}\s*$\n?(.*?)(?=^## |\Z)",
flags=re.MULTILINE | re.DOTALL,
)
stripped = pattern.sub("", markdown)
return re.sub(r"\n{3,}", "\n\n", stripped).strip()
def parse_numbered_list(section_text: str) -> dict[int, str]:
items: dict[int, str] = {}
current_id: int | None = None
current_lines: list[str] = []
for raw_line in section_text.splitlines():
line = raw_line.rstrip()
match = re.match(r"^\s*(\d+)\.\s+(.*)$", line)
if match:
if current_lines and current_id is not None:
items[current_id] = " ".join(current_lines).strip()
current_id = int(match.group(1))
current_lines = [match.group(2).strip()]
continue
if current_lines and line.strip():
current_lines.append(line.strip())
if current_lines and current_id is not None:
items[current_id] = " ".join(current_lines).strip()
return items
def parse_numbered_list_sequence(section_text: str) -> list[int]:
sequence: list[int] = []
for raw_line in section_text.splitlines():
match = re.match(r"^\s*(\d+)\.\s+(.*)$", raw_line.rstrip())
if match:
sequence.append(int(match.group(1)))
return sequence
def parse_refinement_suggestions(markdown: str) -> list[str]:
section = extract_markdown_section(markdown, "Suggestions for Refinement")
if section is None:
raise ValueError("Missing 'Suggestions for Refinement' section.")
items = parse_numbered_list(section)
missing = [number for number in (1, 2, 3) if number not in items]
if missing:
raise ValueError(f"Missing refinement suggestion(s): {missing}")
return [items[1], items[2], items[3]]
_REVISION_DELTA_RE = re.compile(
r"^## Revision Delta\s*\n(.*?)(?=^## |\Z)",
flags=re.MULTILINE | re.DOTALL,
)
def extract_revision_delta(markdown: str) -> str | None:
"""Extract the Revision Delta section content from stage markdown.
Returns the delta text if present, or None if the section is absent.
"""
match = _REVISION_DELTA_RE.search(markdown)
if not match:
return None
return match.group(1).strip() or None
def strip_revision_delta(markdown: str) -> str:
"""Remove the Revision Delta section from stage markdown.
Returns the markdown with the delta block stripped so it is not persisted
in the final stage summary.
"""
stripped = _REVISION_DELTA_RE.sub("", markdown)
# Collapse any triple-or-more blank lines left behind
stripped = re.sub(r"\n{3,}", "\n\n", stripped)
return stripped
def contains_placeholder_text(text: str) -> bool:
lowered = text.lower()
return any(re.search(pattern, lowered) for pattern in PLACEHOLDER_PATTERNS)
def validate_stage_markdown(
markdown: str,
stage: StageSpec | None = None,
paths: RunPaths | None = None,
) -> list[str]:
problems: list[str] = []
lines = markdown.splitlines()
first_nonempty_line = next((line.strip() for line in lines if line.strip()), "")
if not markdown.startswith("# Stage "):
problems.append("Stage markdown must begin with '# Stage '.")
elif stage is not None and first_nonempty_line != f"# {stage.stage_title}":
problems.append(f"Stage markdown title must be exactly '# {stage.stage_title}'.")
for heading in REQUIRED_STAGE_HEADINGS:
section = extract_markdown_section(markdown, heading)
if section is None:
problems.append(f"Missing required section: {heading}")
continue
if contains_placeholder_text(section):
problems.append(f"Section '{heading}' still contains placeholder text.")
if heading == "Files Produced":
listed_files = _extract_path_references(section)
if not listed_files:
problems.append("Section 'Files Produced' must list at least one concrete file path.")
elif paths is not None:
missing_files = [
file_ref
for file_ref in listed_files
if not _listed_file_exists(paths.run_root, file_ref)
]
if missing_files:
problems.append(
"Section 'Files Produced' references missing file(s): "
+ ", ".join(f"`{path}`" for path in missing_files)
)
elif heading == "Decision Ledger":
required_keywords = [
"Open Questions",
"Locked Decisions",
"Assumptions",
"Rejected Alternatives",
]
if any(keyword not in section for keyword in required_keywords):
problems.append(
"Section 'Decision Ledger' must include Open Questions, Locked Decisions, "
"Assumptions, and Rejected Alternatives."
)
if stage is not None and stage.slug == "02_hypothesis_generation":
hypothesis_sections = extract_typed_hypothesis_sections(markdown)
for heading in TYPED_HYPOTHESIS_HEADINGS:
if heading not in hypothesis_sections:
problems.append(
"Stage 02 'Key Results' must include typed subsections for Theoretical Propositions, "
"Empirical Hypotheses, and Paper Claims (Provisional)."
)
break
identifier_patterns = {
"Theoretical Propositions": r"\*\*T\d+\*\*:",
"Empirical Hypotheses": r"\*\*H\d+\*\*:",
"Paper Claims (Provisional)": r"\*\*C\d+\*\*:",
}
for heading, pattern in identifier_patterns.items():
section = hypothesis_sections.get(heading)
if section is not None and not re.search(pattern, section):
problems.append(
f"Stage 02 subsection '{heading}' must include at least one typed identifier."
)
options_section = extract_markdown_section(markdown, "Your Options")
if options_section is not None:
option_sequence = parse_numbered_list_sequence(options_section)
if option_sequence != [1, 2, 3, 4, 5, 6]:
problems.append("Section 'Your Options' must contain exactly options 1-6 in order with no extras.")
option_items = parse_numbered_list(options_section)
for number in range(1, 7):
if number not in option_items:
problems.append(f"Missing option {number} in 'Your Options'.")
continue
expected_text = FIXED_STAGE_OPTIONS[number - 1].split(". ", 1)[1]
if option_items[number] != expected_text:
problems.append(f"Option {number} in 'Your Options' must be exactly '{expected_text}'.")
suggestions_section = extract_markdown_section(markdown, "Suggestions for Refinement")
if suggestions_section is not None:
suggestion_sequence = parse_numbered_list_sequence(suggestions_section)
if suggestion_sequence != [1, 2, 3]:
problems.append(
"Section 'Suggestions for Refinement' must contain exactly suggestions 1-3 in order with no extras."
)
try:
suggestions = parse_refinement_suggestions(markdown)
if len(suggestions) != 3:
problems.append("Expected exactly 3 refinement suggestions.")
for index, suggestion in enumerate(suggestions, start=1):
if contains_placeholder_text(suggestion):
problems.append(
f"Suggestion {index} in 'Suggestions for Refinement' still contains placeholder text."
)
except ValueError as exc:
problems.append(str(exc))
return problems
def validate_stage_artifacts(stage: StageSpec, paths: RunPaths) -> list[str]:
problems: list[str] = []
freshness_cutoff = stage_execution_started_at(paths, stage)
if stage.number == 1:
from .evidence_ledger import validate_literature_evidence
for problem in validate_literature_evidence(paths):
problems.append(f"{stage.stage_title}: {problem}")
if stage.number >= 3:
if _count_files_with_suffixes(paths.data_dir, MACHINE_DATA_SUFFIXES) == 0:
problems.append(
f"{stage.stage_title} requires machine-readable data artifacts under workspace/data, not only markdown notes."
)
elif stage.number == 3 and freshness_cutoff is not None and not _has_recent_files_with_suffixes(
paths.data_dir, MACHINE_DATA_SUFFIXES, freshness_cutoff
):
problems.append(
f"{stage.stage_title} requires machine-readable data artifacts produced or updated during the current stage execution."
)
if stage.number >= 5:
if _count_files_with_suffixes(paths.results_dir, RESULT_SUFFIXES) == 0:
problems.append(
f"{stage.stage_title} requires machine-readable result artifacts under workspace/results."
)
if not paths.experiment_manifest.exists():
problems.append(
f"{stage.stage_title} requires experiment_manifest.json under workspace/results."
)
else:
from .experiment_manifest import validate_experiment_manifest
for problem in validate_experiment_manifest(paths.experiment_manifest):
problems.append(f"{stage.stage_title}: {problem}")
if stage.number >= 6:
if _count_files_with_suffixes(paths.figures_dir, FIGURE_SUFFIXES) == 0:
problems.append(
f"{stage.stage_title} requires figure artifacts under workspace/figures."
)
elif stage.number == 6 and freshness_cutoff is not None and not _has_recent_files_with_suffixes(
paths.figures_dir, FIGURE_SUFFIXES, freshness_cutoff
):
problems.append(
f"{stage.stage_title} requires figures produced or updated during the current stage execution."
)
if stage.number >= 7:
main_tex = paths.writing_dir / "main.tex"
if not main_tex.exists():
problems.append(
f"{stage.stage_title} requires main.tex under workspace/writing."
)
elif not _looks_like_supported_manuscript(main_tex, selected_venue_key(paths)):
problems.append(
f"{stage.stage_title} requires a supported conference or journal manuscript in workspace/writing/main.tex. "
f"Expected venue: {selected_venue_key(paths)}. Use a matching style package or add a comment such as '% AutoR venue: {selected_venue_key(paths)}' near the top of main.tex."
)
bib_files = [path for path in _existing_files(paths.writing_dir) if path.suffix.lower() in BIB_SUFFIXES]
if not bib_files and not _has_inline_bibliography(paths.writing_dir):
problems.append(
f"{stage.stage_title} requires a .bib file or an inline bibliography in the writing package."
)
sections_dir = paths.writing_dir / "sections"
section_tex_files = list(sections_dir.glob("*.tex")) if sections_dir.exists() else []
if not section_tex_files:
problems.append(
f"{stage.stage_title} requires section .tex files under workspace/writing/sections."
)
pdf_count = _count_files_with_suffixes(paths.writing_dir, PDF_SUFFIXES)
pdf_count += _count_files_with_suffixes(paths.artifacts_dir, PDF_SUFFIXES)
if pdf_count == 0:
problems.append(
f"{stage.stage_title} requires a compiled PDF manuscript under workspace/writing or workspace/artifacts."
)
if not (paths.artifacts_dir / "build_log.txt").exists():
problems.append(
f"{stage.stage_title} requires build_log.txt under workspace/artifacts."
)
if not (paths.artifacts_dir / "citation_verification.json").exists():
problems.append(
f"{stage.stage_title} requires citation_verification.json under workspace/artifacts."
)
else:
from .evidence_ledger import validate_citation_verification
for problem in validate_citation_verification(paths.artifacts_dir / "citation_verification.json"):
problems.append(f"{stage.stage_title}: {problem}")
if not (paths.artifacts_dir / "self_review.json").exists():
problems.append(
f"{stage.stage_title} requires self_review.json under workspace/artifacts."
)
if stage.number == 7 and freshness_cutoff is not None:
stage7_required_files = [
main_tex,
paths.artifacts_dir / "build_log.txt",
paths.artifacts_dir / "citation_verification.json",
paths.artifacts_dir / "self_review.json",
]
if not all(path.exists() and path.stat().st_mtime >= freshness_cutoff for path in stage7_required_files):
problems.append(
f"{stage.stage_title} requires the writing package and build metadata to be produced or updated during the current stage execution."
)
if not _has_recent_files_with_suffixes(paths.writing_dir, PDF_SUFFIXES, freshness_cutoff) and not _has_recent_files_with_suffixes(
paths.artifacts_dir, PDF_SUFFIXES, freshness_cutoff
):
problems.append(
f"{stage.stage_title} requires a manuscript PDF produced or updated during the current stage execution."
)
sections_dir = paths.writing_dir / "sections"
if not _has_recent_files_with_suffixes(sections_dir, LATEX_SUFFIXES, freshness_cutoff):
problems.append(
f"{stage.stage_title} requires section .tex files produced or updated during the current stage execution."
)
if stage.number >= 8:
review_files = _existing_files(paths.reviews_dir)
if not review_files:
problems.append(
f"{stage.stage_title} requires review/readiness artifacts under workspace/reviews."
)
elif freshness_cutoff is not None and not any(path.stat().st_mtime >= freshness_cutoff for path in review_files):
problems.append(
f"{stage.stage_title} requires review/readiness artifacts produced or updated during the current stage execution."
)
return problems
def render_approved_stage_entry(stage: StageSpec, stage_markdown: str) -> str:
objective = extract_markdown_section(stage_markdown, "Objective") or "Not provided."
what_i_did = extract_markdown_section(stage_markdown, "What I Did") or "Not provided."
key_results = extract_markdown_section(stage_markdown, "Key Results") or "Not provided."
files_produced = extract_markdown_section(stage_markdown, "Files Produced") or "Not provided."
return (
f"### {stage.stage_title}\n\n"
"#### Objective\n"
f"{objective}\n\n"
"#### What I Did\n"
f"{what_i_did}\n\n"