shipwright-cli 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/.claude/agents/code-reviewer.md +2 -0
  2. package/.claude/agents/devops-engineer.md +2 -0
  3. package/.claude/agents/doc-fleet-agent.md +2 -0
  4. package/.claude/agents/pipeline-agent.md +2 -0
  5. package/.claude/agents/shell-script-specialist.md +2 -0
  6. package/.claude/agents/test-specialist.md +2 -0
  7. package/.claude/hooks/agent-crash-capture.sh +32 -0
  8. package/.claude/hooks/post-tool-use.sh +3 -2
  9. package/.claude/hooks/pre-tool-use.sh +35 -3
  10. package/README.md +4 -4
  11. package/claude-code/hooks/config-change.sh +18 -0
  12. package/claude-code/hooks/instructions-reloaded.sh +7 -0
  13. package/claude-code/hooks/worktree-create.sh +25 -0
  14. package/claude-code/hooks/worktree-remove.sh +20 -0
  15. package/config/code-constitution.json +130 -0
  16. package/dashboard/middleware/auth.ts +134 -0
  17. package/dashboard/middleware/constants.ts +21 -0
  18. package/dashboard/public/index.html +2 -6
  19. package/dashboard/public/styles.css +100 -97
  20. package/dashboard/routes/auth.ts +38 -0
  21. package/dashboard/server.ts +66 -25
  22. package/dashboard/services/config.ts +26 -0
  23. package/dashboard/services/db.ts +118 -0
  24. package/dashboard/src/canvas/pixel-agent.ts +298 -0
  25. package/dashboard/src/canvas/pixel-sprites.ts +440 -0
  26. package/dashboard/src/canvas/shipyard-effects.ts +367 -0
  27. package/dashboard/src/canvas/shipyard-scene.ts +616 -0
  28. package/dashboard/src/canvas/submarine-layout.ts +267 -0
  29. package/dashboard/src/components/header.ts +8 -7
  30. package/dashboard/src/core/router.ts +1 -0
  31. package/dashboard/src/design/submarine-theme.ts +253 -0
  32. package/dashboard/src/main.ts +2 -0
  33. package/dashboard/src/types/api.ts +2 -1
  34. package/dashboard/src/views/activity.ts +2 -1
  35. package/dashboard/src/views/shipyard.ts +39 -0
  36. package/dashboard/types/index.ts +166 -0
  37. package/docs/plans/2026-02-28-compound-audit-and-shipyard-design.md +186 -0
  38. package/docs/plans/2026-02-28-skipper-shipwright-implementation-plan.md +1182 -0
  39. package/docs/plans/2026-02-28-skipper-shipwright-integration-design.md +531 -0
  40. package/docs/plans/2026-03-01-ai-powered-skill-injection-design.md +298 -0
  41. package/docs/plans/2026-03-01-ai-powered-skill-injection-plan.md +1109 -0
  42. package/docs/plans/2026-03-01-capabilities-cleanup-plan.md +658 -0
  43. package/docs/plans/2026-03-01-clean-architecture-plan.md +924 -0
  44. package/docs/plans/2026-03-01-compound-audit-cascade-design.md +191 -0
  45. package/docs/plans/2026-03-01-compound-audit-cascade-plan.md +921 -0
  46. package/docs/plans/2026-03-01-deep-integration-plan.md +851 -0
  47. package/docs/plans/2026-03-01-pipeline-audit-trail-design.md +145 -0
  48. package/docs/plans/2026-03-01-pipeline-audit-trail-plan.md +770 -0
  49. package/docs/plans/2026-03-01-refined-depths-brand-design.md +382 -0
  50. package/docs/plans/2026-03-01-refined-depths-implementation.md +599 -0
  51. package/docs/plans/2026-03-01-skipper-kernel-integration-design.md +203 -0
  52. package/docs/plans/2026-03-01-unified-platform-design.md +272 -0
  53. package/docs/plans/2026-03-07-claude-code-feature-integration-design.md +189 -0
  54. package/docs/plans/2026-03-07-claude-code-feature-integration-plan.md +1165 -0
  55. package/docs/research/BACKLOG_QUICK_REFERENCE.md +352 -0
  56. package/docs/research/CUTTING_EDGE_RESEARCH_2026.md +546 -0
  57. package/docs/research/RESEARCH_INDEX.md +439 -0
  58. package/docs/research/RESEARCH_SOURCES.md +440 -0
  59. package/docs/research/RESEARCH_SUMMARY.txt +275 -0
  60. package/docs/superpowers/specs/2026-03-10-pipeline-quality-revolution-design.md +341 -0
  61. package/package.json +2 -2
  62. package/scripts/lib/adaptive-model.sh +427 -0
  63. package/scripts/lib/adaptive-timeout.sh +316 -0
  64. package/scripts/lib/audit-trail.sh +309 -0
  65. package/scripts/lib/auto-recovery.sh +471 -0
  66. package/scripts/lib/bandit-selector.sh +431 -0
  67. package/scripts/lib/bootstrap.sh +104 -2
  68. package/scripts/lib/causal-graph.sh +455 -0
  69. package/scripts/lib/compat.sh +126 -0
  70. package/scripts/lib/compound-audit.sh +337 -0
  71. package/scripts/lib/constitutional.sh +454 -0
  72. package/scripts/lib/context-budget.sh +359 -0
  73. package/scripts/lib/convergence.sh +594 -0
  74. package/scripts/lib/cost-optimizer.sh +634 -0
  75. package/scripts/lib/daemon-adaptive.sh +10 -0
  76. package/scripts/lib/daemon-dispatch.sh +106 -17
  77. package/scripts/lib/daemon-failure.sh +34 -4
  78. package/scripts/lib/daemon-patrol.sh +23 -2
  79. package/scripts/lib/daemon-poll-github.sh +361 -0
  80. package/scripts/lib/daemon-poll-health.sh +299 -0
  81. package/scripts/lib/daemon-poll.sh +27 -611
  82. package/scripts/lib/daemon-state.sh +112 -66
  83. package/scripts/lib/daemon-triage.sh +10 -0
  84. package/scripts/lib/dod-scorecard.sh +442 -0
  85. package/scripts/lib/error-actionability.sh +300 -0
  86. package/scripts/lib/formal-spec.sh +461 -0
  87. package/scripts/lib/helpers.sh +177 -4
  88. package/scripts/lib/intent-analysis.sh +409 -0
  89. package/scripts/lib/loop-convergence.sh +350 -0
  90. package/scripts/lib/loop-iteration.sh +682 -0
  91. package/scripts/lib/loop-progress.sh +48 -0
  92. package/scripts/lib/loop-restart.sh +185 -0
  93. package/scripts/lib/memory-effectiveness.sh +506 -0
  94. package/scripts/lib/mutation-executor.sh +352 -0
  95. package/scripts/lib/outcome-feedback.sh +521 -0
  96. package/scripts/lib/pipeline-cli.sh +336 -0
  97. package/scripts/lib/pipeline-commands.sh +1216 -0
  98. package/scripts/lib/pipeline-detection.sh +100 -2
  99. package/scripts/lib/pipeline-execution.sh +897 -0
  100. package/scripts/lib/pipeline-github.sh +28 -3
  101. package/scripts/lib/pipeline-intelligence-compound.sh +431 -0
  102. package/scripts/lib/pipeline-intelligence-scoring.sh +407 -0
  103. package/scripts/lib/pipeline-intelligence-skip.sh +181 -0
  104. package/scripts/lib/pipeline-intelligence.sh +100 -1136
  105. package/scripts/lib/pipeline-quality-bash-compat.sh +182 -0
  106. package/scripts/lib/pipeline-quality-checks.sh +17 -715
  107. package/scripts/lib/pipeline-quality-gates.sh +563 -0
  108. package/scripts/lib/pipeline-stages-build.sh +730 -0
  109. package/scripts/lib/pipeline-stages-delivery.sh +965 -0
  110. package/scripts/lib/pipeline-stages-intake.sh +1133 -0
  111. package/scripts/lib/pipeline-stages-monitor.sh +407 -0
  112. package/scripts/lib/pipeline-stages-review.sh +1022 -0
  113. package/scripts/lib/pipeline-stages.sh +59 -2929
  114. package/scripts/lib/pipeline-state.sh +36 -5
  115. package/scripts/lib/pipeline-util.sh +487 -0
  116. package/scripts/lib/policy-learner.sh +438 -0
  117. package/scripts/lib/process-reward.sh +493 -0
  118. package/scripts/lib/project-detect.sh +649 -0
  119. package/scripts/lib/quality-profile.sh +334 -0
  120. package/scripts/lib/recruit-commands.sh +885 -0
  121. package/scripts/lib/recruit-learning.sh +739 -0
  122. package/scripts/lib/recruit-roles.sh +648 -0
  123. package/scripts/lib/reward-aggregator.sh +458 -0
  124. package/scripts/lib/rl-optimizer.sh +362 -0
  125. package/scripts/lib/root-cause.sh +427 -0
  126. package/scripts/lib/scope-enforcement.sh +445 -0
  127. package/scripts/lib/session-restart.sh +493 -0
  128. package/scripts/lib/skill-memory.sh +300 -0
  129. package/scripts/lib/skill-registry.sh +775 -0
  130. package/scripts/lib/spec-driven.sh +476 -0
  131. package/scripts/lib/test-helpers.sh +18 -7
  132. package/scripts/lib/test-holdout.sh +429 -0
  133. package/scripts/lib/test-optimizer.sh +511 -0
  134. package/scripts/shipwright-file-suggest.sh +45 -0
  135. package/scripts/skills/adversarial-quality.md +61 -0
  136. package/scripts/skills/api-design.md +44 -0
  137. package/scripts/skills/architecture-design.md +50 -0
  138. package/scripts/skills/brainstorming.md +43 -0
  139. package/scripts/skills/data-pipeline.md +44 -0
  140. package/scripts/skills/deploy-safety.md +64 -0
  141. package/scripts/skills/documentation.md +38 -0
  142. package/scripts/skills/frontend-design.md +45 -0
  143. package/scripts/skills/generated/.gitkeep +0 -0
  144. package/scripts/skills/generated/_refinements/.gitkeep +0 -0
  145. package/scripts/skills/generated/_refinements/adversarial-quality.patch.md +3 -0
  146. package/scripts/skills/generated/_refinements/architecture-design.patch.md +3 -0
  147. package/scripts/skills/generated/_refinements/brainstorming.patch.md +3 -0
  148. package/scripts/skills/generated/cli-version-management.md +29 -0
  149. package/scripts/skills/generated/collection-system-validation.md +99 -0
  150. package/scripts/skills/generated/large-scale-c-refactoring-coordination.md +97 -0
  151. package/scripts/skills/generated/pattern-matching-similarity-scoring.md +195 -0
  152. package/scripts/skills/generated/test-parallelization-detection.md +65 -0
  153. package/scripts/skills/observability.md +79 -0
  154. package/scripts/skills/performance.md +48 -0
  155. package/scripts/skills/pr-quality.md +49 -0
  156. package/scripts/skills/product-thinking.md +43 -0
  157. package/scripts/skills/security-audit.md +49 -0
  158. package/scripts/skills/systematic-debugging.md +40 -0
  159. package/scripts/skills/testing-strategy.md +47 -0
  160. package/scripts/skills/two-stage-review.md +52 -0
  161. package/scripts/skills/validation-thoroughness.md +55 -0
  162. package/scripts/sw +9 -3
  163. package/scripts/sw-activity.sh +9 -2
  164. package/scripts/sw-adaptive.sh +2 -1
  165. package/scripts/sw-adversarial.sh +2 -1
  166. package/scripts/sw-architecture-enforcer.sh +3 -1
  167. package/scripts/sw-auth.sh +12 -2
  168. package/scripts/sw-autonomous.sh +5 -1
  169. package/scripts/sw-changelog.sh +4 -1
  170. package/scripts/sw-checkpoint.sh +2 -1
  171. package/scripts/sw-ci.sh +5 -1
  172. package/scripts/sw-cleanup.sh +4 -26
  173. package/scripts/sw-code-review.sh +10 -4
  174. package/scripts/sw-connect.sh +2 -1
  175. package/scripts/sw-context.sh +2 -1
  176. package/scripts/sw-cost.sh +48 -3
  177. package/scripts/sw-daemon.sh +66 -9
  178. package/scripts/sw-dashboard.sh +3 -1
  179. package/scripts/sw-db.sh +59 -16
  180. package/scripts/sw-decide.sh +8 -2
  181. package/scripts/sw-decompose.sh +360 -17
  182. package/scripts/sw-deps.sh +4 -1
  183. package/scripts/sw-developer-simulation.sh +4 -1
  184. package/scripts/sw-discovery.sh +325 -2
  185. package/scripts/sw-doc-fleet.sh +4 -1
  186. package/scripts/sw-docs-agent.sh +3 -1
  187. package/scripts/sw-docs.sh +2 -1
  188. package/scripts/sw-doctor.sh +453 -2
  189. package/scripts/sw-dora.sh +4 -1
  190. package/scripts/sw-durable.sh +4 -3
  191. package/scripts/sw-e2e-orchestrator.sh +17 -16
  192. package/scripts/sw-eventbus.sh +7 -1
  193. package/scripts/sw-evidence.sh +364 -12
  194. package/scripts/sw-feedback.sh +550 -9
  195. package/scripts/sw-fix.sh +20 -1
  196. package/scripts/sw-fleet-discover.sh +6 -2
  197. package/scripts/sw-fleet-viz.sh +4 -1
  198. package/scripts/sw-fleet.sh +5 -1
  199. package/scripts/sw-github-app.sh +16 -3
  200. package/scripts/sw-github-checks.sh +3 -2
  201. package/scripts/sw-github-deploy.sh +3 -2
  202. package/scripts/sw-github-graphql.sh +18 -7
  203. package/scripts/sw-guild.sh +5 -1
  204. package/scripts/sw-heartbeat.sh +5 -30
  205. package/scripts/sw-hello.sh +67 -0
  206. package/scripts/sw-hygiene.sh +6 -1
  207. package/scripts/sw-incident.sh +265 -1
  208. package/scripts/sw-init.sh +18 -2
  209. package/scripts/sw-instrument.sh +10 -2
  210. package/scripts/sw-intelligence.sh +42 -6
  211. package/scripts/sw-jira.sh +5 -1
  212. package/scripts/sw-launchd.sh +2 -1
  213. package/scripts/sw-linear.sh +4 -1
  214. package/scripts/sw-logs.sh +4 -1
  215. package/scripts/sw-loop.sh +432 -1128
  216. package/scripts/sw-memory.sh +356 -2
  217. package/scripts/sw-mission-control.sh +6 -1
  218. package/scripts/sw-model-router.sh +481 -26
  219. package/scripts/sw-otel.sh +13 -4
  220. package/scripts/sw-oversight.sh +14 -5
  221. package/scripts/sw-patrol-meta.sh +334 -0
  222. package/scripts/sw-pipeline-composer.sh +5 -1
  223. package/scripts/sw-pipeline-vitals.sh +2 -1
  224. package/scripts/sw-pipeline.sh +53 -2664
  225. package/scripts/sw-pm.sh +12 -5
  226. package/scripts/sw-pr-lifecycle.sh +2 -1
  227. package/scripts/sw-predictive.sh +7 -1
  228. package/scripts/sw-prep.sh +185 -2
  229. package/scripts/sw-ps.sh +5 -25
  230. package/scripts/sw-public-dashboard.sh +15 -3
  231. package/scripts/sw-quality.sh +2 -1
  232. package/scripts/sw-reaper.sh +8 -25
  233. package/scripts/sw-recruit.sh +156 -2303
  234. package/scripts/sw-regression.sh +19 -12
  235. package/scripts/sw-release-manager.sh +3 -1
  236. package/scripts/sw-release.sh +4 -1
  237. package/scripts/sw-remote.sh +3 -1
  238. package/scripts/sw-replay.sh +7 -1
  239. package/scripts/sw-retro.sh +158 -1
  240. package/scripts/sw-review-rerun.sh +3 -1
  241. package/scripts/sw-scale.sh +10 -3
  242. package/scripts/sw-security-audit.sh +6 -1
  243. package/scripts/sw-self-optimize.sh +6 -3
  244. package/scripts/sw-session.sh +9 -3
  245. package/scripts/sw-setup.sh +3 -1
  246. package/scripts/sw-stall-detector.sh +406 -0
  247. package/scripts/sw-standup.sh +15 -7
  248. package/scripts/sw-status.sh +3 -1
  249. package/scripts/sw-strategic.sh +4 -1
  250. package/scripts/sw-stream.sh +7 -1
  251. package/scripts/sw-swarm.sh +18 -6
  252. package/scripts/sw-team-stages.sh +13 -6
  253. package/scripts/sw-templates.sh +5 -29
  254. package/scripts/sw-testgen.sh +7 -1
  255. package/scripts/sw-tmux-pipeline.sh +4 -1
  256. package/scripts/sw-tmux-role-color.sh +2 -0
  257. package/scripts/sw-tmux-status.sh +1 -1
  258. package/scripts/sw-tmux.sh +3 -1
  259. package/scripts/sw-trace.sh +3 -1
  260. package/scripts/sw-tracker-github.sh +3 -0
  261. package/scripts/sw-tracker-jira.sh +3 -0
  262. package/scripts/sw-tracker-linear.sh +3 -0
  263. package/scripts/sw-tracker.sh +3 -1
  264. package/scripts/sw-triage.sh +2 -1
  265. package/scripts/sw-upgrade.sh +3 -1
  266. package/scripts/sw-ux.sh +5 -2
  267. package/scripts/sw-webhook.sh +3 -1
  268. package/scripts/sw-widgets.sh +3 -1
  269. package/scripts/sw-worktree.sh +15 -3
  270. package/scripts/test-skill-injection.sh +1233 -0
  271. package/templates/pipelines/autonomous.json +27 -3
  272. package/templates/pipelines/cost-aware.json +34 -8
  273. package/templates/pipelines/deployed.json +12 -0
  274. package/templates/pipelines/enterprise.json +12 -0
  275. package/templates/pipelines/fast.json +6 -0
  276. package/templates/pipelines/full.json +27 -3
  277. package/templates/pipelines/hotfix.json +6 -0
  278. package/templates/pipelines/standard.json +12 -0
  279. package/templates/pipelines/tdd.json +12 -0
