-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmanager.py
More file actions
1904 lines (1751 loc) · 80.8 KB
/
manager.py
File metadata and controls
1904 lines (1751 loc) · 80.8 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
from datetime import datetime
import shutil
import sys
from pathlib import Path
from typing import TextIO
from .bootstrap import (
bootstrap_profile_exists,
format_corpus_for_prompt,
format_corpus_stats_for_log,
format_profile_for_prompt,
missing_bootstrap_profile_artifacts,
scan_corpus,
)
from .approval_agent import AutomatedReviewer, ReviewDecision
from .project_bootstrap import (
format_project_context_for_prompt,
format_project_scan_for_prompt,
format_scan_stats_for_log,
load_recommended_entry_stage,
load_stage_assessments,
project_bootstrap_exists,
recommend_entry_stage,
save_project_bootstrap,
save_recommended_entry_stage,
scan_project,
)
from .intake import (
IntakeContext,
ResourceEntry,
format_intake_for_prompt,
format_resources_for_intake_prompt,
ingest_resources,
load_intake_context,
save_intake_context
)
from .artifact_index import format_artifact_index_for_prompt, write_artifact_index
from .experiment_manifest import format_experiment_manifest_for_prompt, write_experiment_manifest
from .hypothesis_manifest import write_hypothesis_manifest
from .manifest import (
ensure_run_manifest,
format_manifest_status,
initialize_run_manifest,
load_run_manifest,
mark_stage_approved_manifest,
mark_stage_failed_manifest,
mark_stage_human_review_manifest,
mark_stage_running_manifest,
rebuild_memory_from_manifest,
rollback_to_stage,
sync_stage_session_id,
update_manifest_run_status,
)
from .operator_protocol import OperatorProtocol
from .diagram_gen import post_writing_diagram_hook
from .terminal_ui import TerminalUI
from .platform.foundry import generate_paper_package, generate_release_package
from .writing_manifest import build_writing_manifest, format_manifest_for_prompt, generate_layout_review
from .utils import (
DEFAULT_REFINEMENT_SUGGESTIONS,
FIXED_STAGE_OPTIONS,
INTAKE_STAGE,
MAX_STAGE_ATTEMPTS,
STAGES,
RunPaths,
StageSpec,
append_approved_stage_summary,
approved_stage_numbers,
approved_stage_summaries,
append_log_entry,
build_decision_ledger_context,
build_handoff_context,
build_hypothesis_context,
build_continuation_prompt,
build_prompt,
build_run_paths,
canonicalize_stage_markdown,
create_run_root,
ensure_run_config,
ensure_run_layout,
format_stage_template,
format_venue_for_prompt,
filtered_approved_memory,
initialize_memory,
initialize_run_config,
load_prompt_template,
mark_stage_execution_started,
extract_revision_delta,
strip_revision_delta,
parse_refinement_suggestions,
read_attempt_count,
read_text,
required_stage_output_template,
truncate_text,
validate_stage_artifacts,
validate_stage_markdown,
write_attempt_count,
write_stage_handoff,
write_text,
)
class ResearchManager:
def __init__(
self,
project_root: Path,
runs_dir: Path,
operator: OperatorProtocol,
output_stream: TextIO = sys.stdout,
ui: TerminalUI | None = None,
reviewer: AutomatedReviewer | None = None,
approval_mode: str = "manual",
review_operator: str | None = None,
review_model: str | None = None,
) -> None:
self.project_root = project_root
self.runs_dir = runs_dir
self.operator = operator
self.reviewer = reviewer
self.prompt_dir = self.project_root / "src" / "prompts"
self.output_stream = output_stream
self.ui = ui or TerminalUI(output_stream=output_stream)
self.approval_mode = "agent" if reviewer is not None else "manual"
if approval_mode == "manual" and reviewer is None:
self.approval_mode = "manual"
self.review_operator = review_operator or getattr(reviewer, "backend_name", getattr(operator, "backend_name", "claude"))
self.review_model = review_model or getattr(reviewer, "model", getattr(operator, "model", "unknown"))
self._redo_start_stage: StageSpec | None = None
self._research_diagram: bool = False
self._jump_target_stage: StageSpec | None = None
def run(
self,
user_goal: str,
venue: str | None = None,
resources: list[ResourceEntry] | None = None,
skip_intake: bool = False,
research_diagram: bool = False,
project_root: Path | None = None,
paper_corpus: Path | None = None,
) -> bool:
self._research_diagram = research_diagram
paths = self._create_run(user_goal, venue=venue, resources=resources)
self.ui.show_run_started(paths.run_root.as_posix(), self.operator.model, venue or "default")
self._announce_approval_mode()
# Run Claude-driven intake stage unless skipped
if not skip_intake:
intake_approved = self._run_intake(paths)
if not intake_approved:
append_log_entry(paths.logs, "run_aborted", "Run aborted during intake.")
update_manifest_run_status(
paths,
run_status="cancelled",
last_event="run.cancelled",
current_stage_slug=INTAKE_STAGE.slug,
)
self.ui.show_status("Run aborted.", level="warn")
return False
# Run project repo bootstrap if provided
bootstrap_start_stage: StageSpec | None = None
if project_root is not None:
bootstrap_result = self._run_project_bootstrap(paths, project_root)
if bootstrap_result is None:
append_log_entry(paths.logs, "run_aborted", "Run aborted during project bootstrap.")
self.ui.show_status("Run aborted.", level="warn")
return False
bootstrap_start_stage = bootstrap_result
# Run bootstrap from paper corpus if provided
if paper_corpus is not None:
bootstrap_approved = self._run_bootstrap(paths, paper_corpus)
if not bootstrap_approved:
append_log_entry(paths.logs, "run_aborted", "Run aborted during bootstrap.")
self.ui.show_status("Run aborted.", level="warn")
return False
return self._run_from_paths(paths, start_stage=bootstrap_start_stage)
def resume_run(
self,
run_root: Path,
start_stage: StageSpec | None = None,
rollback_stage: StageSpec | None = None,
venue: str | None = None,
research_diagram: bool = False,
) -> bool:
self._research_diagram = research_diagram
paths = build_run_paths(run_root)
ensure_run_layout(paths)
config = ensure_run_config(
paths,
model=self.operator.model,
venue=venue,
operator=getattr(self.operator, "backend_name", "claude"),
approval_mode=self.approval_mode,
review_operator=self.review_operator,
review_model=self.review_model,
)
ensure_run_manifest(paths)
if not paths.user_input.exists():
raise FileNotFoundError(f"Missing user_input.txt in run: {run_root}")
if not paths.memory.exists():
raise FileNotFoundError(f"Missing memory.md in run: {run_root}")
if rollback_stage is not None:
self._print(self._format_rollback_preview(paths, rollback_stage))
rollback_to_stage(paths, rollback_stage)
start_stage = rollback_stage
append_log_entry(
paths.logs,
"run_resume",
f"Resumed run at: {paths.run_root}"
+ (f"\nRequested start stage: {start_stage.stage_title}" if start_stage else "")
+ (f"\nRequested rollback stage: {rollback_stage.stage_title}" if rollback_stage else "")
+ f"\nVenue: {config['venue']}",
)
self.ui.show_run_started(
paths.run_root.as_posix(),
self.operator.model,
config["venue"],
resumed=True,
)
self._announce_approval_mode()
if start_stage:
self.ui.show_status(f"Restarting from {start_stage.stage_title}", level="warn")
return self._run_from_paths(paths, start_stage=start_stage)
def _run_from_paths(self, paths: RunPaths, start_stage: StageSpec | None = None) -> bool:
stages_to_run = self._select_stages_for_run(paths, start_stage)
stage_index = 0
while stage_index < len(stages_to_run):
stage = stages_to_run[stage_index]
self._jump_target_stage = None
approved = self._run_stage(paths, stage)
if self._jump_target_stage is not None:
target = self._jump_target_stage
stages_to_run = self._select_stages_for_run(paths, target)
stage_index = 0
continue
if not approved:
append_log_entry(
paths.logs,
"run_aborted",
f"Run aborted during {stage.stage_title}.",
)
update_manifest_run_status(
paths,
run_status="cancelled",
last_event="run.cancelled",
current_stage_slug=stage.slug,
)
self._print("Run aborted.")
return False
stage_index += 1
append_log_entry(paths.logs, "run_complete", "All stages approved.")
update_manifest_run_status(
paths,
run_status="completed",
last_event="run.completed",
current_stage_slug=None,
completed_at=datetime.now().isoformat(timespec="seconds"),
)
self._print("All stages approved. Run complete.")
return True
def _create_run(
self,
user_goal: str,
venue: str | None = None,
resources: list[ResourceEntry] | None = None,
) -> RunPaths:
run_root = create_run_root(self.runs_dir)
paths = build_run_paths(run_root)
ensure_run_layout(paths)
write_text(paths.user_input, user_goal)
# Ingest any pre-provided resources into workspace
intake_summary: str | None = None
if resources:
updated = ingest_resources(resources, paths)
ctx = IntakeContext(goal=user_goal, original_goal=user_goal, resources=updated)
save_intake_context(paths, ctx)
intake_summary = format_intake_for_prompt(ctx)
initialize_memory(paths, user_goal, intake_summary=intake_summary)
config = initialize_run_config(
paths,
model=self.operator.model,
venue=venue,
operator=getattr(self.operator, "backend_name", "claude"),
approval_mode=self.approval_mode,
review_operator=self.review_operator,
review_model=self.review_model,
)
initialize_run_manifest(paths)
write_artifact_index(paths)
write_experiment_manifest(paths)
append_log_entry(paths.logs, "run_start", f"Run root: {paths.run_root}")
append_log_entry(
paths.logs,
"run_config",
(
f"Model: {config['model']}\n"
f"Venue: {config['venue']}\n"
f"Approval mode: {config['approval_mode']}\n"
f"Review backend: {config['review_operator']}\n"
f"Review model: {config['review_model']}"
),
)
return paths
def _select_stages_for_run(
self,
paths: RunPaths,
start_stage: StageSpec | None,
) -> list[StageSpec]:
if start_stage is not None:
return [stage for stage in STAGES if stage.number >= start_stage.number]
manifest = ensure_run_manifest(paths)
pending: list[StageSpec] = []
for stage in STAGES:
entry = next(entry for entry in manifest.stages if entry.slug == stage.slug)
if entry.approved and entry.status == "approved":
continue
pending.append(stage)
return pending
# ------------------------------------------------------------------
# Intake stage (Claude-driven Socratic Q&A, runs before Stage 01)
# ------------------------------------------------------------------
def _run_intake(self, paths: RunPaths) -> bool:
"""Run the Claude-driven intake stage.
Uses the same operator + approval loop pattern as ``_run_stage``
so that Claude generates Socratic questions and the user refines
via the standard suggestion / custom-feedback / approve mechanism.
On approval the intake summary is saved to ``intake_context.json``
and appended to run memory so all downstream stages can see it.
"""
stage = INTAKE_STAGE
# Skip if intake was already approved (e.g. on resume)
intake_stage_file = paths.stage_file(stage)
if intake_stage_file.exists():
self.ui.show_status("Intake already approved, skipping.", level="info")
return True
attempt_no = 1
revision_feedback: str | None = None
continue_session = False
mark_stage_execution_started(paths, stage)
while True:
if attempt_no > MAX_STAGE_ATTEMPTS:
self.ui.show_status(
f"{stage.stage_title} failed after {MAX_STAGE_ATTEMPTS} attempts. Escalating to user.",
level="error",
)
append_log_entry(paths.logs, f"{stage.slug} max_attempts_exceeded",
f"Stopped after {MAX_STAGE_ATTEMPTS} attempts.")
return False
self.ui.show_stage_start(stage.stage_title, attempt_no, continue_session)
prompt = self._build_stage_prompt(paths, stage, revision_feedback, continue_session)
append_log_entry(paths.logs, f"{stage.slug} attempt {attempt_no} prompt", prompt)
result = self.operator.run_stage(stage, prompt, paths, attempt_no, continue_session=continue_session)
append_log_entry(
paths.logs,
f"{stage.slug} attempt {attempt_no} result",
(
f"success: {result.success}\n"
f"exit_code: {result.exit_code}\n"
f"session_id: {result.session_id or '(unknown)'}\n"
f"stage_file_path: {result.stage_file_path}\n\n"
"stdout:\n"
f"{result.stdout or '(empty)'}\n\n"
"stderr:\n"
f"{result.stderr or '(empty)'}"
),
)
# If no stage file was produced, try repair (same as regular stages)
if not result.stage_file_path.exists():
self.ui.show_status(
f"Stage summary draft missing for {stage.stage_title}. Running repair attempt...",
level="warn",
)
repair_result = self.operator.repair_stage_summary(
stage=stage, original_prompt=prompt,
original_result=result, paths=paths, attempt_no=attempt_no,
)
result = repair_result
if not result.stage_file_path.exists():
fallback_text = "\n\n".join(
part for part in [result.stdout, result.stderr] if part
)
result = self._materialize_missing_stage_draft(
paths=paths, stage=stage, attempt_no=attempt_no,
source="intake attempt and repair", fallback_text=fallback_text,
)
stage_markdown = read_text(result.stage_file_path)
# Extract and display revision delta before showing the full summary
delta = extract_revision_delta(stage_markdown)
if delta and attempt_no >= 2:
self.ui.show_revision_delta(delta, attempt_no)
stage_markdown = strip_revision_delta(stage_markdown)
write_text(result.stage_file_path, stage_markdown)
# Show output and let user choose (same approval loop as _run_stage)
suggestions = parse_refinement_suggestions(stage_markdown)
choice, auto_feedback = self._collect_review_decision(
paths=paths,
stage=stage,
attempt_no=attempt_no,
stage_markdown=stage_markdown,
suggestions=suggestions,
)
if choice in {"1", "2", "3"}:
selected = suggestions[int(choice) - 1]
revision_feedback = (
"Continue the current stage conversation and improve the existing work. "
"Do not discard correct completed parts. Address this refinement request:\n"
f"{selected}"
)
continue_session = True
attempt_no += 1
continue
if choice == "4":
custom_feedback = auto_feedback or self._read_multiline_feedback()
revision_feedback = (
"Continue the current stage conversation and improve the existing work. "
"Preserve correct completed parts unless the feedback requires changing them. "
"Address this user feedback:\n"
f"{custom_feedback}"
)
append_log_entry(paths.logs, f"{stage.slug} attempt {attempt_no} custom_feedback", custom_feedback)
continue_session = True
attempt_no += 1
continue
if choice == "5":
# Promote and save intake context
final_path = paths.stage_file(stage)
shutil.copyfile(result.stage_file_path, final_path)
append_log_entry(
paths.logs,
f"{stage.slug} attempt {attempt_no} promoted",
f"Promoted intake summary.\ndraft: {result.stage_file_path}\nfinal: {final_path}",
)
self._save_intake_from_approved_stage(paths, stage_markdown)
self.ui.show_status(f"Approved {stage.stage_title}.", level="success")
return True
if choice == "6":
return False
def _save_intake_from_approved_stage(self, paths: RunPaths, stage_markdown: str) -> None:
"""Persist the approved intake stage output into intake_context.json and memory."""
existing_ctx = load_intake_context(paths)
goal = read_text(paths.user_input).strip()
# Merge: keep any pre-ingested resources, store the stage output as notes
ctx = IntakeContext(
goal=goal,
original_goal=existing_ctx.original_goal if existing_ctx else goal,
resources=existing_ctx.resources if existing_ctx else [],
notes=stage_markdown,
)
save_intake_context(paths, ctx)
# Append intake summary to memory so downstream stages see it
intake_text = format_intake_for_prompt(ctx)
if intake_text:
append_approved_stage_summary(paths.memory, INTAKE_STAGE, stage_markdown)
# ------------------------------------------------------------------
# Project repo bootstrap (scan existing repo → infer stage)
# ------------------------------------------------------------------
PROJECT_BOOTSTRAP_STAGE = StageSpec(number=-1, slug="project_bootstrap", display_name="Project Repo Bootstrap")
def _run_project_bootstrap(self, paths: RunPaths, project_root: Path) -> StageSpec | None:
"""Scan an existing project repo and run Claude to infer project state.
Returns the recommended start StageSpec, or None if the user aborts.
"""
stage = self.PROJECT_BOOTSTRAP_STAGE
if project_bootstrap_exists(paths):
self.ui.show_status("Project bootstrap already exists, skipping scan.", level="info")
entry = load_recommended_entry_stage(paths)
if entry is not None:
for s in STAGES:
if s.number == entry:
return s
self.ui.show_status("Bootstrap entry stage metadata missing. Defaulting to Stage 01.", level="warn")
return STAGES[0]
self.ui.show_status(f"Scanning project repo: {project_root}", level="info")
try:
scan_result = scan_project(project_root)
except (FileNotFoundError, NotADirectoryError) as exc:
self.ui.show_status(f"Project bootstrap error: {exc}", level="error")
return None
self.ui.show_status(
f"Scanned {scan_result.total_files} files. "
f"Code: {scan_result.code_state.status}, "
f"Experiments: {scan_result.experiment_state.status}, "
f"Writing: {scan_result.writing_state.status}. "
f"Heuristic entry: Stage {scan_result.recommended_entry_stage:02d}.",
level="info",
)
append_log_entry(paths.logs, "project_bootstrap_start", format_scan_stats_for_log(scan_result))
save_project_bootstrap(paths, scan_result)
scan_prompt_section = format_project_scan_for_prompt(scan_result)
attempt_no = 1
revision_feedback: str | None = None
continue_session = False
while True:
if attempt_no > MAX_STAGE_ATTEMPTS:
self.ui.show_status(
f"{stage.stage_title} failed after {MAX_STAGE_ATTEMPTS} attempts. Escalating to user.",
level="error",
)
append_log_entry(paths.logs, f"project_bootstrap max_attempts_exceeded",
f"Stopped after {MAX_STAGE_ATTEMPTS} attempts.")
return None
self.ui.show_stage_start(stage.stage_title, attempt_no, continue_session)
prompt = self._build_project_bootstrap_prompt(
paths, stage, scan_prompt_section, project_root, revision_feedback, continue_session,
)
append_log_entry(paths.logs, f"project_bootstrap attempt {attempt_no} prompt", prompt)
result = self.operator.run_stage(stage, prompt, paths, attempt_no, continue_session=continue_session)
append_log_entry(
paths.logs,
f"project_bootstrap attempt {attempt_no} result",
(
f"success: {result.success}\n"
f"session_id: {result.session_id or '(unknown)'}\n"
f"stage_file_path: {result.stage_file_path}\n\n"
"stdout:\n"
f"{result.stdout or '(empty)'}\n\n"
"stderr:\n"
f"{result.stderr or '(empty)'}"
),
)
if not result.stage_file_path.exists():
self.ui.show_status(
"Project bootstrap draft missing. Running repair attempt...",
level="warn",
)
repair_result = self.operator.repair_stage_summary(
stage=stage, original_prompt=prompt,
original_result=result, paths=paths, attempt_no=attempt_no,
)
result = repair_result
if not result.stage_file_path.exists():
fallback_text = "\n\n".join(
part for part in [result.stdout, result.stderr] if part
)
result = self._materialize_missing_stage_draft(
paths=paths, stage=stage, attempt_no=attempt_no,
source="project bootstrap attempt and repair", fallback_text=fallback_text,
)
stage_markdown = read_text(result.stage_file_path)
delta = extract_revision_delta(stage_markdown)
if delta and attempt_no >= 2:
self.ui.show_revision_delta(delta, attempt_no)
stage_markdown = strip_revision_delta(stage_markdown)
write_text(result.stage_file_path, stage_markdown)
suggestions = parse_refinement_suggestions(stage_markdown)
choice, auto_feedback = self._collect_review_decision(
paths=paths,
stage=stage,
attempt_no=attempt_no,
stage_markdown=stage_markdown,
suggestions=suggestions,
)
if choice in {"1", "2", "3"}:
selected = suggestions[int(choice) - 1]
revision_feedback = (
"Continue the project bootstrap conversation and improve the stage assessments. "
"Do not discard correct parts. Address this refinement request:\n"
f"{selected}"
)
continue_session = True
attempt_no += 1
continue
if choice == "4":
custom_feedback = auto_feedback or self._read_multiline_feedback()
revision_feedback = (
"Continue the project bootstrap conversation and improve the stage assessments. "
"Preserve correct parts unless the feedback requires changing them. "
"Address this user feedback:\n"
f"{custom_feedback}"
)
append_log_entry(paths.logs, f"project_bootstrap attempt {attempt_no} custom_feedback", custom_feedback)
continue_session = True
attempt_no += 1
continue
if choice == "5":
final_path = paths.stage_file(stage)
shutil.copyfile(result.stage_file_path, final_path)
append_log_entry(
paths.logs,
"project_bootstrap_promoted",
f"Promoted project bootstrap summary.\ndraft: {result.stage_file_path}\nfinal: {final_path}",
)
corrected_assessments = load_stage_assessments(paths) or scan_result.stage_assessments
entry_stage_num = recommend_entry_stage(corrected_assessments)
save_recommended_entry_stage(paths, entry_stage_num)
self._adopt_project_bootstrap_baseline(paths, corrected_assessments, entry_stage_num)
append_log_entry(paths.logs, "project_bootstrap_approved", "Project bootstrap approved.")
self.ui.show_status("Approved project bootstrap.", level="success")
for s in STAGES:
if s.number == entry_stage_num:
self.ui.show_status(
f"Starting from {s.stage_title} based on project bootstrap.",
level="info",
)
return s
return STAGES[0]
if choice == "6":
return None
# ------------------------------------------------------------------
# Bootstrap stage (paper corpus → researcher profile)
# ------------------------------------------------------------------
BOOTSTRAP_STAGE = StageSpec(number=-1, slug="bootstrap", display_name="Paper Corpus Bootstrap")
def _run_bootstrap(self, paths: RunPaths, corpus_path: Path) -> bool:
"""Scan the user's paper corpus and run Claude to extract a researcher profile.
Uses the same operator + approval loop so the user can review and refine
the extracted profile before downstream stages use it as context.
"""
stage = self.BOOTSTRAP_STAGE
if bootstrap_profile_exists(paths):
self.ui.show_status("Bootstrap profile already exists, skipping.", level="info")
return True
self.ui.show_status(f"Scanning paper corpus: {corpus_path}", level="info")
try:
corpus_manifest = scan_corpus(corpus_path)
except (FileNotFoundError, NotADirectoryError) as exc:
self.ui.show_status(f"Bootstrap error: {exc}", level="error")
return False
if not corpus_manifest.papers:
self.ui.show_status("No extractable files found in paper corpus. Skipping bootstrap.", level="warn")
return True
stats = corpus_manifest.stats
self.ui.show_status(
f"Found {stats['total_papers']} paper(s), {stats['unique_references']} unique references. "
f"Running profile extraction...",
level="info",
)
append_log_entry(paths.logs, "bootstrap_start", format_corpus_stats_for_log(corpus_manifest))
corpus_prompt_section = format_corpus_for_prompt(corpus_manifest)
attempt_no = 1
revision_feedback: str | None = None
continue_session = False
while True:
if attempt_no > MAX_STAGE_ATTEMPTS:
self.ui.show_status(
f"{stage.stage_title} failed after {MAX_STAGE_ATTEMPTS} attempts. Escalating to user.",
level="error",
)
append_log_entry(paths.logs, f"bootstrap max_attempts_exceeded",
f"Stopped after {MAX_STAGE_ATTEMPTS} attempts.")
return False
self.ui.show_stage_start(stage.stage_title, attempt_no, continue_session)
prompt = self._build_bootstrap_prompt(paths, stage, corpus_prompt_section, revision_feedback, continue_session)
append_log_entry(paths.logs, f"bootstrap attempt {attempt_no} prompt", prompt)
result = self.operator.run_stage(stage, prompt, paths, attempt_no, continue_session=continue_session)
append_log_entry(
paths.logs,
f"bootstrap attempt {attempt_no} result",
(
f"success: {result.success}\n"
f"session_id: {result.session_id or '(unknown)'}\n"
f"stage_file_path: {result.stage_file_path}\n\n"
"stdout:\n"
f"{result.stdout or '(empty)'}\n\n"
"stderr:\n"
f"{result.stderr or '(empty)'}"
),
)
if not result.stage_file_path.exists():
self.ui.show_status(
"Bootstrap summary draft missing. Running repair attempt...",
level="warn",
)
repair_result = self.operator.repair_stage_summary(
stage=stage, original_prompt=prompt,
original_result=result, paths=paths, attempt_no=attempt_no,
)
result = repair_result
if not result.stage_file_path.exists():
fallback_text = "\n\n".join(
part for part in [result.stdout, result.stderr] if part
)
result = self._materialize_missing_stage_draft(
paths=paths, stage=stage, attempt_no=attempt_no,
source="bootstrap attempt and repair", fallback_text=fallback_text,
)
stage_markdown = read_text(result.stage_file_path)
suggestions = parse_refinement_suggestions(stage_markdown)
choice, auto_feedback = self._collect_review_decision(
paths=paths,
stage=stage,
attempt_no=attempt_no,
stage_markdown=stage_markdown,
suggestions=suggestions,
)
if choice in {"1", "2", "3"}:
selected = suggestions[int(choice) - 1]
revision_feedback = (
"Continue the bootstrap conversation and improve the researcher profile. "
"Do not discard correct completed parts. Address this refinement request:\n"
f"{selected}"
)
continue_session = True
attempt_no += 1
continue
if choice == "4":
custom_feedback = auto_feedback or self._read_multiline_feedback()
revision_feedback = (
"Continue the bootstrap conversation and improve the researcher profile. "
"Preserve correct parts unless the feedback requires changing them. "
"Address this user feedback:\n"
f"{custom_feedback}"
)
append_log_entry(paths.logs, f"bootstrap attempt {attempt_no} custom_feedback", custom_feedback)
continue_session = True
attempt_no += 1
continue
if choice == "5":
missing_artifacts = missing_bootstrap_profile_artifacts(paths)
if missing_artifacts:
missing_block = "\n".join(f"- {path}" for path in missing_artifacts)
append_log_entry(
paths.logs,
"bootstrap_missing_artifacts",
missing_block,
)
self.ui.show_status(
"Bootstrap profile artifacts are incomplete. Continuing refinement.",
level="warn",
)
revision_feedback = (
"Continue the bootstrap conversation and complete the missing profile artifacts. "
"Do not discard correct completed artifacts. Write the missing files and refresh the stage summary.\n"
f"Missing artifacts:\n{missing_block}"
)
continue_session = True
attempt_no += 1
continue
final_path = paths.stage_file(stage)
shutil.copyfile(result.stage_file_path, final_path)
append_log_entry(paths.logs, "bootstrap_approved", "Bootstrap profile approved.")
append_log_entry(
paths.logs,
"bootstrap_promoted",
f"Promoted bootstrap summary.\ndraft: {result.stage_file_path}\nfinal: {final_path}",
)
self.ui.show_status("Approved bootstrap profile.", level="success")
return True
if choice == "6":
return False
def _adopt_project_bootstrap_baseline(
self,
paths: RunPaths,
assessments,
entry_stage_num: int,
) -> None:
if entry_stage_num <= 1:
return
artifact_paths = self._project_bootstrap_artifact_paths(paths)
assessments_by_number = {assessment.stage_number: assessment for assessment in assessments}
for stage in STAGES:
if stage.number >= entry_stage_num:
break
stage_markdown = self._bootstrap_stage_markdown(
paths,
stage,
assessments_by_number.get(stage.number),
artifact_paths,
)
write_text(paths.stage_file(stage), stage_markdown)
append_approved_stage_summary(paths.memory, stage, stage_markdown)
mark_stage_approved_manifest(paths, stage, 0, self._stage_file_paths(stage_markdown))
write_stage_handoff(paths, stage, stage_markdown)
def _project_bootstrap_artifact_paths(self, paths: RunPaths) -> list[str]:
artifact_paths: list[str] = []
for filename in ("bootstrap_summary.md", "stage_assessments.json", "scan_metadata.json"):
path = paths.bootstrap_dir / filename
if path.exists():
artifact_paths.append(str(path.relative_to(paths.run_root)).replace("\\", "/"))
return artifact_paths
def _bootstrap_stage_markdown(
self,
paths: RunPaths,
stage: StageSpec,
assessment,
artifact_paths: list[str],
) -> str:
prior = approved_stage_summaries(read_text(paths.memory))
stage_file_path = str(paths.stage_file(stage).relative_to(paths.run_root)).replace("\\", "/")
files_produced = [f"- `{stage_file_path}`"] + [f"- `{path}`" for path in artifact_paths]
evidence_lines = ["- No specific bootstrap evidence recorded."]
status_line = "Bootstrap carry-forward status: unspecified."
if assessment is not None:
status_line = (
f"Bootstrap carry-forward status: {assessment.status} "
f"(confidence: {assessment.confidence})."
)
if assessment.evidence:
evidence_lines = [f"- {item}" for item in assessment.evidence]
suggestions = "\n".join(
f"{index}. {text}"
for index, text in enumerate(DEFAULT_REFINEMENT_SUGGESTIONS, start=1)
)
options = "\n".join(FIXED_STAGE_OPTIONS)
evidence_block = "\n".join(evidence_lines)
files_block = "\n".join(files_produced)
return (
f"# Stage {stage.number:02d}: {stage.display_name}\n\n"
"## Objective\n"
f"Carry forward the pre-existing project state for {stage.display_name} from the approved project bootstrap.\n\n"
"## Previously Approved Stage Summaries\n"
f"{prior}\n\n"
"## What I Did\n"
"- Reviewed the approved project bootstrap artifacts for this repository.\n"
"- Recorded the prior state of this stage instead of rerunning it from scratch.\n\n"
"## Key Results\n"
f"- {status_line}\n"
"- This stage is being accepted as prior project context before continuing downstream AutoR stages.\n"
f"{evidence_block}\n\n"
"## Files Produced\n"
f"{files_block}\n\n"
"## Suggestions for Refinement\n"
f"{suggestions}\n\n"
"## Your Options\n"
f"{options}\n"
)
def _build_project_bootstrap_prompt(
self,
paths: RunPaths,
stage: StageSpec,
scan_text: str,
project_root: Path,
revision_feedback: str | None,
continue_session: bool,
) -> str:
template = load_prompt_template(self.prompt_dir, stage)
stage_template = format_stage_template(template, stage, paths)
if continue_session:
return build_continuation_prompt(
stage, stage_template, paths,
handoff_context="",
revision_feedback=revision_feedback,
)
user_request = read_text(paths.user_input)
project_section = (
f"# Existing Project Repository\n\n"
f"**Project root:** `{project_root}`\n\n"
f"{scan_text}"
)
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```",
"# Original User Request",
user_request.strip(),
project_section,
"# Revision Feedback",
revision_feedback.strip() if revision_feedback else "None.",
]
return "\n\n".join(sections).strip() + "\n"
def _build_bootstrap_prompt(
self,
paths: RunPaths,
stage: StageSpec,
corpus_text: str,
revision_feedback: str | None,
continue_session: bool,
) -> str:
"""Build the prompt for the bootstrap stage."""
template = load_prompt_template(self.prompt_dir, stage)
stage_template = format_stage_template(template, stage, paths)
if continue_session:
return build_continuation_prompt(
stage, stage_template, paths,
handoff_context="",
revision_feedback=revision_feedback,
)
user_request = read_text(paths.user_input)
corpus_section = f"# User's Paper Corpus\n\n{corpus_text}"
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```",
"# Original User Request",
user_request.strip(),
corpus_section,
"# Revision Feedback",
revision_feedback.strip() if revision_feedback else "None.",
]
return "\n\n".join(sections).strip() + "\n"
# ------------------------------------------------------------------
# Regular stages (01–08)
# ------------------------------------------------------------------
def _run_stage(self, paths: RunPaths, stage: StageSpec) -> bool:
attempt_no = read_attempt_count(paths, stage) + 1
loop_attempts = 0
revision_feedback: str | None = None
continue_session = False
last_validation_errors: list[str] = []
mark_stage_execution_started(paths, stage)
# Optional pre-loaded revision feedback. The Studio (or any other
# caller) can drop a "<slug>.pending_feedback.txt" file under
# operator_state/ to inject feedback into the FIRST attempt of this
# stage's prompt instead of waiting for choose_action() on attempt 2.