oc-pilot 0.160.0 → 0.161.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 (378) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/CONTRIBUTING.md +5 -0
  3. package/Dockerfile +2 -1
  4. package/README.md +42 -1261
  5. package/README.ru.md +52 -1144
  6. package/action.yml +8 -2
  7. package/dist/cli.js +62 -179
  8. package/dist/cli.js.map +1 -1
  9. package/dist/command-groups.js +52 -0
  10. package/dist/command-groups.js.map +1 -0
  11. package/dist/command-registry.js +92 -0
  12. package/dist/command-registry.js.map +1 -0
  13. package/dist/commands/apoptosis.js +16 -1
  14. package/dist/commands/apoptosis.js.map +1 -1
  15. package/dist/commands/blindfold.js +30 -2
  16. package/dist/commands/blindfold.js.map +1 -1
  17. package/dist/commands/butterfly.js +9 -5
  18. package/dist/commands/butterfly.js.map +1 -1
  19. package/dist/commands/cache.js +24 -14
  20. package/dist/commands/cache.js.map +1 -1
  21. package/dist/commands/deps.js +30 -0
  22. package/dist/commands/deps.js.map +1 -1
  23. package/dist/commands/doctor.js +11 -448
  24. package/dist/commands/doctor.js.map +1 -1
  25. package/dist/commands/fix.js +38 -345
  26. package/dist/commands/fix.js.map +1 -1
  27. package/dist/commands/flight.js +15 -33
  28. package/dist/commands/flight.js.map +1 -1
  29. package/dist/commands/hygiene.js +47 -0
  30. package/dist/commands/hygiene.js.map +1 -0
  31. package/dist/commands/metrics.js +49 -0
  32. package/dist/commands/metrics.js.map +1 -0
  33. package/dist/commands/preflight.js +11 -6
  34. package/dist/commands/preflight.js.map +1 -1
  35. package/dist/commands/review.js +44 -215
  36. package/dist/commands/review.js.map +1 -1
  37. package/dist/commands/setup.js +10 -331
  38. package/dist/commands/setup.js.map +1 -1
  39. package/dist/commands/test-gen.js +25 -246
  40. package/dist/commands/test-gen.js.map +1 -1
  41. package/dist/core/blindfold.js +63 -0
  42. package/dist/core/blindfold.js.map +1 -1
  43. package/dist/core/butterfly.js +12 -0
  44. package/dist/core/butterfly.js.map +1 -1
  45. package/dist/core/cache.js +161 -56
  46. package/dist/core/cache.js.map +1 -1
  47. package/dist/core/deps-registry.js +169 -0
  48. package/dist/core/deps-registry.js.map +1 -0
  49. package/dist/core/doctor.js +448 -0
  50. package/dist/core/doctor.js.map +1 -0
  51. package/dist/core/expiry.js +39 -0
  52. package/dist/core/expiry.js.map +1 -0
  53. package/dist/core/fix.js +298 -0
  54. package/dist/core/fix.js.map +1 -0
  55. package/dist/core/flight/bundle-report.js +163 -0
  56. package/dist/core/flight/bundle-report.js.map +1 -0
  57. package/dist/core/flight/bundles.js +162 -0
  58. package/dist/core/flight/bundles.js.map +1 -0
  59. package/dist/core/flight/compare-reports.js +107 -0
  60. package/dist/core/flight/compare-reports.js.map +1 -0
  61. package/dist/core/flight/comparison.js +94 -0
  62. package/dist/core/flight/comparison.js.map +1 -0
  63. package/dist/core/flight/diffs.js +67 -0
  64. package/dist/core/flight/diffs.js.map +1 -0
  65. package/dist/core/flight/events.js +78 -0
  66. package/dist/core/flight/events.js.map +1 -0
  67. package/dist/core/flight/html-reports.js +73 -0
  68. package/dist/core/flight/html-reports.js.map +1 -0
  69. package/dist/core/flight/inspection.js +28 -0
  70. package/dist/core/flight/inspection.js.map +1 -0
  71. package/dist/core/flight/proof.js +135 -0
  72. package/dist/core/flight/proof.js.map +1 -0
  73. package/dist/core/flight/queries.js +218 -0
  74. package/dist/core/flight/queries.js.map +1 -0
  75. package/dist/core/flight/query-reports.js +35 -0
  76. package/dist/core/flight/query-reports.js.map +1 -0
  77. package/dist/core/flight/runner.js +141 -0
  78. package/dist/core/flight/runner.js.map +1 -0
  79. package/dist/core/flight/session-reports.js +166 -0
  80. package/dist/core/flight/session-reports.js.map +1 -0
  81. package/dist/core/flight/sessions.js +252 -0
  82. package/dist/core/flight/sessions.js.map +1 -0
  83. package/dist/core/flight/types.js +2 -0
  84. package/dist/core/flight/types.js.map +1 -0
  85. package/dist/core/flight/worktree-reports.js +39 -0
  86. package/dist/core/flight/worktree-reports.js.map +1 -0
  87. package/dist/core/flight/worktrees.js +96 -0
  88. package/dist/core/flight/worktrees.js.map +1 -0
  89. package/dist/core/flight.js +16 -1761
  90. package/dist/core/flight.js.map +1 -1
  91. package/dist/core/hygiene.js +44 -0
  92. package/dist/core/hygiene.js.map +1 -0
  93. package/dist/core/metrics.js +172 -0
  94. package/dist/core/metrics.js.map +1 -0
  95. package/dist/core/preflight-run.js +5 -2
  96. package/dist/core/preflight-run.js.map +1 -1
  97. package/dist/core/preflight-sarif.js +64 -0
  98. package/dist/core/preflight-sarif.js.map +1 -0
  99. package/dist/core/review-publication.js +57 -0
  100. package/dist/core/review-publication.js.map +1 -0
  101. package/dist/core/review.js +148 -0
  102. package/dist/core/review.js.map +1 -0
  103. package/dist/core/sarif.js +21 -5
  104. package/dist/core/sarif.js.map +1 -1
  105. package/dist/core/setup.js +333 -0
  106. package/dist/core/setup.js.map +1 -0
  107. package/dist/core/test-gen.js +224 -0
  108. package/dist/core/test-gen.js.map +1 -0
  109. package/dist/core/test-weakening.js +58 -16
  110. package/dist/core/test-weakening.js.map +1 -1
  111. package/dist/mcp.js +135 -17
  112. package/dist/mcp.js.map +1 -1
  113. package/dist/version.js +1 -1
  114. package/docs/integrations.md +121 -6
  115. package/docs/reference.md +1318 -0
  116. package/docs/reference.ru.md +1191 -0
  117. package/package.json +5 -4
  118. package/skills/agent-self-review/SKILL.md +1 -1
  119. package/skills/commit-discipline/SKILL.md +1 -1
  120. package/skills/secure-diff-gate/SKILL.md +1 -1
  121. package/skills/stack-review-packs/SKILL.md +1 -1
  122. package/skills/test-failure-triage/SKILL.md +1 -1
  123. package/dist/cli.test.js +0 -2493
  124. package/dist/cli.test.js.map +0 -1
  125. package/dist/commands/commit.test.js +0 -160
  126. package/dist/commands/commit.test.js.map +0 -1
  127. package/dist/commands/day.test.js +0 -45
  128. package/dist/commands/day.test.js.map +0 -1
  129. package/dist/commands/doctor.test.js +0 -189
  130. package/dist/commands/doctor.test.js.map +0 -1
  131. package/dist/commands/init.test.js +0 -138
  132. package/dist/commands/init.test.js.map +0 -1
  133. package/dist/commands/install-hook.test.js +0 -107
  134. package/dist/commands/install-hook.test.js.map +0 -1
  135. package/dist/commands/replay.test.js +0 -125
  136. package/dist/commands/replay.test.js.map +0 -1
  137. package/dist/commands/review.test.js +0 -160
  138. package/dist/commands/review.test.js.map +0 -1
  139. package/dist/commands/slop.test.js +0 -135
  140. package/dist/commands/slop.test.js.map +0 -1
  141. package/dist/core/alien-dna.test.js +0 -117
  142. package/dist/core/alien-dna.test.js.map +0 -1
  143. package/dist/core/anthropic.test.js +0 -116
  144. package/dist/core/anthropic.test.js.map +0 -1
  145. package/dist/core/anti-regression.test.js +0 -154
  146. package/dist/core/anti-regression.test.js.map +0 -1
  147. package/dist/core/antibody.test.js +0 -142
  148. package/dist/core/antibody.test.js.map +0 -1
  149. package/dist/core/apoptosis.test.js +0 -104
  150. package/dist/core/apoptosis.test.js.map +0 -1
  151. package/dist/core/aql.test.js +0 -64
  152. package/dist/core/aql.test.js.map +0 -1
  153. package/dist/core/arch-diff.test.js +0 -93
  154. package/dist/core/arch-diff.test.js.map +0 -1
  155. package/dist/core/authz.test.js +0 -125
  156. package/dist/core/authz.test.js.map +0 -1
  157. package/dist/core/autopsy.test.js +0 -106
  158. package/dist/core/autopsy.test.js.map +0 -1
  159. package/dist/core/bankruptcy.test.js +0 -91
  160. package/dist/core/bankruptcy.test.js.map +0 -1
  161. package/dist/core/baseline.test.js +0 -91
  162. package/dist/core/baseline.test.js.map +0 -1
  163. package/dist/core/battle.test.js +0 -116
  164. package/dist/core/battle.test.js.map +0 -1
  165. package/dist/core/beacon.test.js +0 -114
  166. package/dist/core/beacon.test.js.map +0 -1
  167. package/dist/core/blindfold.test.js +0 -77
  168. package/dist/core/blindfold.test.js.map +0 -1
  169. package/dist/core/boundaries.test.js +0 -62
  170. package/dist/core/boundaries.test.js.map +0 -1
  171. package/dist/core/bounty.test.js +0 -82
  172. package/dist/core/bounty.test.js.map +0 -1
  173. package/dist/core/brag.test.js +0 -43
  174. package/dist/core/brag.test.js.map +0 -1
  175. package/dist/core/butterfly.test.js +0 -146
  176. package/dist/core/butterfly.test.js.map +0 -1
  177. package/dist/core/cache.test.js +0 -159
  178. package/dist/core/cache.test.js.map +0 -1
  179. package/dist/core/chronos.test.js +0 -139
  180. package/dist/core/chronos.test.js.map +0 -1
  181. package/dist/core/cinema.test.js +0 -73
  182. package/dist/core/cinema.test.js.map +0 -1
  183. package/dist/core/clairvoyant.test.js +0 -144
  184. package/dist/core/clairvoyant.test.js.map +0 -1
  185. package/dist/core/compliance.test.js +0 -123
  186. package/dist/core/compliance.test.js.map +0 -1
  187. package/dist/core/config.test.js +0 -211
  188. package/dist/core/config.test.js.map +0 -1
  189. package/dist/core/contract-drift.test.js +0 -166
  190. package/dist/core/contract-drift.test.js.map +0 -1
  191. package/dist/core/cost.test.js +0 -103
  192. package/dist/core/cost.test.js.map +0 -1
  193. package/dist/core/coverage.test.js +0 -190
  194. package/dist/core/coverage.test.js.map +0 -1
  195. package/dist/core/cuckoo.test.js +0 -98
  196. package/dist/core/cuckoo.test.js.map +0 -1
  197. package/dist/core/deps-fix.test.js +0 -176
  198. package/dist/core/deps-fix.test.js.map +0 -1
  199. package/dist/core/deps-health.test.js +0 -230
  200. package/dist/core/deps-health.test.js.map +0 -1
  201. package/dist/core/deps-why.test.js +0 -175
  202. package/dist/core/deps-why.test.js.map +0 -1
  203. package/dist/core/deps.test.js +0 -88
  204. package/dist/core/deps.test.js.map +0 -1
  205. package/dist/core/diff.test.js +0 -94
  206. package/dist/core/diff.test.js.map +0 -1
  207. package/dist/core/echo.test.js +0 -90
  208. package/dist/core/echo.test.js.map +0 -1
  209. package/dist/core/ecosystem-verify.test.js +0 -158
  210. package/dist/core/ecosystem-verify.test.js.map +0 -1
  211. package/dist/core/engine-preset.test.js +0 -60
  212. package/dist/core/engine-preset.test.js.map +0 -1
  213. package/dist/core/engine.test.js +0 -206
  214. package/dist/core/engine.test.js.map +0 -1
  215. package/dist/core/env-sync.test.js +0 -99
  216. package/dist/core/env-sync.test.js.map +0 -1
  217. package/dist/core/file-context.test.js +0 -58
  218. package/dist/core/file-context.test.js.map +0 -1
  219. package/dist/core/findings-baseline.test.js +0 -77
  220. package/dist/core/findings-baseline.test.js.map +0 -1
  221. package/dist/core/findings.test.js +0 -62
  222. package/dist/core/findings.test.js.map +0 -1
  223. package/dist/core/flaky.test.js +0 -97
  224. package/dist/core/flaky.test.js.map +0 -1
  225. package/dist/core/flight.test.js +0 -853
  226. package/dist/core/flight.test.js.map +0 -1
  227. package/dist/core/format.test.js +0 -26
  228. package/dist/core/format.test.js.map +0 -1
  229. package/dist/core/fuzz.test.js +0 -121
  230. package/dist/core/fuzz.test.js.map +0 -1
  231. package/dist/core/gitlab.test.js +0 -199
  232. package/dist/core/gitlab.test.js.map +0 -1
  233. package/dist/core/hemorrhage.test.js +0 -138
  234. package/dist/core/hemorrhage.test.js.map +0 -1
  235. package/dist/core/hivemind.test.js +0 -79
  236. package/dist/core/hivemind.test.js.map +0 -1
  237. package/dist/core/hologram.test.js +0 -124
  238. package/dist/core/hologram.test.js.map +0 -1
  239. package/dist/core/honeypot.test.js +0 -106
  240. package/dist/core/honeypot.test.js.map +0 -1
  241. package/dist/core/hooks.test.js +0 -132
  242. package/dist/core/hooks.test.js.map +0 -1
  243. package/dist/core/hyper-chamber.test.js +0 -105
  244. package/dist/core/hyper-chamber.test.js.map +0 -1
  245. package/dist/core/impact.test.js +0 -105
  246. package/dist/core/impact.test.js.map +0 -1
  247. package/dist/core/import-graph.test.js +0 -68
  248. package/dist/core/import-graph.test.js.map +0 -1
  249. package/dist/core/injection-scan.test.js +0 -100
  250. package/dist/core/injection-scan.test.js.map +0 -1
  251. package/dist/core/injection.test.js +0 -45
  252. package/dist/core/injection.test.js.map +0 -1
  253. package/dist/core/intent.test.js +0 -86
  254. package/dist/core/intent.test.js.map +0 -1
  255. package/dist/core/invariants.test.js +0 -87
  256. package/dist/core/invariants.test.js.map +0 -1
  257. package/dist/core/lang.test.js +0 -22
  258. package/dist/core/lang.test.js.map +0 -1
  259. package/dist/core/last-review.test.js +0 -97
  260. package/dist/core/last-review.test.js.map +0 -1
  261. package/dist/core/lockfile-support.test.js +0 -112
  262. package/dist/core/lockfile-support.test.js.map +0 -1
  263. package/dist/core/lockfile.test.js +0 -203
  264. package/dist/core/lockfile.test.js.map +0 -1
  265. package/dist/core/mayday.test.js +0 -117
  266. package/dist/core/mayday.test.js.map +0 -1
  267. package/dist/core/mirage.test.js +0 -120
  268. package/dist/core/mirage.test.js.map +0 -1
  269. package/dist/core/mitosis.test.js +0 -170
  270. package/dist/core/mitosis.test.js.map +0 -1
  271. package/dist/core/mock-leak.test.js +0 -79
  272. package/dist/core/mock-leak.test.js.map +0 -1
  273. package/dist/core/mutation.test.js +0 -104
  274. package/dist/core/mutation.test.js.map +0 -1
  275. package/dist/core/opencode.test.js +0 -68
  276. package/dist/core/opencode.test.js.map +0 -1
  277. package/dist/core/oracle.test.js +0 -136
  278. package/dist/core/oracle.test.js.map +0 -1
  279. package/dist/core/osv.test.js +0 -173
  280. package/dist/core/osv.test.js.map +0 -1
  281. package/dist/core/output-format.test.js +0 -102
  282. package/dist/core/output-format.test.js.map +0 -1
  283. package/dist/core/pack.test.js +0 -129
  284. package/dist/core/pack.test.js.map +0 -1
  285. package/dist/core/passport.test.js +0 -173
  286. package/dist/core/passport.test.js.map +0 -1
  287. package/dist/core/patch.test.js +0 -70
  288. package/dist/core/patch.test.js.map +0 -1
  289. package/dist/core/phantom.test.js +0 -58
  290. package/dist/core/phantom.test.js.map +0 -1
  291. package/dist/core/polygraph.test.js +0 -110
  292. package/dist/core/polygraph.test.js.map +0 -1
  293. package/dist/core/pr-comment.test.js +0 -53
  294. package/dist/core/pr-comment.test.js.map +0 -1
  295. package/dist/core/pr-review.test.js +0 -62
  296. package/dist/core/pr-review.test.js.map +0 -1
  297. package/dist/core/preflight.test.js +0 -242
  298. package/dist/core/preflight.test.js.map +0 -1
  299. package/dist/core/presets.test.js +0 -79
  300. package/dist/core/presets.test.js.map +0 -1
  301. package/dist/core/project.test.js +0 -75
  302. package/dist/core/project.test.js.map +0 -1
  303. package/dist/core/prompt.golden.test.js +0 -74
  304. package/dist/core/prompt.golden.test.js.map +0 -1
  305. package/dist/core/prompt.test.js +0 -122
  306. package/dist/core/prompt.test.js.map +0 -1
  307. package/dist/core/quarantine.test.js +0 -98
  308. package/dist/core/quarantine.test.js.map +0 -1
  309. package/dist/core/readiness-fix.test.js +0 -127
  310. package/dist/core/readiness-fix.test.js.map +0 -1
  311. package/dist/core/readiness.test.js +0 -318
  312. package/dist/core/readiness.test.js.map +0 -1
  313. package/dist/core/receipt.test.js +0 -193
  314. package/dist/core/receipt.test.js.map +0 -1
  315. package/dist/core/reviewers.test.js +0 -105
  316. package/dist/core/reviewers.test.js.map +0 -1
  317. package/dist/core/roast.test.js +0 -19
  318. package/dist/core/roast.test.js.map +0 -1
  319. package/dist/core/router.test.js +0 -157
  320. package/dist/core/router.test.js.map +0 -1
  321. package/dist/core/rules.test.js +0 -72
  322. package/dist/core/rules.test.js.map +0 -1
  323. package/dist/core/sarif.test.js +0 -60
  324. package/dist/core/sarif.test.js.map +0 -1
  325. package/dist/core/sast.test.js +0 -119
  326. package/dist/core/sast.test.js.map +0 -1
  327. package/dist/core/sbom.test.js +0 -81
  328. package/dist/core/sbom.test.js.map +0 -1
  329. package/dist/core/scalpel.test.js +0 -132
  330. package/dist/core/scalpel.test.js.map +0 -1
  331. package/dist/core/second-opinion.test.js +0 -89
  332. package/dist/core/second-opinion.test.js.map +0 -1
  333. package/dist/core/secrets.test.js +0 -194
  334. package/dist/core/secrets.test.js.map +0 -1
  335. package/dist/core/shadow.test.js +0 -50
  336. package/dist/core/shadow.test.js.map +0 -1
  337. package/dist/core/skeptic.test.js +0 -106
  338. package/dist/core/skeptic.test.js.map +0 -1
  339. package/dist/core/slicing.test.js +0 -287
  340. package/dist/core/slicing.test.js.map +0 -1
  341. package/dist/core/slop/dead-exports.test.js +0 -29
  342. package/dist/core/slop/dead-exports.test.js.map +0 -1
  343. package/dist/core/slop/slop.test.js +0 -160
  344. package/dist/core/slop/slop.test.js.map +0 -1
  345. package/dist/core/slop/test-debt.test.js +0 -114
  346. package/dist/core/slop/test-debt.test.js.map +0 -1
  347. package/dist/core/snapshot.test.js +0 -101
  348. package/dist/core/snapshot.test.js.map +0 -1
  349. package/dist/core/snippets.test.js +0 -55
  350. package/dist/core/snippets.test.js.map +0 -1
  351. package/dist/core/stats.test.js +0 -86
  352. package/dist/core/stats.test.js.map +0 -1
  353. package/dist/core/suppressions.test.js +0 -98
  354. package/dist/core/suppressions.test.js.map +0 -1
  355. package/dist/core/test-delta.test.js +0 -41
  356. package/dist/core/test-delta.test.js.map +0 -1
  357. package/dist/core/test-plan.test.js +0 -99
  358. package/dist/core/test-plan.test.js.map +0 -1
  359. package/dist/core/test-weakening.test.js +0 -114
  360. package/dist/core/test-weakening.test.js.map +0 -1
  361. package/dist/core/tree-scan.test.js +0 -58
  362. package/dist/core/tree-scan.test.js.map +0 -1
  363. package/dist/core/tribunal.test.js +0 -52
  364. package/dist/core/tribunal.test.js.map +0 -1
  365. package/dist/core/vaccine.test.js +0 -139
  366. package/dist/core/vaccine.test.js.map +0 -1
  367. package/dist/core/warden.test.js +0 -121
  368. package/dist/core/warden.test.js.map +0 -1
  369. package/dist/mcp-http.test.js +0 -146
  370. package/dist/mcp-http.test.js.map +0 -1
  371. package/dist/mcp-prompts.test.js +0 -160
  372. package/dist/mcp-prompts.test.js.map +0 -1
  373. package/dist/mcp.test.js +0 -2108
  374. package/dist/mcp.test.js.map +0 -1
  375. package/dist/setup.test.js +0 -215
  376. package/dist/setup.test.js.map +0 -1
  377. package/dist/skills.test.js +0 -293
  378. package/dist/skills.test.js.map +0 -1