@@ -0,0 +1,493 @@
1
+ #!/usr/bin/env bash
2
+ # ╔═══════════════════════════════════════════════════════════════════════════╗
3
+ # ║ session-restart — Intelligent session restart with enhanced resume ║
4
+ # ║ ║
5
+ # ║ Captures rich context before restart, generates strategic briefings ║
6
+ # ║ for new sessions, and tracks progress across multiple restarts. ║
7
+ # ╚═══════════════════════════════════════════════════════════════════════════╝
8
+
9
+ # Module guard - prevent double-sourcing
10
+ [[ -n "${_SESSION_RESTART_LOADED:-}" ]] && return 0
11
+ _SESSION_RESTART_LOADED=1
12
+
13
+ VERSION="3.3.0"
14
+
15
+ # ─── State Capture ─────────────────────────────────────────────────────────
16
+
17
+ restart_capture_state() {
18
+ local state_file="${ARTIFACTS_DIR:-${LOG_DIR}}/restart-state.json"
19
+ local tmp_state="${state_file}.tmp.$$"
20
+
21
+ # Ensure ARTIFACTS_DIR exists
22
+ mkdir -p "${ARTIFACTS_DIR:-${LOG_DIR}}" 2>/dev/null || true
23
+
24
+ # Capture git state
25
+ local current_branch commit_hash diff_stat uncommitted_changes
26
+ current_branch="$(git -C "$PROJECT_ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")"
27
+ commit_hash="$(git -C "$PROJECT_ROOT" rev-parse HEAD 2>/dev/null || echo "")"
28
+ diff_stat="$(git -C "$PROJECT_ROOT" diff --stat HEAD 2>/dev/null || echo "")"
29
+ uncommitted_changes=$(git -C "$PROJECT_ROOT" status --short 2>/dev/null | wc -l)
30
+
31
+ # Capture test state
32
+ local test_status test_results
33
+ test_status="${TEST_PASSED:-unknown}"
34
+ test_results=""
35
+ if [[ -f "$LOG_DIR/tests-iter-${ITERATION}.log" ]]; then
36
+ test_results="$(tail -20 "$LOG_DIR/tests-iter-${ITERATION}.log" 2>/dev/null || echo "")"
37
+ fi
38
+
39
+ # Capture progress metrics
40
+ local iterations_completed failed_iterations tests_passed_count tests_failed_count
41
+ iterations_completed="${ITERATION:-0}"
42
+ failed_iterations="${CONSECUTIVE_FAILURES:-0}"
43
+ tests_passed_count=$(grep -c "✓ PASSED" "$LOG_DIR/progress.md" 2>/dev/null || echo "0")
44
+ tests_failed_count=$(grep -c "✗ FAILED" "$LOG_DIR/progress.md" 2>/dev/null || echo "0")
45
+
46
+ # Capture modified files
47
+ local modified_files created_files deleted_files
48
+ modified_files="$(git -C "$PROJECT_ROOT" diff --name-only HEAD~5 2>/dev/null | head -30 || echo "")"
49
+ created_files="$(git -C "$PROJECT_ROOT" diff --diff-filter=A --name-only HEAD~5 2>/dev/null | head -10 || echo "")"
50
+ deleted_files="$(git -C "$PROJECT_ROOT" diff --diff-filter=D --name-only HEAD~5 2>/dev/null | head -10 || echo "")"
51
+
52
+ # Recent error summary
53
+ local recent_error=""
54
+ if [[ -f "$LOG_DIR/error-summary.json" ]]; then
55
+ recent_error="$(jq -r '.error_summary // ""' "$LOG_DIR/error-summary.json" 2>/dev/null || echo "")"
56
+ fi
57
+
58
+ # Build JSON atomically
59
+ {
60
+ printf '{\n'
61
+ printf ' "timestamp": "%s",\n' "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
62
+ printf ' "restart_count": %d,\n' "${RESTART_COUNT:-0}"
63
+ printf ' "max_restarts": %d,\n' "${MAX_RESTARTS:-0}"
64
+ printf ' "goal": %s,\n' "$(echo "$GOAL" | jq -Rs .)"
65
+ printf ' "git": {\n'
66
+ printf ' "branch": %s,\n' "$(echo "$current_branch" | jq -Rs .)"
67
+ printf ' "commit": %s,\n' "$(echo "$commit_hash" | jq -Rs .)"
68
+ printf ' "uncommitted_changes": %d\n' "$uncommitted_changes"
69
+ printf ' },\n'
70
+ printf ' "progress": {\n'
71
+ printf ' "iteration": %d,\n' "$iterations_completed"
72
+ printf ' "max_iterations": %d,\n' "${MAX_ITERATIONS:-0}"
73
+ printf ' "test_status": %s,\n' "$(echo "$test_status" | jq -Rs .)"
74
+ printf ' "tests_passed": %d,\n' "$tests_passed_count"
75
+ printf ' "tests_failed": %d,\n' "$tests_failed_count"
76
+ printf ' "consecutive_failures": %d\n' "$failed_iterations"
77
+ printf ' },\n'
78
+ printf ' "files": {\n'
79
+ printf ' "modified": %s,\n' "$(echo "$modified_files" | jq -Rs .)"
80
+ printf ' "created": %s,\n' "$(echo "$created_files" | jq -Rs .)"
81
+ printf ' "deleted": %s\n' "$(echo "$deleted_files" | jq -Rs .)"
82
+ printf ' },\n'
83
+ printf ' "errors": %s\n' "$(echo "$recent_error" | jq -Rs .)"
84
+ printf '}\n'
85
+ } > "$tmp_state" 2>/dev/null
86
+
87
+ if mv "$tmp_state" "$state_file" 2>/dev/null; then
88
+ emit_event "session.restart_capture" "state_file=$state_file" "iteration=$ITERATION" "restart=$RESTART_COUNT" 2>/dev/null || true
89
+ echo "$state_file"
90
+ return 0
91
+ else
92
+ warn "Failed to write restart state to $state_file"
93
+ rm -f "$tmp_state"
94
+ return 1
95
+ fi
96
+ }
97
+
98
+ # ─── Briefing Generation ──────────────────────────────────────────────────
99
+
100
+ restart_generate_briefing() {
101
+ local state_file="${1:-${ARTIFACTS_DIR:-${LOG_DIR}}/restart-state.json}"
102
+ local briefing_file="${ARTIFACTS_DIR:-${LOG_DIR}}/restart-briefing.md"
103
+ local tmp_briefing="${briefing_file}.tmp.$$"
104
+
105
+ [[ ! -f "$state_file" ]] && {
106
+ warn "Restart state file not found: $state_file"
107
+ return 1
108
+ }
109
+
110
+ # Parse state JSON
111
+ local goal iteration max_iter test_status tests_passed tests_failed
112
+ local modified_files recent_error restart_count
113
+ goal="$(jq -r '.goal // ""' "$state_file" 2>/dev/null || echo "")"
114
+ iteration="$(jq -r '.progress.iteration // 0' "$state_file" 2>/dev/null || echo "0")"
115
+ max_iter="$(jq -r '.progress.max_iterations // 0' "$state_file" 2>/dev/null || echo "0")"
116
+ test_status="$(jq -r '.progress.test_status // "unknown"' "$state_file" 2>/dev/null || echo "unknown")"
117
+ tests_passed="$(jq -r '.progress.tests_passed // 0' "$state_file" 2>/dev/null || echo "0")"
118
+ tests_failed="$(jq -r '.progress.tests_failed // 0' "$state_file" 2>/dev/null || echo "0")"
119
+ modified_files="$(jq -r '.files.modified // ""' "$state_file" 2>/dev/null || echo "")"
120
+ recent_error="$(jq -r '.errors // ""' "$state_file" 2>/dev/null || echo "")"
121
+ restart_count="$(jq -r '.restart_count // 0' "$state_file" 2>/dev/null || echo "0")"
122
+
123
+ # Generate briefing sections
124
+ {
125
+ printf '# Session Restart Briefing #%d\n\n' "$restart_count"
126
+
127
+ printf '## What'"'"'s Done ✓\n'
128
+ printf '- Completed **%d of %d** iterations\n' "$iteration" "$max_iter"
129
+ printf '- Tests: %d passed, %d failed\n' "$tests_passed" "$tests_failed"
130
+ if [[ "$test_status" == "true" ]]; then
131
+ printf '- **Tests are currently PASSING** — maintain momentum\n'
132
+ else
133
+ printf '- **Tests are currently FAILING** — focus on fixing\n'
134
+ fi
135
+ printf '\n'
136
+
137
+ printf '## What'"'"'s Failing 🔴\n'
138
+ if [[ -n "$recent_error" && "$recent_error" != "null" ]]; then
139
+ printf '%s\n\n' "$recent_error"
140
+ else
141
+ printf '- No specific error captured yet — check test output\n\n'
142
+ fi
143
+
144
+ printf '## Modified Files 📝\n'
145
+ if [[ -n "$modified_files" && "$modified_files" != "null" && "$modified_files" != "" ]]; then
146
+ printf '%s\n\n' "$modified_files"
147
+ else
148
+ printf '- No files modified yet\n\n'
149
+ fi
150
+
151
+ printf '## What to Try Next 🎯\n'
152
+ if [[ "$test_status" == "true" ]]; then
153
+ printf '- Tests are passing: focus on incomplete features\n'
154
+ printf '- Do NOT re-run passing tests — save context\n'
155
+ printf '- Commit frequently to preserve progress\n'
156
+ elif [[ "$tests_failed" -gt "$tests_passed" ]]; then
157
+ printf '- Fix the FAILING tests first\n'
158
+ printf '- Start with the most common error pattern\n'
159
+ printf '- Read error output carefully before changing code\n'
160
+ else
161
+ printf '- Balance between fixing tests and adding features\n'
162
+ fi
163
+ printf '\n'
164
+
165
+ printf '## What NOT to Try (Previous Failures) 🚫\n'
166
+ printf '- Do not repeat failed iterations without understanding why\n'
167
+ printf '- Do not ignore test failures — they indicate real problems\n'
168
+ printf '- Do not modify files already committed unless necessary\n'
169
+ printf '\n'
170
+
171
+ printf '---\n'
172
+ printf 'Resume point: Iteration %d/%d at %s\n' "$iteration" "$max_iter" "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
173
+ printf 'Use %s for detailed state.\n' "$(basename "$state_file")"
174
+
175
+ } > "$tmp_briefing" 2>/dev/null
176
+
177
+ if mv "$tmp_briefing" "$briefing_file" 2>/dev/null; then
178
+ emit_event "session.briefing_generated" "briefing_file=$briefing_file" "iteration=$iteration" 2>/dev/null || true
179
+ echo "$briefing_file"
180
+ return 0
181
+ else
182
+ warn "Failed to write briefing to $briefing_file"
183
+ rm -f "$tmp_briefing"
184
+ return 1
185
+ fi
186
+ }
187
+
188
+ # ─── Restart Reason Detection ──────────────────────────────────────────────
189
+
190
+ restart_detect_reason() {
191
+ local iteration="${1:-${ITERATION:-0}}"
192
+ local max_iterations="${2:-${MAX_ITERATIONS:-0}}"
193
+ local test_status="${3:-${TEST_PASSED:-unknown}}"
194
+ local consecutive_failures="${4:-${CONSECUTIVE_FAILURES:-0}}"
195
+ local manual="${5:-false}"
196
+
197
+ local reason classification evidence
198
+
199
+ # Check for manual restart (from user signal)
200
+ if [[ "$manual" == "true" ]]; then
201
+ reason="manual"
202
+ evidence="User triggered restart via signal or command"
203
+ classification="manual"
204
+ # Check for context exhaustion (loop completed all iterations)
205
+ elif [[ "$iteration" -ge "$max_iterations" ]] && [[ "$max_iterations" -gt 0 ]]; then
206
+ reason="context_exhaustion"
207
+ evidence="Reached iteration $iteration/$max_iterations"
208
+ classification="context_exhaustion"
209
+ # Check for iteration limit hit
210
+ elif [[ "$iteration" -ge "$max_iterations" ]] && [[ "$max_iterations" -gt 0 ]]; then
211
+ reason="iteration_limit"
212
+ evidence="Hit max iterations ($max_iterations)"
213
+ classification="iteration_limit"
214
+ # Check for stuck loop (same error multiple times)
215
+ elif [[ "$consecutive_failures" -ge 3 ]]; then
216
+ reason="stuck_loop"
217
+ evidence="$consecutive_failures consecutive failures without progress"
218
+ classification="stuck_loop"
219
+ else
220
+ reason="unknown"
221
+ evidence="Unable to classify restart reason"
222
+ classification="unknown"
223
+ fi
224
+
225
+ # Output as JSON for machine parsing
226
+ local tmp_reason="${ARTIFACTS_DIR:-${LOG_DIR}}/restart-reason.json"
227
+ mkdir -p "${ARTIFACTS_DIR:-${LOG_DIR}}" 2>/dev/null || true
228
+ {
229
+ printf '{\n'
230
+ printf ' "classification": %s,\n' "$(echo "$classification" | jq -Rs .)"
231
+ printf ' "reason": %s,\n' "$(echo "$reason" | jq -Rs .)"
232
+ printf ' "evidence": %s,\n' "$(echo "$evidence" | jq -Rs .)"
233
+ printf ' "iteration": %d,\n' "$iteration"
234
+ printf ' "max_iterations": %d,\n' "$max_iterations"
235
+ printf ' "consecutive_failures": %d,\n' "$consecutive_failures"
236
+ printf ' "timestamp": %s\n' "$(date -u +"%Y-%m-%dT%H:%M:%SZ" | jq -Rs .)"
237
+ printf '}\n'
238
+ } > "$tmp_reason" 2>/dev/null
239
+ mv "$tmp_reason" "${tmp_reason%.tmp.$$}" 2>/dev/null || true
240
+
241
+ emit_event "session.restart_reason" "classification=$classification" "reason=$reason" "iteration=$iteration" 2>/dev/null || true
242
+
243
+ # Also output to stdout for caller to capture
244
+ echo "$classification"
245
+ return 0
246
+ }
247
+
248
+ # ─── Strategy Suggestion ───────────────────────────────────────────────────
249
+
250
+ restart_suggest_strategy() {
251
+ local reason="${1:-unknown}"
252
+ local goal="${2:-${GOAL:-}}"
253
+ local test_status="${3:-${TEST_PASSED:-unknown}}"
254
+
255
+ local strategy priority focus avoid
256
+
257
+ case "$reason" in
258
+ context_exhaustion)
259
+ strategy="Focus on remaining failing tests, don't re-read files already committed"
260
+ priority="high"
261
+ focus="Complete failing tests and features"
262
+ avoid="Re-reading entire files, verbose exploration"
263
+ ;;
264
+ iteration_limit)
265
+ strategy="Prioritize the highest-impact remaining work"
266
+ priority="high"
267
+ focus="Most critical features for goal completion"
268
+ avoid="Low-impact improvements, refactoring"
269
+ ;;
270
+ stuck_loop)
271
+ strategy="Try a fundamentally different approach to the current problem"
272
+ priority="critical"
273
+ focus="Root cause analysis of the stuck point"
274
+ avoid="Repeated small changes that didn't work before"
275
+ ;;
276
+ manual)
277
+ strategy="Continue from where you left off with fresh context"
278
+ priority="normal"
279
+ focus="Completing the goal"
280
+ avoid="Repeating already-completed work"
281
+ ;;
282
+ *)
283
+ strategy="Analyze progress and continue toward goal"
284
+ priority="normal"
285
+ focus="Making measurable progress on the goal"
286
+ avoid="Repeating failed approaches"
287
+ ;;
288
+ esac
289
+
290
+ # Output structured strategy JSON
291
+ local tmp_strat="${ARTIFACTS_DIR:-${LOG_DIR}}/restart-strategy.json"
292
+ mkdir -p "${ARTIFACTS_DIR:-${LOG_DIR}}" 2>/dev/null || true
293
+ {
294
+ printf '{\n'
295
+ printf ' "reason": %s,\n' "$(echo "$reason" | jq -Rs .)"
296
+ printf ' "strategy": %s,\n' "$(echo "$strategy" | jq -Rs .)"
297
+ printf ' "priority": %s,\n' "$(echo "$priority" | jq -Rs .)"
298
+ printf ' "focus": %s,\n' "$(echo "$focus" | jq -Rs .)"
299
+ printf ' "avoid": %s,\n' "$(echo "$avoid" | jq -Rs .)"
300
+ printf ' "goal": %s,\n' "$(echo "$goal" | jq -Rs .)"
301
+ printf ' "test_status": %s,\n' "$(echo "$test_status" | jq -Rs .)"
302
+ printf ' "timestamp": %s\n' "$(date -u +"%Y-%m-%dT%H:%M:%SZ" | jq -Rs .)"
303
+ printf '}\n'
304
+ } > "$tmp_strat" 2>/dev/null
305
+ mv "$tmp_strat" "${tmp_strat%.tmp.$$}" 2>/dev/null || true
306
+
307
+ emit_event "session.strategy_suggested" "reason=$reason" "priority=$priority" 2>/dev/null || true
308
+
309
+ echo "$strategy"
310
+ return 0
311
+ }
312
+
313
+ # ─── Cross-Session Tracking ───────────────────────────────────────────────
314
+
315
+ restart_track_across_sessions() {
316
+ local history_file="${ARTIFACTS_DIR:-${LOG_DIR}}/restart-history.json"
317
+ mkdir -p "${ARTIFACTS_DIR:-${LOG_DIR}}" 2>/dev/null || true
318
+
319
+ # Get current state snapshot
320
+ local restart_num="${RESTART_COUNT:-0}"
321
+ local iteration="${ITERATION:-0}"
322
+ local test_passed="${TEST_PASSED:-unknown}"
323
+ local consecutive_failures="${CONSECUTIVE_FAILURES:-0}"
324
+
325
+ # Build JSON entry first (avoid newline issues with proper escaping)
326
+ local timestamp_clean="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
327
+ local new_entry
328
+ new_entry=$(printf '{"restart_number": %d, "iteration": %d, "test_passed": %s, "consecutive_failures": %d, "timestamp": %s}' \
329
+ "$restart_num" \
330
+ "$iteration" \
331
+ "$(printf '%s' "$test_passed" | jq -Rs .)" \
332
+ "$consecutive_failures" \
333
+ "$(printf '%s' "$timestamp_clean" | jq -Rs .)")
334
+
335
+ # Read existing array
336
+ local existing_array="[]"
337
+ if [[ -f "$history_file" ]] && jq . "$history_file" > /dev/null 2>&1; then
338
+ existing_array=$(cat "$history_file")
339
+ fi
340
+
341
+ # Append new entry using jq
342
+ local tmp_history="${history_file}.tmp.$$"
343
+ if echo "$existing_array" | jq --argjson entry "$new_entry" '. += [$entry]' > "$tmp_history" 2>/dev/null; then
344
+ if mv "$tmp_history" "$history_file" 2>/dev/null; then
345
+ emit_event "session.tracked_restart" "restart=$restart_num" "iteration=$iteration" "history_file=$history_file" 2>/dev/null || true
346
+
347
+ # Analyze pattern: if 3+ restarts with no test progress, recommend escalation
348
+ local restart_count
349
+ restart_count=$(jq 'length' "$history_file" 2>/dev/null || echo "0")
350
+ if [[ "$restart_count" -ge 3 ]]; then
351
+ local first_test last_test
352
+ first_test=$(jq -r '.[0].test_passed // "unknown"' "$history_file" 2>/dev/null || echo "unknown")
353
+ last_test=$(jq -r '.[-1].test_passed // "unknown"' "$history_file" 2>/dev/null || echo "unknown")
354
+ if [[ "$first_test" == "$last_test" && "$last_test" == "false" ]]; then
355
+ warn "Pattern detected: 3+ restarts with no test progress. Consider escalation to human or different strategy."
356
+ emit_event "session.escalation_recommended" "restart=$restart_count" "test_status=$last_test" 2>/dev/null || true
357
+ return 1
358
+ fi
359
+ fi
360
+ return 0
361
+ else
362
+ warn "Failed to move history file to $history_file"
363
+ rm -f "$tmp_history"
364
+ return 1
365
+ fi
366
+ else
367
+ warn "Failed to append entry to restart history"
368
+ rm -f "$tmp_history"
369
+ return 1
370
+ fi
371
+ }
372
+
373
+ # ─── Enhanced Progress File Writer ────────────────────────────────────────
374
+
375
+ restart_enhance_progress_md() {
376
+ local progress_file="${1:-${LOG_DIR}/progress.md}"
377
+ local tmp_progress="${progress_file}.tmp.$$"
378
+
379
+ # Read existing progress if available
380
+ local existing_content=""
381
+ [[ -f "$progress_file" ]] && existing_content="$(cat "$progress_file" 2>/dev/null || true)"
382
+
383
+ # Determine test summary
384
+ local test_summary
385
+ if [[ "${TEST_PASSED:-}" == "true" ]]; then
386
+ test_summary="✓ PASSING"
387
+ elif [[ "${TEST_PASSED:-}" == "false" ]]; then
388
+ test_summary="✗ FAILING"
389
+ else
390
+ test_summary="? UNKNOWN"
391
+ fi
392
+
393
+ # Detect anti-patterns from log
394
+ local antipatterns=""
395
+ if [[ -f "$LOG_DIR/error-summary.json" ]]; then
396
+ local err_count
397
+ err_count=$(jq -r '.error_count // 0' "$LOG_DIR/error-summary.json" 2>/dev/null || echo "0")
398
+ if [[ "$err_count" -gt 5 ]]; then
399
+ antipatterns="$antipatterns
400
+ - Too many distinct errors — narrow focus to one problem at a time"
401
+ fi
402
+ fi
403
+ if [[ "${CONSECUTIVE_FAILURES:-0}" -ge 2 ]]; then
404
+ antipatterns="$antipatterns
405
+ - Multiple consecutive failures — reconsider the current approach"
406
+ fi
407
+
408
+ # Write enhanced progress (atomic)
409
+ {
410
+ printf -- '# Build Loop Progress — Iteration %d/%d\n\n' "${ITERATION:-0}" "${MAX_ITERATIONS:-0}"
411
+ printf -- '## Status Summary\n'
412
+ printf -- '- **Tests**: %s\n' "$test_summary"
413
+ printf -- '- **Session Restart**: %d/%d\n' "${RESTART_COUNT:-0}" "${MAX_RESTARTS:-0}"
414
+ printf -- '- **Consecutive Failures**: %d\n' "${CONSECUTIVE_FAILURES:-0}"
415
+ printf -- '- **Updated**: %s\n\n' "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
416
+
417
+ if [[ -n "$existing_content" ]]; then
418
+ printf -- '## Previous Content\n%s\n' "$existing_content"
419
+ fi
420
+
421
+ if [[ -n "$antipatterns" ]]; then
422
+ printf -- '## Anti-Patterns to Avoid%s\n' "$antipatterns"
423
+ fi
424
+
425
+ } > "$tmp_progress" 2>/dev/null
426
+
427
+ if mv "$tmp_progress" "$progress_file" 2>/dev/null; then
428
+ emit_event "session.progress_enhanced" "progress_file=$progress_file" "iteration=${ITERATION:-0}" 2>/dev/null || true
429
+ return 0
430
+ else
431
+ warn "Failed to write enhanced progress to $progress_file"
432
+ rm -f "$tmp_progress"
433
+ return 1
434
+ fi
435
+ }
436
+
437
+ # ─── Main Integration Points ──────────────────────────────────────────────
438
+
439
+ # Called before session restart to save context
440
+ restart_before_restart() {
441
+ info "Capturing restart state and briefing..."
442
+
443
+ # Capture comprehensive state
444
+ local state_file
445
+ state_file=$(restart_capture_state) || {
446
+ error "Failed to capture restart state"
447
+ return 1
448
+ }
449
+
450
+ # Generate briefing for new session
451
+ local briefing_file
452
+ briefing_file=$(restart_generate_briefing "$state_file") || {
453
+ error "Failed to generate restart briefing"
454
+ return 1
455
+ }
456
+
457
+ # Detect restart reason
458
+ local reason
459
+ reason=$(restart_detect_reason) || true
460
+
461
+ # Suggest strategy based on reason
462
+ local strategy
463
+ strategy=$(restart_suggest_strategy "$reason") || true
464
+
465
+ # Track this restart across session history
466
+ restart_track_across_sessions || {
467
+ warn "Failed to track restart in history (continuing anyway)"
468
+ }
469
+
470
+ # Enhance progress.md with anti-patterns and summary
471
+ restart_enhance_progress_md || {
472
+ warn "Failed to enhance progress.md (continuing anyway)"
473
+ }
474
+
475
+ success "Restart preparation complete"
476
+ info "State: $state_file"
477
+ info "Briefing: $briefing_file"
478
+ info "Strategy: $strategy"
479
+
480
+ return 0
481
+ }
482
+
483
+ # Called after session restart to inject briefing into prompt
484
+ restart_inject_briefing() {
485
+ local briefing_file="${1:-${ARTIFACTS_DIR:-${LOG_DIR}}/restart-briefing.md}"
486
+
487
+ if [[ ! -f "$briefing_file" ]]; then
488
+ return 0 # No briefing to inject
489
+ fi
490
+
491
+ # Return briefing content for prompt injection
492
+ cat "$briefing_file" 2>/dev/null || true
493
+ }