@@ -1,1762 +1,17 @@
1
- import { spawnSync } from "node:child_process";
2
- import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, } from "node:fs";
4
- import { tmpdir } from "node:os";
5
- import { isAbsolute, join, resolve } from "node:path";
6
- import { PilotError } from "./errors.js";
7
- import { getRepoRoot, runGit } from "./git.js";
8
- const MAX_TAIL = 8000;
9
- function isAbsoluteLike(value) {
10
- return /^(?:[A-Za-z]:[\\/]|\/|\\\\)/.test(value);
11
- }
12
- function canonicalJson(value) {
13
- if (value === undefined)
14
- return "null";
15
- if (value === null || typeof value !== "object")
16
- return JSON.stringify(value);
17
- if (Array.isArray(value))
18
- return `[${value.map(canonicalJson).join(",")}]`;
19
- const record = value;
20
- const keys = Object.keys(record).filter((key) => record[key] !== undefined).sort();
21
- return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
22
- }
23
- export function flightEventHash(event) {
24
- return `sha256:${createHash("sha256").update(canonicalJson(event)).digest("hex")}`;
25
- }
26
- export function flightsRoot(cwd) {
27
- const repoRoot = getRepoRoot(cwd);
28
- const result = runGit(["rev-parse", "--git-dir"], repoRoot);
29
- if (result.status !== 0) {
30
- throw new PilotError("Не удалось найти git-каталог для полёта.", {
31
- hint: "Запустите команду внутри git-репозитория.",
32
- });
33
- }
34
- const value = result.stdout.trim();
35
- const gitDir = isAbsoluteLike(value) || isAbsolute(value) ? value : resolve(repoRoot, value);
36
- return join(gitDir, "oc-pilot", "flights");
37
- }
38
- export function newFlightId(now = new Date()) {
39
- const stamp = now.toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
40
- return `${stamp}-${randomBytes(3).toString("hex")}`;
41
- }
42
- function sessionDir(root, id) {
43
- if (!/^[A-Za-z0-9._-]+$/.test(id) || id === "." || id === "..") {
44
- throw new PilotError(`Некорректный идентификатор полёта: ${id}`, {
45
- hint: "Используйте идентификатор из oc-pilot flight list.",
46
- exitCode: 2,
47
- });
48
- }
49
- return join(root, id);
50
- }
51
- function metaPath(dir) {
52
- return join(dir, "meta.json");
53
- }
54
- function eventsPath(dir) {
55
- return join(dir, "events.jsonl");
56
- }
57
- function currentPath(root) {
58
- return join(root, "current");
59
- }
60
- function readMeta(dir) {
61
- const text = readFileSync(metaPath(dir), "utf8");
62
- return JSON.parse(text);
63
- }
64
- function writeMeta(dir, meta) {
65
- writeFileSync(metaPath(dir), `${JSON.stringify(meta, null, 2)}\n`, "utf8");
66
- }
67
- export function readFlightEvents(dir) {
68
- const file = eventsPath(dir);
69
- if (!existsSync(file))
70
- return [];
71
- const text = readFileSync(file, "utf8");
72
- const events = [];
73
- for (const [index, line] of text.split(/\r?\n/).entries()) {
74
- if (!line.trim())
75
- continue;
76
- let event;
77
- try {
78
- event = JSON.parse(line);
79
- }
80
- catch {
81
- throw new PilotError(`Повреждён журнал полёта: строка ${index + 1}.`, {
82
- hint: "Журнал нельзя прочитать; проверьте events.jsonl вручную.",
83
- });
84
- }
85
- events.push(event);
86
- }
87
- return events;
88
- }
89
- export function appendFlightEvent(dir, kind, payload) {
90
- const events = readFlightEvents(dir);
91
- const last = events.at(-1);
92
- const base = {
93
- seq: (last?.seq ?? 0) + 1,
94
- ts: new Date().toISOString(),
95
- kind,
96
- prev: last?.hash ?? "genesis",
97
- payload,
98
- };
99
- const event = { ...base, hash: flightEventHash(base) };
100
- appendFileSync(eventsPath(dir), `${JSON.stringify(event)}\n`, "utf8");
101
- return event;
102
- }
103
- export function addFlightNote(cwd, text) {
104
- const note = text.trim();
105
- if (note.length === 0) {
106
- throw new PilotError("Пустая заметка.", {
107
- hint: "Передайте текст: oc-pilot flight note \"...\".",
108
- exitCode: 2,
109
- });
110
- }
111
- const session = requireActiveFlight(cwd);
112
- const event = appendFlightEvent(session.dir, "note", { text: note });
113
- return { id: session.meta.id, seq: event.seq, note };
114
- }
115
- export function verifyFlightEvents(events) {
116
- const errors = [];
117
- let previous = "genesis";
118
- for (const [index, event] of events.entries()) {
119
- if (event.seq !== index + 1) {
120
- errors.push(`Событие ${index + 1}: ожидался seq ${index + 1}, получен ${event.seq}.`);
121
- }
122
- if (event.prev !== previous) {
123
- errors.push(`Событие ${index + 1}: разорвана цепочка prev.`);
124
- }
125
- const { hash, ...rest } = event;
126
- if (flightEventHash(rest) !== hash) {
127
- errors.push(`Событие ${index + 1}: хеш не совпадает.`);
128
- }
129
- previous = event.hash;
130
- }
131
- if (events.length === 0)
132
- errors.push("Журнал пуст.");
133
- return { valid: errors.length === 0, events: events.length, errors };
134
- }
135
- export function startFlight(cwd, name) {
136
- const root = flightsRoot(cwd);
137
- mkdirSync(root, { recursive: true });
138
- const current = currentPath(root);
139
- if (existsSync(current)) {
140
- const existingId = readFileSync(current, "utf8").trim();
141
- if (existingId && existsSync(sessionDir(root, existingId))) {
142
- throw new PilotError(`Уже идёт полёт ${existingId}.`, {
143
- hint: "Завершите его: oc-pilot flight end.",
144
- });
145
- }
146
- rmSync(current, { force: true });
147
- }
148
- const repoRoot = getRepoRoot(cwd);
149
- const id = newFlightId();
150
- const dir = sessionDir(root, id);
151
- mkdirSync(dir, { recursive: true });
152
- const head = runGit(["rev-parse", "--verify", "HEAD"], repoRoot);
153
- const branch = runGit(["rev-parse", "--abbrev-ref", "HEAD"], repoRoot);
154
- const meta = {
155
- id,
156
- name,
157
- startedAt: new Date().toISOString(),
158
- cwd: repoRoot,
159
- baseCommit: head.status === 0 ? head.stdout.trim() : null,
160
- branch: branch.status === 0 ? branch.stdout.trim() : null,
161
- };
162
- writeMeta(dir, meta);
163
- appendFlightEvent(dir, "session.start", {
164
- name,
165
- cwd: meta.cwd,
166
- baseCommit: meta.baseCommit,
167
- branch: meta.branch,
168
- });
169
- writeFileSync(current, `${id}\n`, "utf8");
170
- return { dir, meta, events: readFlightEvents(dir) };
171
- }
172
- export function activeFlight(cwd) {
173
- const root = flightsRoot(cwd);
174
- const current = currentPath(root);
175
- if (!existsSync(current))
176
- return undefined;
177
- const id = readFileSync(current, "utf8").trim();
178
- if (!id)
179
- return undefined;
180
- const dir = sessionDir(root, id);
181
- if (!existsSync(metaPath(dir)))
182
- return undefined;
183
- const meta = readMeta(dir);
184
- return { dir, meta, events: readFlightEvents(dir) };
185
- }
186
- export function requireActiveFlight(cwd) {
187
- const session = activeFlight(cwd);
188
- if (!session) {
189
- throw new PilotError("Полёт не запущен.", {
190
- hint: "Начните: oc-pilot flight start --name \"...\".",
191
- exitCode: 2,
192
- });
193
- }
194
- return session;
195
- }
196
- function runGitWithEnv(args, cwd, env) {
197
- const result = spawnSync("git", args, {
198
- cwd,
199
- encoding: "utf8",
200
- env,
201
- maxBuffer: 16 * 1024 * 1024,
202
- windowsHide: true,
203
- });
204
- return {
205
- status: result.status,
206
- stdout: result.stdout ?? "",
207
- stderr: result.stderr ?? "",
208
- };
209
- }
210
- export function createCheckpoint(cwd, label) {
211
- const session = requireActiveFlight(cwd);
212
- const wanted = label.trim();
213
- if (wanted.length > 0 &&
214
- session.events.some((event) => event.kind === "file.checkpoint" &&
215
- String(event.payload.label ?? "") === wanted)) {
216
- throw new PilotError(`Чекпоинт с меткой «${wanted}» уже есть.`, {
217
- hint: "Выберите другую метку: --label <имя>.",
218
- exitCode: 2,
219
- });
220
- }
221
- const repoRoot = getRepoRoot(cwd);
222
- const indexFile = join(session.dir, `index-${randomBytes(4).toString("hex")}.tmp`);
223
- const env = {
224
- ...process.env,
225
- GIT_INDEX_FILE: indexFile,
226
- GIT_AUTHOR_NAME: "oc-pilot flight",
227
- GIT_AUTHOR_EMAIL: "flight@oc-pilot.local",
228
- GIT_COMMITTER_NAME: "oc-pilot flight",
229
- GIT_COMMITTER_EMAIL: "flight@oc-pilot.local",
230
- GIT_PAGER: "cat",
231
- GIT_TERMINAL_PROMPT: "0",
232
- };
233
- try {
234
- const added = runGitWithEnv(["add", "-A"], repoRoot, env);
235
- if (added.status !== 0) {
236
- throw new PilotError("Не удалось подготовить снимок рабочего дерева.", {
237
- hint: added.stderr.trim() || "Проверьте состояние git-индекса.",
238
- });
239
- }
240
- const treeResult = runGitWithEnv(["write-tree"], repoRoot, env);
241
- if (treeResult.status !== 0) {
242
- throw new PilotError("Не удалось записать дерево снимка.", {
243
- hint: treeResult.stderr.trim() || "Проверьте git-репозиторий.",
244
- });
245
- }
246
- const tree = treeResult.stdout.trim();
247
- const head = runGit(["rev-parse", "--verify", "HEAD"], repoRoot);
248
- const args = ["commit-tree", tree];
249
- if (head.status === 0)
250
- args.push("-p", head.stdout.trim());
251
- args.push("-m", `oc-pilot flight checkpoint: ${label}`);
252
- const commitResult = runGitWithEnv(args, repoRoot, env);
253
- if (commitResult.status !== 0) {
254
- throw new PilotError("Не удалось создать снимок полёта.", {
255
- hint: commitResult.stderr.trim() || "Проверьте git-репозиторий.",
256
- });
257
- }
258
- const checkpoint = {
259
- label,
260
- tree,
261
- commit: commitResult.stdout.trim(),
262
- createdAt: new Date().toISOString(),
263
- };
264
- appendFlightEvent(session.dir, "file.checkpoint", { ...checkpoint });
265
- return checkpoint;
266
- }
267
- finally {
268
- rmSync(indexFile, { force: true });
269
- }
270
- }
271
- function tail(value) {
272
- if (value.length <= MAX_TAIL)
273
- return value;
274
- return value.slice(-MAX_TAIL);
275
- }
276
- export function execInFlight(cwd, command, options = {}) {
277
- const session = requireActiveFlight(cwd);
278
- if (command.length === 0) {
279
- throw new PilotError("Не указана команда для flight exec.", {
280
- hint: "Используйте: oc-pilot flight exec -- npm test.",
281
- });
282
- }
283
- const timeoutMs = options.timeoutMs ?? 600_000;
284
- const started = Date.now();
285
- const eventStart = appendFlightEvent(session.dir, "command.start", { command, timeoutMs });
286
- const result = spawnSync(command[0], command.slice(1), {
287
- cwd,
288
- encoding: "utf8",
289
- timeout: timeoutMs,
290
- maxBuffer: 32 * 1024 * 1024,
291
- windowsHide: true,
292
- });
293
- const durationMs = Date.now() - started;
294
- const timedOut = result.signal === "SIGTERM" ||
295
- result.error?.code === "ETIMEDOUT";
296
- const exitCode = result.status;
297
- const stdoutTail = tail(result.stdout ?? "");
298
- const stderrTail = tail(result.stderr ?? "");
299
- const eventEnd = appendFlightEvent(session.dir, "command.end", {
300
- command,
301
- exitCode,
302
- signal: result.signal,
303
- durationMs,
304
- timedOut,
305
- stdoutTail,
306
- stderrTail,
307
- error: result.error ? String(result.error.message) : undefined,
308
- });
309
- if (!options.quiet) {
310
- if (result.stdout)
311
- process.stdout.write(result.stdout);
312
- if (result.stderr)
313
- process.stderr.write(result.stderr);
314
- }
315
- return {
316
- command,
317
- exitCode,
318
- signal: result.signal,
319
- durationMs,
320
- timedOut,
321
- stdoutTail,
322
- stderrTail,
323
- eventStart,
324
- eventEnd,
325
- };
326
- }
327
- export function endFlight(cwd) {
328
- const session = requireActiveFlight(cwd);
329
- const checkpoints = session.events.filter((event) => event.kind === "file.checkpoint").length;
330
- const commands = session.events.filter((event) => event.kind === "command.start").length;
331
- const summary = {
332
- checkpoints,
333
- commands,
334
- durationMs: Date.now() - Date.parse(session.meta.startedAt),
335
- };
336
- appendFlightEvent(session.dir, "session.end", summary);
337
- rmSync(currentPath(flightsRoot(cwd)), { force: true });
338
- const events = readFlightEvents(session.dir);
339
- return { meta: session.meta, events, summary };
340
- }
341
- export function listFlights(cwd) {
342
- const root = flightsRoot(cwd);
343
- if (!existsSync(root))
344
- return [];
345
- const entries = [];
346
- for (const name of readdirSync(root)) {
347
- const dir = sessionDir(root, name);
348
- if (!existsSync(metaPath(dir)))
349
- continue;
350
- const meta = readMeta(dir);
351
- const events = readFlightEvents(dir);
352
- entries.push({
353
- ...meta,
354
- events: events.length,
355
- checkpoints: events.filter((event) => event.kind === "file.checkpoint").length,
356
- notes: events.filter((event) => event.kind === "note").length,
357
- ended: events.some((event) => event.kind === "session.end"),
358
- });
359
- }
360
- return entries.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
361
- }
362
- export function flightStats(cwd) {
363
- const flights = listFlights(cwd);
364
- const commands = new Map();
365
- let events = 0;
366
- let commandCount = 0;
367
- let notes = 0;
368
- let checkpoints = 0;
369
- let failedCommands = 0;
370
- let durationMs = 0;
371
- for (const entry of flights) {
372
- const show = showFlight(cwd, entry.id);
373
- events += show.events.length;
374
- checkpoints += entry.checkpoints;
375
- const startedAt = Date.parse(show.meta.startedAt);
376
- const endedAt = Date.parse(show.events.at(-1)?.ts ?? show.meta.startedAt);
377
- durationMs += Math.max(0, endedAt - startedAt);
378
- for (const event of show.events) {
379
- if (event.kind === "command.start")
380
- commandCount += 1;
381
- if (event.kind === "note")
382
- notes += 1;
383
- if (event.kind !== "command.end")
384
- continue;
385
- const payload = event.payload;
386
- const command = Array.isArray(payload.command)
387
- ? payload.command.filter((part) => typeof part === "string")
388
- : [];
389
- if (command.length === 0)
390
- continue;
391
- const key = JSON.stringify(command);
392
- const current = commands.get(key) ?? { command: command.join(" "), runs: 0, failures: 0 };
393
- current.runs += 1;
394
- if (payload.timedOut === true ||
395
- (typeof payload.exitCode === "number" && payload.exitCode !== 0)) {
396
- current.failures += 1;
397
- failedCommands += 1;
398
- }
399
- commands.set(key, current);
400
- }
401
- }
402
- const topCommands = [...commands.values()]
403
- .sort((left, right) => right.runs - left.runs || left.command.localeCompare(right.command))
404
- .slice(0, 5);
405
- return {
406
- total: flights.length,
407
- active: flights.filter((flight) => !flight.ended).length,
408
- ended: flights.filter((flight) => flight.ended).length,
409
- events,
410
- commands: commandCount,
411
- notes,
412
- checkpoints,
413
- failedCommands,
414
- durationMs,
415
- averageDurationMs: flights.length === 0 ? 0 : Math.round(durationMs / flights.length),
416
- last: flights[0]
417
- ? {
418
- id: flights[0].id,
419
- name: flights[0].name,
420
- startedAt: flights[0].startedAt,
421
- ended: flights[0].ended,
422
- }
423
- : undefined,
424
- topCommands,
425
- };
426
- }
427
- export function pruneFlights(cwd, options = {}) {
428
- const keep = options.keep ?? 20;
429
- if (!Number.isInteger(keep) || keep < 0) {
430
- throw new PilotError(`Некорректный --keep: ${String(options.keep)}`, {
431
- hint: "Укажите неотрицательное целое число полётов, которые нужно оставить.",
432
- });
433
- }
434
- const days = options.olderThanDays;
435
- if (days !== undefined && (!Number.isFinite(days) || days < 0)) {
436
- throw new PilotError(`Некорректный --older-than: ${String(days)}`, {
437
- hint: "Укажите неотрицательное число дней.",
438
- });
439
- }
440
- const active = activeFlight(cwd)?.meta.id ?? null;
441
- const cutoff = days === undefined ? undefined : Date.now() - days * 86_400_000;
442
- const flights = listFlights(cwd);
443
- const ended = flights.filter((flight) => flight.ended && flight.id !== active);
444
- const remove = new Set();
445
- ended.forEach((flight, index) => {
446
- if (index < keep)
447
- return;
448
- if (cutoff !== undefined && Date.parse(flight.startedAt) >= cutoff)
449
- return;
450
- remove.add(flight.id);
451
- });
452
- const removed = [];
453
- const root = flightsRoot(cwd);
454
- for (const id of remove) {
455
- removed.push(id);
456
- if (options.dryRun !== true)
457
- rmSync(sessionDir(root, id), { recursive: true, force: true });
458
- }
459
- return {
460
- removed,
461
- kept: flights.length - removed.length,
462
- active,
463
- dryRun: options.dryRun === true,
464
- };
465
- }
466
- export function deleteFlight(cwd, id, dryRun = false) {
467
- const target = id.trim();
468
- if (!target) {
469
- throw new PilotError("Не указан идентификатор полёта.", {
470
- hint: "Используйте: oc-pilot flight delete <id>.",
471
- exitCode: 2,
472
- });
473
- }
474
- const show = showFlight(cwd, target);
475
- const active = activeFlight(cwd);
476
- if (active && active.meta.id === show.meta.id) {
477
- throw new PilotError("Нельзя удалить активный полёт.", {
478
- hint: "Сначала завершите его: oc-pilot flight end.",
479
- });
480
- }
481
- const entry = listFlights(cwd).find((flight) => flight.id === show.meta.id);
482
- const result = {
483
- id: show.meta.id,
484
- name: show.meta.name,
485
- events: show.events.length,
486
- checkpoints: entry?.checkpoints ?? 0,
487
- removed: false,
488
- dryRun,
489
- };
490
- if (dryRun)
491
- return result;
492
- rmSync(sessionDir(flightsRoot(cwd), show.meta.id), { recursive: true, force: true });
493
- return { ...result, removed: true };
494
- }
495
- export function showFlight(cwd, id) {
496
- const root = flightsRoot(cwd);
497
- const resolved = resolveFlightId(cwd, id);
498
- const dir = sessionDir(root, resolved);
499
- if (!existsSync(metaPath(dir))) {
500
- throw new PilotError(`Полёт ${resolved} не найден.`, {
501
- hint: "Посмотрите список: oc-pilot flight list.",
502
- exitCode: 2,
503
- });
504
- }
505
- const meta = readMeta(dir);
506
- const events = readFlightEvents(dir);
507
- return { meta, events, verification: verifyFlightEvents(events) };
508
- }
509
- export function flightStatus(cwd) {
510
- const session = activeFlight(cwd);
511
- if (!session) {
512
- const last = listFlights(cwd)[0];
513
- return last ? { active: false, last } : { active: false };
514
- }
515
- const checkpoints = session.events.filter((event) => event.kind === "file.checkpoint").length;
516
- const commands = session.events.filter((event) => event.kind === "command.start").length;
517
- const notes = session.events.filter((event) => event.kind === "note").length;
518
- return {
519
- active: true,
520
- session,
521
- checkpoints,
522
- commands,
523
- notes,
524
- lastEvent: session.events.at(-1),
525
- };
526
- }
527
- export function renderFlightStatus(status) {
528
- if (!status.active || !status.session) {
529
- if (status.last) {
530
- return [
531
- "Полёт не запущен. Начните: oc-pilot flight start --name \"...\".",
532
- `Последний: ${status.last.id} (${status.last.name}), завершён: событий ${status.last.events}, чекпоинтов ${status.last.checkpoints}, заметок ${status.last.notes}`,
533
- ].join("\n");
534
- }
535
- return "Полёт не запущен. Начните: oc-pilot flight start --name \"...\".";
536
- }
537
- const { meta } = status.session;
538
- return [
539
- `Полёт ${meta.id} (${meta.name})`,
540
- `Начат: ${meta.startedAt}`,
541
- `Коммит: ${meta.baseCommit ?? "нет HEAD"}`,
542
- `Событий: ${status.session.events.length}; чекпоинтов: ${status.checkpoints ?? 0}; команд: ${status.commands ?? 0}; заметок: ${status.notes ?? 0}`,
543
- `Последнее событие: ${status.lastEvent?.kind ?? "нет"}`,
544
- ].join("\n");
545
- }
546
- export function renderFlightList(flights) {
547
- if (flights.length === 0)
548
- return "Полётов пока нет.";
549
- return flights
550
- .map((flight) => `${flight.id} ${flight.ended ? "завершён" : "активен"} ${flight.name} событий ${flight.events}, чекпоинтов ${flight.checkpoints}, заметок ${flight.notes}`)
551
- .join("\n");
552
- }
553
- function grepEventText(event) {
554
- if (event.kind === "note")
555
- return String(event.payload.text ?? "");
556
- if (event.kind === "file.checkpoint")
557
- return String(event.payload.label ?? "");
558
- if (event.kind === "session.start")
559
- return String(event.payload.name ?? "");
560
- if (event.kind === "command.start" || event.kind === "command.end") {
561
- const parts = [];
562
- if (Array.isArray(event.payload.command)) {
563
- parts.push(event.payload.command
564
- .filter((part) => typeof part === "string")
565
- .join(" "));
566
- }
567
- if (event.kind === "command.end") {
568
- if (typeof event.payload.stdoutTail === "string")
569
- parts.push(event.payload.stdoutTail);
570
- if (typeof event.payload.stderrTail === "string")
571
- parts.push(event.payload.stderrTail);
572
- }
573
- return parts.join("\n");
574
- }
575
- return "";
576
- }
577
- function grepShows(shows, query, limit, kind) {
578
- const needle = query.trim().toLowerCase();
579
- if (needle.length === 0) {
580
- throw new PilotError("Пустой поисковый запрос.", {
581
- hint: "Передайте текст: oc-pilot flight grep \"...\".",
582
- exitCode: 2,
583
- });
584
- }
585
- if (!Number.isInteger(limit) || limit < 1) {
586
- throw new PilotError(`Некорректный --limit: ${String(limit)}`, {
587
- hint: "Укажите положительное целое число.",
588
- exitCode: 2,
589
- });
590
- }
591
- const kindFilter = kind?.trim();
592
- if (kindFilter && !FLIGHT_EVENT_KINDS.includes(kindFilter)) {
593
- throw new PilotError(`Неизвестный тип события: ${kindFilter}`, {
594
- hint: `Доступно: ${FLIGHT_EVENT_KINDS.join(", ")}.`,
595
- exitCode: 2,
596
- });
597
- }
598
- const matches = [];
599
- let total = 0;
600
- for (const show of shows) {
601
- for (const event of show.events) {
602
- if (kindFilter && event.kind !== kindFilter)
603
- continue;
604
- const text = grepEventText(event);
605
- if (!text.toLowerCase().includes(needle))
606
- continue;
607
- total += 1;
608
- if (matches.length >= limit)
609
- continue;
610
- matches.push({
611
- id: show.meta.id,
612
- name: show.meta.name,
613
- seq: event.seq,
614
- kind: event.kind,
615
- ts: event.ts,
616
- text,
617
- });
618
- }
619
- }
620
- return { query, matches, total };
621
- }
622
- export function grepFlights(cwd, query, id, limit = 50, kind) {
623
- const shows = id
624
- ? [showFlight(cwd, id)]
625
- : listFlights(cwd).map((flight) => showFlight(cwd, flight.id));
626
- return grepShows(shows, query, limit, kind);
627
- }
628
- export function grepFlightBundle(file, query, limit = 50, kind) {
629
- return grepShows([flightShowFromBundle(loadFlightBundle(file))], query, limit, kind);
630
- }
631
- export function renderFlightGrep(result) {
632
- if (result.total === 0) {
633
- return `[FLIGHT GREP] по запросу «${result.query}» ничего не найдено.`;
634
- }
635
- const lines = [`[FLIGHT GREP] ${result.total} совпадений по запросу «${result.query}».`];
636
- for (const match of result.matches) {
637
- const flat = match.text.replace(/\s+/g, " ").trim();
638
- const short = flat.length > 120 ? `${flat.slice(0, 117)}...` : flat;
639
- lines.push(` ${match.id} #${match.seq} ${match.kind}: ${short}`);
640
- }
641
- if (result.total > result.matches.length) {
642
- lines.push(` показано ${result.matches.length}; увеличьте --limit, чтобы увидеть больше.`);
643
- }
644
- return lines.join("\n");
645
- }
646
- export function renderFlightStats(stats) {
647
- if (stats.total === 0)
648
- return "[FLIGHT STATS] полётов нет.";
649
- const lines = [
650
- `[FLIGHT STATS] всего ${stats.total}: завершено ${stats.ended}, активно ${stats.active}.`,
651
- `События: ${stats.events}, команды: ${stats.commands}, заметки: ${stats.notes}, чекпоинты: ${stats.checkpoints}, ошибки команд: ${stats.failedCommands}.`,
652
- `Длительность: ${stats.durationMs} мс, средняя: ${stats.averageDurationMs} мс.`,
653
- ];
654
- if (stats.last) {
655
- lines.push(`Последний: ${stats.last.id} (${stats.last.name})${stats.last.ended ? "" : ", активен"}.`);
656
- }
657
- if (stats.topCommands.length > 0) {
658
- lines.push("Частые команды:");
659
- for (const command of stats.topCommands) {
660
- lines.push(` ${command.command} — ${command.runs}, ошибок ${command.failures}`);
661
- }
662
- }
663
- return lines.join("\n");
664
- }
665
- export function renderFlightStatsHtml(stats) {
666
- const cards = [
667
- ["Flights", stats.total],
668
- ["Ended", stats.ended],
669
- ["Active", stats.active],
670
- ["Events", stats.events],
671
- ["Commands", stats.commands],
672
- ["Notes", stats.notes],
673
- ["Checkpoints", stats.checkpoints],
674
- ["Failed commands", stats.failedCommands],
675
- ["Duration", `${stats.durationMs} ms`],
676
- ["Average duration", `${stats.averageDurationMs} ms`],
677
- ]
678
- .map(([label, value]) => `<div><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong></div>`)
679
- .join("");
680
- const commands = stats.topCommands.length === 0
681
- ? `<p class="muted">No commands recorded yet.</p>`
682
- : `<table><thead><tr><th>Command</th><th>Runs</th><th>Failures</th></tr></thead><tbody>${stats.topCommands
683
- .map((command) => `<tr><td><code>${escapeHtml(command.command)}</code></td><td>${command.runs}</td><td>${command.failures}</td></tr>`)
684
- .join("")}</tbody></table>`;
685
- const lastFlight = stats.last
686
- ? `<p><code>${escapeHtml(stats.last.id)}</code> ${escapeHtml(stats.last.name)} — ${stats.last.ended ? "ended" : "active"}, started ${escapeHtml(stats.last.startedAt)}</p>`
687
- : `<p class="muted">No flights recorded yet.</p>`;
688
- return `<!doctype html>
689
- <html lang="en">
690
- <head>
691
- <meta charset="utf-8">
692
- <meta name="viewport" content="width=device-width, initial-scale=1">
693
- <title>oc-pilot flight stats</title>
694
- <style>
695
- :root { color-scheme: light dark; --bg:#f6f7f9; --card:#fff; --ink:#17191d; --muted:#68707d; --line:#d9dde4; --accent:#2457d6; }
696
- @media (prefers-color-scheme: dark) { :root { --bg:#111318; --card:#181b22; --ink:#e8ebf0; --muted:#9aa3b1; --line:#2b303a; --accent:#8ab4ff; } }
697
- * { box-sizing: border-box; }
698
- body { margin:0; background:var(--bg); color:var(--ink); font:15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
699
- main { max-width:1080px; margin:0 auto; padding:40px 20px 64px; }
700
- h1 { margin:0 0 20px; font-size:clamp(28px,5vw,44px); line-height:1.1; }
701
- .grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:12px; margin:20px 0; }
702
- .grid > div, section { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:16px; }
703
- .grid span { display:block; color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.06em; }
704
- .grid strong { display:block; margin-top:4px; font-size:20px; }
705
- section { margin:18px 0; }
706
- h2 { margin:0 0 12px; font-size:18px; }
707
- table { width:100%; border-collapse:collapse; }
708
- th, td { padding:8px; border-top:1px solid var(--line); text-align:left; }
709
- th { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.06em; }
710
- code { font-family:ui-monospace, SFMono-Regular, Consolas, monospace; }
711
- .muted { color:var(--muted); }
712
- </style>
713
- </head>
714
- <body>
715
- <main>
716
- <h1>oc-pilot flight stats</h1>
717
- <div class="grid">${cards}</div>
718
- <section><h2>Last flight</h2>${lastFlight}</section>
719
- <section><h2>Top commands</h2>${commands}</section>
720
- </main>
721
- </body>
722
- </html>`;
723
- }
724
- export function renderFlightPrune(result) {
725
- const shown = result.removed.slice(0, 5).join(", ");
726
- const suffix = result.removed.length > 5 ? ` и ещё ${result.removed.length - 5}` : "";
727
- const list = result.removed.length > 0 ? `: ${shown}${suffix}` : "";
728
- return `[FLIGHT PRUNE] ${result.dryRun ? "будет удалено" : "удалено"} ${result.removed.length}${list}; осталось ${result.kept}${result.active ? `, активный ${result.active}` : ""}.`;
729
- }
730
- export function renderFlightDelete(result) {
731
- const verb = result.dryRun ? "будет удалён" : "удалён";
732
- return `[FLIGHT DELETE] ${verb} ${result.id} (${result.name}): событий ${result.events}, чекпоинтов ${result.checkpoints}.`;
733
- }
734
- export const FLIGHT_EVENT_KINDS = [
735
- "session.start",
736
- "command.start",
737
- "command.end",
738
- "file.checkpoint",
739
- "gate.result",
740
- "approval",
741
- "note",
742
- "session.end",
743
- ];
744
- export function filterFlightEvents(events, kind, last) {
745
- let filtered = events;
746
- if (kind !== undefined) {
747
- const trimmed = kind.trim();
748
- if (!FLIGHT_EVENT_KINDS.includes(trimmed)) {
749
- throw new PilotError(`Неизвестный тип события: ${trimmed}`, {
750
- hint: `Доступно: ${FLIGHT_EVENT_KINDS.join(", ")}.`,
751
- exitCode: 2,
752
- });
753
- }
754
- filtered = filtered.filter((event) => event.kind === trimmed);
755
- }
756
- if (last !== undefined) {
757
- if (!Number.isInteger(last) || last < 1) {
758
- throw new PilotError(`Некорректный --last: ${String(last)}`, {
759
- hint: "Укажите положительное целое число.",
760
- exitCode: 2,
761
- });
762
- }
763
- filtered = filtered.slice(-last);
764
- }
765
- return filtered;
766
- }
767
- function eventSummary(event) {
768
- if (event.kind === "file.checkpoint") {
769
- return `чекпоинт ${String(event.payload.label ?? "")} (${String(event.payload.commit ?? "").slice(0, 8)})`;
770
- }
771
- if (event.kind === "note") {
772
- return `Заметка: ${String(event.payload.text ?? "")}`;
773
- }
774
- if (event.kind === "command.start" || event.kind === "command.end") {
775
- const command = Array.isArray(event.payload.command) ? event.payload.command.join(" ") : "";
776
- return `${command}${event.kind === "command.end" ? ` → ${String(event.payload.exitCode ?? "?")}` : ""}`;
777
- }
778
- return String(event.payload.name ?? event.kind);
779
- }
780
- export function renderFlightSummary(show) {
781
- const checkpoints = flightCheckpoints(show);
782
- const commands = [];
783
- for (const event of show.events) {
784
- if (event.kind !== "command.end")
785
- continue;
786
- const payload = event.payload;
787
- const parts = Array.isArray(payload.command)
788
- ? payload.command.filter((part) => typeof part === "string")
789
- : [];
790
- if (parts.length === 0)
791
- continue;
792
- commands.push({
793
- command: parts.join(" "),
794
- exitCode: typeof payload.exitCode === "number" ? payload.exitCode : undefined,
795
- durationMs: typeof payload.durationMs === "number" ? payload.durationMs : undefined,
796
- });
797
- }
798
- const startedAt = Date.parse(show.meta.startedAt);
799
- const lastTs = show.events.at(-1)?.ts;
800
- const durationMs = lastTs ? Math.max(0, Date.parse(lastTs) - startedAt) : 0;
801
- const failed = commands.filter((command) => command.exitCode !== undefined && command.exitCode !== 0);
802
- const lines = [
803
- `# Полёт: ${show.meta.name}`,
804
- "",
805
- `- ID: \`${show.meta.id}\``,
806
- `- Начат: ${show.meta.startedAt}`,
807
- `- База: \`${show.meta.baseCommit ?? "HEAD"}\``,
808
- `- Длительность: ${durationMs} мс`,
809
- `- События: ${show.events.length}`,
810
- `- Чекпоинты: ${checkpoints.length}`,
811
- `- Команды: ${commands.length} (ошибок: ${failed.length})`,
812
- `- Цепочка: ${show.verification.valid ? "целая" : "повреждена"}`,
813
- "",
814
- "## Чекпоинты",
815
- "",
816
- ];
817
- if (checkpoints.length === 0) {
818
- lines.push("_нет_");
819
- }
820
- else {
821
- lines.push("| Метка | Коммит |", "| --- | --- |");
822
- for (const checkpoint of checkpoints) {
823
- lines.push(`| ${checkpoint.label} | \`${checkpoint.commit.slice(0, 12)}\` |`);
824
- }
825
- }
826
- lines.push("", "## Команды", "");
827
- if (commands.length === 0) {
828
- lines.push("_нет_");
829
- }
830
- else {
831
- lines.push("| Команда | Код | Длительность |", "| --- | --- | --- |");
832
- for (const command of commands) {
833
- const code = command.exitCode === undefined ? "?" : String(command.exitCode);
834
- lines.push(`| \`${command.command.replaceAll("|", "\\|")}\` | ${code} | ${command.durationMs ?? 0} мс |`);
835
- }
836
- }
837
- const notes = show.events
838
- .filter((event) => event.kind === "note")
839
- .map((event) => String(event.payload.text ?? ""))
840
- .filter((note) => note.length > 0);
841
- if (notes.length > 0) {
842
- lines.push("", "## Заметки", "", ...notes.map((note) => `- ${note}`));
843
- }
844
- if (!show.verification.valid) {
845
- lines.push("", "## Повреждения", "", ...show.verification.errors.map((error) => `- ${error}`));
846
- }
847
- return lines.join("\n");
848
- }
849
- export function renderFlightShow(show) {
850
- const lines = [
851
- `Полёт ${show.meta.id} (${show.meta.name})`,
852
- `Начат: ${show.meta.startedAt}`,
853
- `Коммит: ${show.meta.baseCommit ?? "нет HEAD"}`,
854
- `Проверка: ${show.verification.valid ? "цепочка цела" : "цепочка повреждена"}`,
855
- `Событий: ${show.events.length}`,
856
- "",
857
- ...show.events.map((event) => `${String(event.seq).padStart(3, " ")} ${event.kind} ${eventSummary(event)}`),
858
- ];
859
- if (!show.verification.valid)
860
- lines.push("", ...show.verification.errors.map((error) => `! ${error}`));
861
- return lines.join("\n");
862
- }
863
- export function auditFlights(cwd) {
864
- const flights = [];
865
- for (const entry of listFlights(cwd)) {
866
- const show = showFlight(cwd, entry.id);
867
- flights.push({
868
- id: show.meta.id,
869
- name: show.meta.name,
870
- valid: show.verification.valid,
871
- events: show.verification.events,
872
- errors: show.verification.errors,
873
- });
874
- }
875
- const tampered = flights.filter((flight) => !flight.valid).length;
876
- return {
877
- total: flights.length,
878
- valid: flights.length - tampered,
879
- tampered,
880
- flights,
881
- };
882
- }
883
- export function renderFlightAudit(result) {
884
- if (result.total === 0)
885
- return "[FLIGHT AUDIT] полётов нет.";
886
- const lines = [
887
- `[FLIGHT AUDIT] всего ${result.total}: целых ${result.valid}, повреждённых ${result.tampered}.`,
888
- ];
889
- for (const flight of result.flights) {
890
- const status = flight.valid ? "ok" : "TAMPERED";
891
- lines.push(` ${status} ${flight.id} ${flight.name} (${flight.events} событий)`);
892
- for (const error of flight.errors)
893
- lines.push(` ${error}`);
894
- }
895
- return lines.join("\n");
896
- }
897
- export function renderFlightVerify(result) {
898
- if (result.valid)
899
- return `[FLIGHT VALID] ${result.events} событий, цепочка цела.`;
900
- return [`[FLIGHT TAMPERED] ${result.errors.length} ошибок.`, ...result.errors.map((error) => ` ${error}`)].join("\n");
901
- }
902
- export function renderFlightStart(session) {
903
- return `Полёт ${session.meta.id} начат (${session.meta.name}).`;
904
- }
905
- export function renderFlightCheckpoint(checkpoint) {
906
- return `Чекпоинт ${checkpoint.label}: ${checkpoint.commit.slice(0, 12)} (tree ${checkpoint.tree.slice(0, 12)}).`;
907
- }
908
- export function renderFlightExec(result) {
909
- const status = result.timedOut ? "таймаут" : `код ${result.exitCode ?? "?"}`;
910
- return `Команда ${result.command.join(" ")}: ${status}, ${result.durationMs} мс.`;
911
- }
912
- export function renderFlightEnd(summary) {
913
- return `Полёт завершён: чекпоинтов ${String(summary.checkpoints ?? 0)}, команд ${String(summary.commands ?? 0)}, ${String(summary.durationMs ?? 0)} мс.`;
914
- }
915
- function resolveFlightId(cwd, id) {
916
- if (id && id.trim().length > 0)
917
- return id.trim();
918
- const active = activeFlight(cwd);
919
- if (active)
920
- return active.meta.id;
921
- const latest = listFlights(cwd)[0];
922
- if (latest)
923
- return latest.id;
924
- throw new PilotError("Полёт не запущен.", {
925
- hint: "Запустите oc-pilot flight start или укажите --id.",
926
- exitCode: 2,
927
- });
928
- }
929
- function flightCheckpoints(show) {
930
- return show.events
931
- .filter((event) => event.kind === "file.checkpoint")
932
- .map((event) => event.payload);
933
- }
934
- function resolveCheckpoint(checkpoints, ref) {
935
- if (checkpoints.length === 0) {
936
- throw new PilotError("В полёте нет чекпоинтов.", {
937
- hint: "Создайте чекпоинт: oc-pilot flight checkpoint --label <метка>.",
938
- exitCode: 2,
939
- });
940
- }
941
- if (!ref)
942
- return checkpoints[checkpoints.length - 1];
943
- const exact = [...checkpoints].reverse().find((checkpoint) => checkpoint.label === ref);
944
- if (exact)
945
- return exact;
946
- const byCommit = [...checkpoints].reverse().find((checkpoint) => checkpoint.commit.startsWith(ref));
947
- if (byCommit)
948
- return byCommit;
949
- throw new PilotError(`Чекпоинт не найден: ${ref}.`, {
950
- hint: "Посмотрите oc-pilot flight show <id>.",
951
- exitCode: 2,
952
- });
953
- }
954
- function sanitizeLabel(label) {
955
- return label.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 40) || "checkpoint";
956
- }
957
- function removeWorktree(cwd, path) {
958
- const result = runGit(["worktree", "remove", "--force", path], cwd);
959
- if (result.status !== 0)
960
- rmSync(path, { recursive: true, force: true });
961
- }
962
- export function replayFlight(cwd, id, to, path) {
963
- const show = showFlight(cwd, resolveFlightId(cwd, id));
964
- const checkpoint = resolveCheckpoint(flightCheckpoints(show), to);
965
- const target = path
966
- ? resolve(cwd, path)
967
- : join(tmpdir(), `oc-pilot-flight-${show.meta.id}-${sanitizeLabel(checkpoint.label)}-${randomBytes(3).toString("hex")}`);
968
- if (existsSync(target)) {
969
- throw new PilotError(`Путь уже существует: ${target}.`, {
970
- hint: "Укажите другой --path или удалите старый worktree.",
971
- });
972
- }
973
- const result = runGit(["worktree", "add", "--detach", target, checkpoint.commit], cwd);
974
- if (result.status !== 0) {
975
- throw new PilotError(`Не удалось создать worktree: ${result.stderr.trim() || "git worktree failed"}.`);
976
- }
977
- return { id: show.meta.id, label: checkpoint.label, commit: checkpoint.commit, path: target };
978
- }
979
- export function restoreFlight(cwd, ref, id, force = false, dryRun = false) {
980
- const show = showFlight(cwd, resolveFlightId(cwd, id));
981
- const checkpoint = resolveCheckpoint(flightCheckpoints(show), ref);
982
- const diff = runGit(["diff", "--name-only", checkpoint.commit, "--", "."], cwd);
983
- if (diff.status !== 0) {
984
- throw new PilotError(`Не удалось сравнить чекпоинт: ${diff.stderr.trim() || "git diff failed"}.`);
985
- }
986
- const files = diff.stdout
987
- .split("\n")
988
- .map((file) => file.trim())
989
- .filter((file) => file.length > 0);
990
- if (dryRun) {
991
- return {
992
- id: show.meta.id,
993
- label: checkpoint.label,
994
- commit: checkpoint.commit,
995
- mode: "restore",
996
- dryRun: true,
997
- files,
998
- };
999
- }
1000
- const status = runGit(["status", "--porcelain"], cwd);
1001
- if (status.status !== 0) {
1002
- throw new PilotError(`Не удалось проверить рабочее дерево: ${status.stderr.trim() || "git status failed"}.`);
1003
- }
1004
- if (!force && status.stdout.trim().length > 0) {
1005
- throw new PilotError("Рабочее дерево содержит изменения.", {
1006
- hint: "Сделайте коммит, stash или используйте --force.",
1007
- });
1008
- }
1009
- const restore = runGit(["restore", "--source", checkpoint.commit, "--worktree", "--", "."], cwd);
1010
- if (restore.status !== 0) {
1011
- throw new PilotError(`Не удалось восстановить чекпоинт: ${restore.stderr.trim() || "git restore failed"}.`);
1012
- }
1013
- return {
1014
- id: show.meta.id,
1015
- label: checkpoint.label,
1016
- commit: checkpoint.commit,
1017
- mode: "restore",
1018
- dryRun: false,
1019
- files,
1020
- };
1021
- }
1022
- function runProofCommand(dir, command, timeoutMs) {
1023
- const result = spawnSync(command[0], command.slice(1), {
1024
- cwd: dir,
1025
- encoding: "utf8",
1026
- timeout: timeoutMs,
1027
- maxBuffer: 32 * 1024 * 1024,
1028
- windowsHide: true,
1029
- });
1030
- const timedOut = result.signal === "SIGTERM" ||
1031
- result.error?.code === "ETIMEDOUT";
1032
- return { ok: !timedOut && result.status === 0, exitCode: result.status, timedOut };
1033
- }
1034
- function withProofWorktree(cwd, commit, run) {
1035
- const target = join(tmpdir(), `oc-pilot-proof-${randomBytes(4).toString("hex")}`);
1036
- const added = runGit(["worktree", "add", "--detach", target, commit], cwd);
1037
- if (added.status !== 0) {
1038
- throw new PilotError(`Не удалось подготовить worktree для ${commit.slice(0, 12)}: ${added.stderr.trim() || "git worktree add failed"}.`, { exitCode: 2 });
1039
- }
1040
- try {
1041
- return run(target);
1042
- }
1043
- finally {
1044
- runGit(["worktree", "remove", "--force", target], cwd);
1045
- rmSync(target, { recursive: true, force: true });
1046
- }
1047
- }
1048
- export function proveClaim(cwd, claim, command, id, timeoutMs = 600_000) {
1049
- const text = claim.trim();
1050
- if (text.length === 0) {
1051
- throw new PilotError("Пустое утверждение для prove.", {
1052
- hint: "Передайте --claim \"что должно быть верно\".",
1053
- exitCode: 2,
1054
- });
1055
- }
1056
- if (command.length === 0) {
1057
- throw new PilotError("Не указана проверка для prove.", {
1058
- hint: "Передайте команду после --: oc-pilot prove --claim \"...\" -- npm test.",
1059
- exitCode: 2,
1060
- });
1061
- }
1062
- const show = showFlight(cwd, resolveFlightId(cwd, id));
1063
- const base = show.meta.baseCommit ?? "HEAD";
1064
- const steps = [];
1065
- const errors = [];
1066
- const baseRun = withProofWorktree(cwd, base, (dir) => runProofCommand(dir, command, timeoutMs));
1067
- steps.push({ ref: "base", commit: base, ...baseRun });
1068
- for (const checkpoint of flightCheckpoints(show)) {
1069
- const label = checkpoint.label ?? checkpoint.commit.slice(0, 12);
1070
- const run = withProofWorktree(cwd, checkpoint.commit, (dir) => runProofCommand(dir, command, timeoutMs));
1071
- steps.push({ ref: label, commit: checkpoint.commit, ...run });
1072
- }
1073
- const headRun = runProofCommand(cwd, command, timeoutMs);
1074
- steps.push({ ref: "head", commit: "HEAD", ...headRun });
1075
- const firstOk = steps.findIndex((step) => step.ok);
1076
- const transition = firstOk > 0 ? { from: steps[firstOk - 1]?.ref ?? "base", to: steps[firstOk]?.ref ?? "head" } : undefined;
1077
- let verdict;
1078
- if (steps[0]?.ok) {
1079
- verdict = "rejected";
1080
- errors.push("Проверка проходит уже на базовом коммите: она не воспроизводит проблему.");
1081
- }
1082
- else if (!steps.at(-1)?.ok) {
1083
- const wasGreen = steps.some((step) => step.ok);
1084
- verdict = wasGreen ? "regressed" : "unproven";
1085
- errors.push(wasGreen
1086
- ? "Проверка была зелёной, но на итоговом дереве снова красная."
1087
- : "Проверка ни разу не стала зелёной.");
1088
- }
1089
- else {
1090
- verdict = "proven";
1091
- }
1092
- return { id: show.meta.id, claim: text, command, verdict, steps, transition, errors };
1093
- }
1094
- export function renderFlightProof(result) {
1095
- const lines = [
1096
- `[FLIGHT PROVE] ${result.verdict.toUpperCase()}: ${result.claim}`,
1097
- `Проверка: ${result.command.join(" ")}`,
1098
- ];
1099
- if (result.transition) {
1100
- lines.push(`Переход: ${result.transition.from} → ${result.transition.to}`);
1101
- }
1102
- lines.push("Шаги:");
1103
- for (const step of result.steps) {
1104
- lines.push(` ${step.ok ? "ok" : "fail"} ${step.ref} (${step.commit.slice(0, 12)}) код ${step.exitCode ?? "?"}`);
1105
- }
1106
- if (result.errors.length > 0) {
1107
- lines.push("", ...result.errors.map((error) => `! ${error}`));
1108
- }
1109
- return lines.join("\n");
1110
- }
1111
- export function bisectFlight(cwd, id, command, timeoutMs = 600_000) {
1112
- if (command.length === 0) {
1113
- throw new PilotError("Не указана команда для bisect.", {
1114
- hint: "Передайте команду после --: oc-pilot flight bisect -- <команда>.",
1115
- });
1116
- }
1117
- const show = showFlight(cwd, resolveFlightId(cwd, id));
1118
- const checkpoints = flightCheckpoints(show);
1119
- if (checkpoints.length === 0) {
1120
- throw new PilotError("В полёте нет чекпоинтов для bisect.", {
1121
- hint: "Создайте чекпоинты: oc-pilot flight checkpoint --label <метка>.",
1122
- exitCode: 2,
1123
- });
1124
- }
1125
- const steps = [];
1126
- let firstBad;
1127
- for (const checkpoint of checkpoints) {
1128
- const replay = replayFlight(cwd, show.meta.id, checkpoint.commit);
1129
- const startedAt = Date.now();
1130
- const result = spawnSync(command[0], command.slice(1), {
1131
- cwd: replay.path,
1132
- encoding: "utf8",
1133
- timeout: timeoutMs,
1134
- maxBuffer: 16 * 1024 * 1024,
1135
- windowsHide: true,
1136
- });
1137
- const errorCode = result.error?.code;
1138
- const timedOut = errorCode === "ETIMEDOUT" || result.signal === "SIGTERM";
1139
- const exitCode = typeof result.status === "number" ? result.status : null;
1140
- const step = {
1141
- label: checkpoint.label,
1142
- commit: checkpoint.commit,
1143
- exitCode,
1144
- timedOut,
1145
- durationMs: Date.now() - startedAt,
1146
- stdoutTail: tail(result.stdout ?? ""),
1147
- stderrTail: tail(result.stderr ?? ""),
1148
- };
1149
- steps.push(step);
1150
- removeWorktree(cwd, replay.path);
1151
- if (timedOut || exitCode !== 0) {
1152
- firstBad = step;
1153
- break;
1154
- }
1155
- }
1156
- return firstBad ? { id: show.meta.id, command, steps, firstBad } : { id: show.meta.id, command, steps };
1157
- }
1158
- export function diffFlight(cwd, id, fromRef, toRef) {
1159
- const show = showFlight(cwd, resolveFlightId(cwd, id));
1160
- const checkpoints = flightCheckpoints(show);
1161
- const base = show.meta.baseCommit ?? "HEAD";
1162
- const from = fromRef
1163
- ? { label: fromRef, commit: resolveCheckpoint(checkpoints, fromRef).commit }
1164
- : { label: "base", commit: base };
1165
- const to = toRef
1166
- ? { label: toRef, commit: resolveCheckpoint(checkpoints, toRef).commit }
1167
- : { label: checkpoints[checkpoints.length - 1]?.label ?? "head", commit: checkpoints[checkpoints.length - 1]?.commit ?? "HEAD" };
1168
- const stat = runGit(["diff", "--no-color", "--stat", from.commit, to.commit], cwd);
1169
- const patch = runGit(["diff", "--no-color", from.commit, to.commit], cwd);
1170
- if (stat.status !== 0 || patch.status !== 0) {
1171
- throw new PilotError(`Не удалось получить diff: ${(stat.stderr || patch.stderr).trim() || "git diff failed"}.`);
1172
- }
1173
- const limit = 200_000;
1174
- return {
1175
- id: show.meta.id,
1176
- from,
1177
- to,
1178
- stat: stat.stdout.trimEnd(),
1179
- patch: patch.stdout.length > limit ? `${patch.stdout.slice(0, limit)}\n... (обрезано)` : patch.stdout,
1180
- };
1181
- }
1182
- function commandKey(command) {
1183
- return JSON.stringify(command);
1184
- }
1185
- function commandLabel(command) {
1186
- const text = command.join(" ");
1187
- return text.length > 160 ? `${text.slice(0, 157)}...` : text;
1188
- }
1189
- function compareSide(show) {
1190
- const events = show.events;
1191
- const startedAt = show.meta.startedAt;
1192
- const endedAt = events.at(-1)?.ts ?? startedAt;
1193
- const durationMs = Math.max(0, Date.parse(endedAt) - Date.parse(startedAt));
1194
- const checkpoints = flightCheckpoints(show);
1195
- const last = checkpoints.at(-1);
1196
- const runs = new Map();
1197
- for (const event of events) {
1198
- if (event.kind !== "command.end")
1199
- continue;
1200
- const payload = event.payload;
1201
- const command = Array.isArray(payload.command)
1202
- ? payload.command.filter((part) => typeof part === "string")
1203
- : [];
1204
- if (command.length === 0)
1205
- continue;
1206
- const run = {
1207
- command,
1208
- exitCode: typeof payload.exitCode === "number" ? payload.exitCode : null,
1209
- timedOut: payload.timedOut === true,
1210
- durationMs: typeof payload.durationMs === "number" ? payload.durationMs : 0,
1211
- };
1212
- runs.set(commandKey(command), run);
1213
- }
1214
- const failedCommands = [...runs.values()].filter((run) => run.timedOut || (run.exitCode !== null && run.exitCode !== 0)).length;
1215
- const side = {
1216
- id: show.meta.id,
1217
- name: show.meta.name,
1218
- startedAt,
1219
- endedAt,
1220
- durationMs,
1221
- events: events.length,
1222
- notes: events.filter((event) => event.kind === "note").length,
1223
- commands: events.filter((event) => event.kind === "command.start").length,
1224
- checkpoints: checkpoints.length,
1225
- failedCommands,
1226
- valid: show.verification.valid,
1227
- baseCommit: show.meta.baseCommit,
1228
- finalCheckpoint: last ? { label: last.label, commit: last.commit, tree: last.tree } : undefined,
1229
- };
1230
- return { side, runs };
1231
- }
1232
- export function compareFlights(cwd, idA, idB) {
1233
- return compareFlightShows(showFlight(cwd, idA), showFlight(cwd, idB));
1234
- }
1235
- export function compareFlightShows(showA, showB) {
1236
- const left = compareSide(showA);
1237
- const right = compareSide(showB);
1238
- const common = [];
1239
- const onlyA = [];
1240
- const onlyB = [];
1241
- for (const [key, run] of left.runs) {
1242
- if (right.runs.has(key))
1243
- common.push(run.command);
1244
- else
1245
- onlyA.push(run.command);
1246
- }
1247
- for (const [key, run] of right.runs) {
1248
- if (!left.runs.has(key))
1249
- onlyB.push(run.command);
1250
- }
1251
- const exitCodeDifferences = [];
1252
- for (const [key, leftRun] of left.runs) {
1253
- const rightRun = right.runs.get(key);
1254
- if (!rightRun)
1255
- continue;
1256
- if (leftRun.exitCode !== rightRun.exitCode || leftRun.timedOut !== rightRun.timedOut) {
1257
- exitCodeDifferences.push({
1258
- command: leftRun.command,
1259
- a: leftRun.timedOut ? null : leftRun.exitCode,
1260
- b: rightRun.timedOut ? null : rightRun.exitCode,
1261
- });
1262
- }
1263
- }
1264
- const sameFinalTree = left.side.finalCheckpoint && right.side.finalCheckpoint
1265
- ? left.side.finalCheckpoint.tree === right.side.finalCheckpoint.tree
1266
- : null;
1267
- return {
1268
- a: left.side,
1269
- b: right.side,
1270
- common,
1271
- onlyA,
1272
- onlyB,
1273
- exitCodeDifferences,
1274
- sameFinalTree,
1275
- };
1276
- }
1277
- const SECRET_PATTERNS = [
1278
- /sk-[A-Za-z0-9]{20,}/g,
1279
- /gh[pousr]_[A-Za-z0-9]{20,}/g,
1280
- /xox[baprs]-[A-Za-z0-9-]{10,}/g,
1281
- /AKIA[0-9A-Z]{16}/g,
1282
- /((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^"'\s]{8,}/gi,
1283
- ];
1284
- function redactText(text) {
1285
- let output = text;
1286
- for (const pattern of SECRET_PATTERNS) {
1287
- output = output.replace(pattern, (_match, prefix) => typeof prefix === "string" && prefix.length > 0 ? `${prefix}[REDACTED]` : "[REDACTED]");
1288
- }
1289
- return output;
1290
- }
1291
- function redactValue(value) {
1292
- if (typeof value === "string")
1293
- return redactText(value);
1294
- if (Array.isArray(value))
1295
- return value.map(redactValue);
1296
- if (value !== null && typeof value === "object") {
1297
- return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactValue(entry)]));
1298
- }
1299
- return value;
1300
- }
1301
- function flightBundleDigest(manifest) {
1302
- return `sha256:${createHash("sha256").update(JSON.stringify(manifest)).digest("hex")}`;
1303
- }
1304
- function hmacFlightDigest(key, digest) {
1305
- return createHmac("sha256", key).update(digest).digest("hex");
1306
- }
1307
- export function generateFlightKey() {
1308
- return randomBytes(32).toString("hex");
1309
- }
1310
- export function exportFlight(cwd, id, keyPath) {
1311
- const show = showFlight(cwd, resolveFlightId(cwd, id));
1312
- const base = show.meta.baseCommit ?? "HEAD";
1313
- const checkpoints = flightCheckpoints(show).map((checkpoint) => {
1314
- const patch = runGit(["diff", "--no-color", base, checkpoint.commit], cwd);
1315
- return {
1316
- ...checkpoint,
1317
- patch: patch.status === 0 ? redactText(patch.stdout) : "",
1318
- };
1319
- });
1320
- const manifest = {
1321
- format: "oc-pilot-flight-export/v1",
1322
- exportedAt: new Date().toISOString(),
1323
- meta: { ...show.meta, cwd: "." },
1324
- verification: show.verification,
1325
- events: show.events.map((event) => redactValue(event)),
1326
- checkpoints,
1327
- };
1328
- const digest = flightBundleDigest(manifest);
1329
- const result = { ...manifest, digest };
1330
- if (keyPath) {
1331
- result.signature = {
1332
- type: "hmac-sha256",
1333
- value: hmacFlightDigest(readFileSync(keyPath), digest),
1334
- };
1335
- }
1336
- return result;
1337
- }
1338
- export function loadFlightBundle(file) {
1339
- let parsed;
1340
- try {
1341
- parsed = JSON.parse(readFileSync(file, "utf8"));
1342
- }
1343
- catch (error) {
1344
- throw new PilotError(`Не удалось прочитать flight bundle: ${error instanceof Error ? error.message : String(error)}`, {
1345
- hint: "Передайте JSON-файл, созданный oc-pilot flight export.",
1346
- exitCode: 2,
1347
- });
1348
- }
1349
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1350
- throw new PilotError("Flight bundle должен быть JSON-объектом.", {
1351
- hint: "Передайте файл, созданный oc-pilot flight export.",
1352
- exitCode: 2,
1353
- });
1354
- }
1355
- const bundle = parsed;
1356
- if (typeof bundle.format !== "string" ||
1357
- typeof bundle.digest !== "string" ||
1358
- !bundle.meta ||
1359
- typeof bundle.meta !== "object" ||
1360
- !Array.isArray(bundle.events)) {
1361
- throw new PilotError("Flight bundle повреждён: нет обязательных полей.", {
1362
- hint: "Передайте файл, созданный oc-pilot flight export.",
1363
- exitCode: 2,
1364
- });
1365
- }
1366
- return bundle;
1367
- }
1368
- export function signFlightBundle(bundle, keyPath) {
1369
- const { digest, signature: _signature, ...base } = bundle;
1370
- if (flightBundleDigest(base) !== digest) {
1371
- throw new PilotError("Flight bundle повреждён: digest не совпадает.", {
1372
- hint: "Не подписывайте изменённый bundle; сначала проверьте его через flight verify-bundle.",
1373
- exitCode: 2,
1374
- });
1375
- }
1376
- return {
1377
- ...base,
1378
- digest,
1379
- signature: { type: "hmac-sha256", value: hmacFlightDigest(readFileSync(keyPath), digest) },
1380
- };
1381
- }
1382
- export function flightShowFromBundle(bundle) {
1383
- return {
1384
- meta: bundle.meta,
1385
- events: bundle.events,
1386
- verification: verifyFlightEvents(bundle.events),
1387
- };
1388
- }
1389
- export function verifyFlightBundle(file, keyPath) {
1390
- const bundle = loadFlightBundle(file);
1391
- const { digest, signature, ...base } = bundle;
1392
- const digestOk = flightBundleDigest(base) === digest;
1393
- const chain = verifyFlightEvents(bundle.events);
1394
- const errors = [];
1395
- if (!digestOk)
1396
- errors.push("digest не совпадает");
1397
- if (!chain.valid)
1398
- errors.push(...chain.errors);
1399
- let signatureStatus = "missing";
1400
- if (signature !== undefined) {
1401
- if (typeof signature !== "object" ||
1402
- signature === null ||
1403
- signature.type !== "hmac-sha256" ||
1404
- typeof signature.value !== "string") {
1405
- signatureStatus = "invalid";
1406
- errors.push("неизвестный формат подписи");
1407
- }
1408
- else if (!keyPath) {
1409
- signatureStatus = "unchecked";
1410
- errors.push("подпись есть, но ключ не указан");
1411
- }
1412
- else {
1413
- const expected = Buffer.from(hmacFlightDigest(readFileSync(keyPath), digest), "hex");
1414
- const actual = Buffer.from(signature.value, "hex");
1415
- signatureStatus =
1416
- expected.length === actual.length && timingSafeEqual(expected, actual) ? "valid" : "invalid";
1417
- if (signatureStatus === "invalid")
1418
- errors.push("подпись не совпадает");
1419
- }
1420
- }
1421
- return {
1422
- format: bundle.format,
1423
- id: typeof bundle.meta.id === "string" ? bundle.meta.id : undefined,
1424
- digestOk,
1425
- chainOk: chain.valid,
1426
- signature: signatureStatus,
1427
- valid: digestOk && chain.valid && signatureStatus !== "invalid" && signatureStatus !== "unchecked",
1428
- errors,
1429
- };
1430
- }
1431
- export function renderFlightReplay(result) {
1432
- return `[FLIGHT REPLAY] ${result.label} (${result.commit.slice(0, 12)}) → ${result.path}`;
1433
- }
1434
- export function renderFlightRestore(result) {
1435
- const files = result.files.length > 0 ? `: ${result.files.join(", ")}` : "";
1436
- return `[FLIGHT RESTORE] ${result.dryRun ? "будет восстановлено" : "восстановлено"} ${result.label} (${result.commit.slice(0, 12)})${files}`;
1437
- }
1438
- export function renderFlightBisect(result) {
1439
- const lines = [`[FLIGHT BISECT] ${result.id}: ${result.steps.length} чекпоинтов.`];
1440
- for (const step of result.steps) {
1441
- const marker = step === result.firstBad ? "FAIL" : "ok";
1442
- lines.push(` ${marker} ${step.label} ${step.commit.slice(0, 12)} exit ${step.exitCode ?? "?"}${step.timedOut ? " timeout" : ""}`);
1443
- }
1444
- if (result.firstBad) {
1445
- lines.push(`[FIRST BAD STEP] ${result.firstBad.label} (${result.firstBad.commit.slice(0, 12)}).`);
1446
- }
1447
- else {
1448
- lines.push("[FLIGHT BISECT] все чекпоинты прошли.");
1449
- }
1450
- return lines.join("\n");
1451
- }
1452
- export function diffFlightBundle(file, ref) {
1453
- const bundle = loadFlightBundle(file);
1454
- if (bundle.checkpoints.length === 0) {
1455
- throw new PilotError("В bundle нет чекпоинтов.", {
1456
- hint: "Сделайте чекпоинт в полёте и экспортируйте его заново.",
1457
- exitCode: 2,
1458
- });
1459
- }
1460
- const wanted = ref?.trim();
1461
- const checkpoint = wanted
1462
- ? bundle.checkpoints.find((item) => item.label === wanted || item.commit.startsWith(wanted))
1463
- : bundle.checkpoints.at(-1);
1464
- if (!checkpoint) {
1465
- const labels = bundle.checkpoints.map((item) => item.label ?? item.commit.slice(0, 12));
1466
- throw new PilotError(`Чекпоинт не найден: ${wanted}.`, {
1467
- hint: `Доступно: ${labels.join(", ")}.`,
1468
- exitCode: 2,
1469
- });
1470
- }
1471
- return {
1472
- id: bundle.meta.id,
1473
- base: bundle.meta.baseCommit ?? "HEAD",
1474
- label: checkpoint.label ?? checkpoint.commit.slice(0, 12),
1475
- commit: checkpoint.commit,
1476
- patch: checkpoint.patch,
1477
- };
1478
- }
1479
- export function renderFlightBundleDiff(result) {
1480
- return [`[FLIGHT BUNDLE DIFF] ${result.base}..${result.label}`, result.patch]
1481
- .filter((line) => line.length > 0)
1482
- .join("\n");
1483
- }
1484
- export function renderFlightDiff(result) {
1485
- return [`[FLIGHT DIFF] ${result.from.label}..${result.to.label}`, result.stat, result.patch]
1486
- .filter((part) => part.length > 0)
1487
- .join("\n");
1488
- }
1489
- export function renderFlightCompareHtml(result) {
1490
- const side = (label, value) => `<section class="card">
1491
- <h2>${label}: ${escapeHtml(value.name)}</h2>
1492
- <p class="id">${escapeHtml(value.id)}</p>
1493
- <span class="badge ${value.valid ? "ok" : "bad"}">${value.valid ? "chain valid" : "chain tampered"}</span>
1494
- <dl>
1495
- <div><dt>Events</dt><dd>${value.events}</dd></div>
1496
- <div><dt>Notes</dt><dd>${value.notes}</dd></div>
1497
- <div><dt>Commands</dt><dd>${value.commands}</dd></div>
1498
- <div><dt>Checkpoints</dt><dd>${value.checkpoints}</dd></div>
1499
- <div><dt>Failed commands</dt><dd>${value.failedCommands}</dd></div>
1500
- <div><dt>Duration</dt><dd>${value.durationMs} ms</dd></div>
1501
- </dl>
1502
- </section>`;
1503
- const commandList = (commands) => commands.length === 0
1504
- ? `<p class="muted">none</p>`
1505
- : `<ul>${commands.map((command) => `<li><code>${escapeHtml(commandLabel(command))}</code></li>`).join("")}</ul>`;
1506
- const differences = result.exitCodeDifferences.length === 0
1507
- ? `<p class="muted">none</p>`
1508
- : `<table><thead><tr><th>Command</th><th>A</th><th>B</th></tr></thead><tbody>${result.exitCodeDifferences
1509
- .map((difference) => `<tr><td><code>${escapeHtml(commandLabel(difference.command))}</code></td><td>${difference.a ?? "?"}</td><td>${difference.b ?? "?"}</td></tr>`)
1510
- .join("")}</tbody></table>`;
1511
- const tree = result.sameFinalTree === null
1512
- ? "no checkpoint on one side"
1513
- : result.sameFinalTree
1514
- ? "same tree"
1515
- : "different tree";
1516
- return `<!doctype html>
1517
- <html lang="en">
1518
- <head>
1519
- <meta charset="utf-8">
1520
- <meta name="viewport" content="width=device-width, initial-scale=1">
1521
- <title>oc-pilot flight compare</title>
1522
- <style>
1523
- :root { color-scheme: light dark; --bg:#f6f7f9; --card:#fff; --ink:#17191d; --muted:#68707d; --line:#d9dde4; --accent:#2457d6; --ok:#177245; --bad:#b42318; }
1524
- @media (prefers-color-scheme: dark) { :root { --bg:#111318; --card:#181b22; --ink:#e8ebf0; --muted:#9aa3b1; --line:#2b303a; --accent:#8ab4ff; --ok:#63d391; --bad:#ff8a80; } }
1525
- * { box-sizing: border-box; }
1526
- body { margin:0; background:var(--bg); color:var(--ink); font:15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
1527
- main { max-width:1080px; margin:0 auto; padding:40px 20px 64px; }
1528
- h1 { margin:0 0 20px; font-size:clamp(28px,5vw,44px); line-height:1.1; }
1529
- .cards { display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:16px; }
1530
- .card, section { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:18px; margin:16px 0; }
1531
- .card h2 { margin:0 0 2px; font-size:18px; }
1532
- .id { margin:0 0 10px; color:var(--muted); font-family:ui-monospace, SFMono-Regular, Consolas, monospace; }
1533
- .badge { display:inline-block; padding:3px 10px; border:1px solid currentColor; border-radius:999px; font-size:12px; font-weight:700; }
1534
- .badge.ok { color:var(--ok); } .badge.bad { color:var(--bad); }
1535
- dl { display:grid; grid-template-columns:repeat(auto-fit,minmax(120px,1fr)); gap:8px; margin:16px 0 0; }
1536
- dt { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.06em; }
1537
- dd { margin:2px 0 0; font-weight:700; }
1538
- h2 { margin:0 0 12px; font-size:18px; }
1539
- ul { margin:0; padding-left:20px; }
1540
- code, pre { font-family:ui-monospace, SFMono-Regular, Consolas, monospace; }
1541
- table { width:100%; border-collapse:collapse; }
1542
- th, td { padding:8px; border-top:1px solid var(--line); text-align:left; }
1543
- th { color:var(--muted); font-size:12px; text-transform:uppercase; letter-spacing:.06em; }
1544
- .muted { color:var(--muted); }
1545
- </style>
1546
- </head>
1547
- <body>
1548
- <main>
1549
- <h1>oc-pilot flight compare</h1>
1550
- <div class="cards">${side("A", result.a)}${side("B", result.b)}</div>
1551
- <section><h2>Only in A</h2>${commandList(result.onlyA)}</section>
1552
- <section><h2>Only in B</h2>${commandList(result.onlyB)}</section>
1553
- <section><h2>Exit code differences</h2>${differences}</section>
1554
- <section><h2>Final tree</h2><p>${escapeHtml(tree)}</p></section>
1555
- </main>
1556
- </body>
1557
- </html>`;
1558
- }
1559
- export function renderFlightExport(result) {
1560
- return `[FLIGHT EXPORT] ${result.meta.id}: ${result.events.length} событий, ${result.checkpoints.length} чекпоинтов, ${result.digest.slice(0, 19)}.`;
1561
- }
1562
- export function renderFlightBundleVerify(result) {
1563
- const lines = [
1564
- `[FLIGHT BUNDLE] ${result.format}`,
1565
- `ID: ${result.id ?? "?"}`,
1566
- `Digest: ${result.digestOk ? "ok" : "mismatch"}`,
1567
- `Chain: ${result.chainOk ? "ok" : "broken"}`,
1568
- `Signature: ${result.signature}`,
1569
- ];
1570
- if (result.errors.length > 0) {
1571
- lines.push("", ...result.errors.map((error) => `! ${error}`));
1572
- }
1573
- return lines.join("\n");
1574
- }
1575
- function escapeHtml(value) {
1576
- return String(value).replace(/[&<>"']/g, (character) => {
1577
- if (character === "&")
1578
- return "&amp;";
1579
- if (character === "<")
1580
- return "&lt;";
1581
- if (character === ">")
1582
- return "&gt;";
1583
- if (character === '"')
1584
- return "&quot;";
1585
- return "&#39;";
1586
- });
1587
- }
1588
- function htmlEventDetail(event) {
1589
- const payload = event.payload;
1590
- if (event.kind === "command.end") {
1591
- const parts = [`exit ${String(payload.exitCode ?? "?")}`];
1592
- if (payload.timedOut === true)
1593
- parts.push("timeout");
1594
- if (typeof payload.durationMs === "number")
1595
- parts.push(`${payload.durationMs} ms`);
1596
- return parts.join(" · ");
1597
- }
1598
- if (event.kind === "file.checkpoint") {
1599
- return `commit ${String(payload.commit ?? "").slice(0, 12)}`;
1600
- }
1601
- if (event.kind === "session.end") {
1602
- return `${String(payload.checkpoints ?? 0)} checkpoints · ${String(payload.commands ?? 0)} commands`;
1603
- }
1604
- return "";
1605
- }
1606
- function htmlEventOutput(event) {
1607
- const payload = event.payload;
1608
- const blocks = [];
1609
- for (const [label, key] of [
1610
- ["stdout", "stdoutTail"],
1611
- ["stderr", "stderrTail"],
1612
- ]) {
1613
- const value = payload[key];
1614
- if (typeof value === "string" && value.trim().length > 0) {
1615
- blocks.push(`<details><summary>${label}</summary><pre>${escapeHtml(value)}</pre></details>`);
1616
- }
1617
- }
1618
- return blocks.join("");
1619
- }
1620
- export function renderFlightHtml(result) {
1621
- const meta = result.meta;
1622
- const verification = verifyFlightEvents(result.events);
1623
- const checkpointRows = result.checkpoints.length === 0
1624
- ? `<tr><td colspan="4" class="muted">No checkpoints.</td></tr>`
1625
- : result.checkpoints
1626
- .map((checkpoint) => `<tr>
1627
- <td>${escapeHtml(checkpoint.label)}</td>
1628
- <td><code>${escapeHtml(checkpoint.commit.slice(0, 12))}</code></td>
1629
- <td>${escapeHtml(checkpoint.createdAt)}</td>
1630
- <td>${checkpoint.patch.trim().length > 0
1631
- ? `<details><summary>patch</summary><pre>${escapeHtml(checkpoint.patch)}</pre></details>`
1632
- : `<span class="muted">—</span>`}</td>
1633
- </tr>`)
1634
- .join("\n");
1635
- const timeline = result.events
1636
- .map((event) => {
1637
- const detail = htmlEventDetail(event);
1638
- const output = htmlEventOutput(event);
1639
- return `<li>
1640
- <div class="event-head"><span class="seq">#${event.seq}</span><span class="kind">${escapeHtml(event.kind)}</span><time>${escapeHtml(event.ts)}</time></div>
1641
- <div class="event-title">${escapeHtml(eventSummary(event))}</div>
1642
- ${detail ? `<div class="event-detail">${escapeHtml(detail)}</div>` : ""}
1643
- ${output}
1644
- </li>`;
1645
- })
1646
- .join("\n");
1647
- const errors = verification.valid
1648
- ? ""
1649
- : `<section class="errors"><h2>Chain errors</h2><ul>${verification.errors
1650
- .map((error) => `<li>${escapeHtml(error)}</li>`)
1651
- .join("")}</ul></section>`;
1652
- return `<!doctype html>
1653
- <html lang="en">
1654
- <head>
1655
- <meta charset="utf-8">
1656
- <meta name="viewport" content="width=device-width, initial-scale=1">
1657
- <title>oc-pilot flight ${escapeHtml(meta.id)}</title>
1658
- <style>
1659
- :root { color-scheme: light dark; --bg: #f6f7f9; --card: #ffffff; --ink: #17191d; --muted: #68707d; --line: #d9dde4; --accent: #2457d6; --ok: #177245; --bad: #b42318; }
1660
- @media (prefers-color-scheme: dark) { :root { --bg: #111318; --card: #181b22; --ink: #e8ebf0; --muted: #9aa3b1; --line: #2b303a; --accent: #8ab4ff; --ok: #63d391; --bad: #ff8a80; } }
1661
- * { box-sizing: border-box; }
1662
- body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
1663
- main { max-width: 1080px; margin: 0 auto; padding: 40px 20px 64px; }
1664
- header { border-bottom: 1px solid var(--line); padding-bottom: 20px; margin-bottom: 24px; }
1665
- .eyebrow { color: var(--accent); font-size: 12px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
1666
- h1 { margin: 6px 0 4px; font-size: clamp(28px, 5vw, 44px); line-height: 1.1; }
1667
- .id { margin: 0; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
1668
- .badge { display: inline-block; margin-top: 12px; padding: 3px 10px; border: 1px solid currentColor; border-radius: 999px; font-size: 12px; font-weight: 700; }
1669
- .badge.ok { color: var(--ok); } .badge.bad { color: var(--bad); }
1670
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 24px 0; }
1671
- .grid > div, section { background: var(--card); border: 1px solid var(--line); border-radius: 10px; }
1672
- .grid > div { padding: 12px 14px; }
1673
- .grid span { display: block; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .06em; }
1674
- .grid strong { display: block; margin-top: 4px; overflow-wrap: anywhere; }
1675
- section { padding: 18px; margin: 18px 0; }
1676
- h2 { margin: 0 0 12px; font-size: 18px; }
1677
- table { width: 100%; border-collapse: collapse; }
1678
- th, td { padding: 9px 8px; border-top: 1px solid var(--line); text-align: left; vertical-align: top; }
1679
- th { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .06em; }
1680
- code, pre { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
1681
- pre { margin: 8px 0 0; padding: 12px; overflow: auto; background: var(--bg); border: 1px solid var(--line); border-radius: 8px; font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
1682
- details summary { cursor: pointer; color: var(--accent); }
1683
- .timeline { list-style: none; margin: 0; padding: 0; }
1684
- .timeline li { padding: 12px 0; border-top: 1px solid var(--line); }
1685
- .timeline li:first-child { border-top: 0; }
1686
- .event-head { display: flex; gap: 10px; align-items: baseline; color: var(--muted); font-size: 12px; }
1687
- .seq { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
1688
- .kind { color: var(--accent); font-weight: 700; }
1689
- .event-head time { margin-left: auto; }
1690
- .event-title { margin-top: 3px; font-weight: 600; overflow-wrap: anywhere; }
1691
- .event-detail { color: var(--muted); font-size: 13px; }
1692
- .muted { color: var(--muted); }
1693
- .errors { border-color: var(--bad); }
1694
- .errors h2 { color: var(--bad); }
1695
- footer { color: var(--muted); font-size: 12px; margin-top: 24px; overflow-wrap: anywhere; }
1696
- </style>
1697
- </head>
1698
- <body>
1699
- <main>
1700
- <header>
1701
- <div class="eyebrow">oc-pilot flight</div>
1702
- <h1>${escapeHtml(meta.name)}</h1>
1703
- <p class="id">${escapeHtml(meta.id)}</p>
1704
- <span class="badge ${verification.valid ? "ok" : "bad"}">${verification.valid ? "chain valid" : "chain tampered"}</span>
1705
- </header>
1706
- <div class="grid">
1707
- <div><span>Started</span><strong>${escapeHtml(meta.startedAt)}</strong></div>
1708
- <div><span>Base commit</span><strong>${escapeHtml(meta.baseCommit ?? "none")}</strong></div>
1709
- <div><span>Branch</span><strong>${escapeHtml(meta.branch ?? "none")}</strong></div>
1710
- <div><span>Events</span><strong>${result.events.length}</strong></div>
1711
- <div><span>Checkpoints</span><strong>${result.checkpoints.length}</strong></div>
1712
- <div><span>Digest</span><strong><code>${escapeHtml(result.digest)}</code></strong></div>
1713
- </div>
1714
- ${errors}
1715
- <section>
1716
- <h2>Checkpoints</h2>
1717
- <table>
1718
- <thead><tr><th>Label</th><th>Commit</th><th>Created</th><th>Patch</th></tr></thead>
1719
- <tbody>${checkpointRows}</tbody>
1720
- </table>
1721
- </section>
1722
- <section>
1723
- <h2>Timeline</h2>
1724
- <ol class="timeline">${timeline}</ol>
1725
- </section>
1726
- <footer>Exported ${escapeHtml(result.exportedAt)} · ${escapeHtml(result.format)}</footer>
1727
- </main>
1728
- </body>
1729
- </html>`;
1730
- }
1731
- export function renderFlightCompare(result) {
1732
- const side = (label, value) => `${label}: ${value.name} (${value.id}) - событий ${value.events}, заметок ${value.notes}, команд ${value.commands}, ` +
1733
- `чекпоинтов ${value.checkpoints}, ошибок ${value.failedCommands}, ${value.durationMs} мс, ` +
1734
- `цепочка ${value.valid ? "валидна" : "повреждена"}`;
1735
- const lines = [
1736
- `[FLIGHT COMPARE] ${result.a.id} ↔ ${result.b.id}`,
1737
- side("A", result.a),
1738
- side("B", result.b),
1739
- ];
1740
- if (result.onlyA.length > 0) {
1741
- lines.push(`Только в A: ${result.onlyA.map(commandLabel).join("; ")}`);
1742
- }
1743
- if (result.onlyB.length > 0) {
1744
- lines.push(`Только в B: ${result.onlyB.map(commandLabel).join("; ")}`);
1745
- }
1746
- if (result.common.length > 0) {
1747
- lines.push(`Общие команды: ${result.common.length}.`);
1748
- }
1749
- if (result.exitCodeDifferences.length > 0) {
1750
- lines.push("Расхождения exit code:");
1751
- for (const difference of result.exitCodeDifferences) {
1752
- lines.push(` ${commandLabel(difference.command)}: A ${difference.a ?? "?"}, B ${difference.b ?? "?"}`);
1753
- }
1754
- }
1755
- lines.push(`Итоговое дерево: ${result.sameFinalTree === null
1756
- ? "нет чекпоинтов у одного из полётов"
1757
- : result.sameFinalTree
1758
- ? "совпадает"
1759
- : "различается"}.`);
1760
- return lines.join("\n");
1761
- }
1
+ // Compatibility entry point for the Flight API.
2
+ export { exportFlight, flightShowFromBundle, generateFlightKey, loadFlightBundle, signFlightBundle, verifyFlightBundle, } from "./flight/bundles.js";
3
+ export { renderFlightBundleVerify, renderFlightExport, renderFlightHtml } from "./flight/bundle-report.js";
4
+ export { appendFlightEvent, flightEventHash, readFlightEvents, verifyFlightEvents } from "./flight/events.js";
5
+ export { renderFlightStatsHtml } from "./flight/html-reports.js";
6
+ export { renderFlightCompare, renderFlightCompareHtml } from "./flight/compare-reports.js";
7
+ export { compareFlights, compareFlightShows } from "./flight/comparison.js";
8
+ export { diffFlight, diffFlightBundle, renderFlightBundleDiff, renderFlightDiff } from "./flight/diffs.js";
9
+ export { bisectFlight, proveClaim } from "./flight/proof.js";
10
+ export { renderFlightGrep, renderFlightStats } from "./flight/query-reports.js";
11
+ export { auditFlights, filterFlightEvents, FLIGHT_EVENT_KINDS, flightStats, flightStatus, grepFlightBundle, grepFlights, } from "./flight/queries.js";
12
+ export { createCheckpoint, execInFlight } from "./flight/runner.js";
13
+ export { renderFlightAudit, renderFlightCheckpoint, renderFlightDelete, renderFlightEnd, renderFlightExec, renderFlightList, renderFlightPrune, renderFlightShow, renderFlightStart, renderFlightStatus, renderFlightSummary, renderFlightVerify, } from "./flight/session-reports.js";
14
+ export { activeFlight, addFlightNote, deleteFlight, endFlight, flightsRoot, listFlights, newFlightId, pruneFlights, requireActiveFlight, showFlight, startFlight, } from "./flight/sessions.js";
15
+ export { renderFlightBisect, renderFlightProof, renderFlightReplay, renderFlightRestore } from "./flight/worktree-reports.js";
16
+ export { replayFlight, restoreFlight } from "./flight/worktrees.js";
1762
17
  //# sourceMappingURL=flight.js.map