popeye-cli 1.10.0 → 2.1.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 (326) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/CONTRIBUTING.md +38 -3
  3. package/README.md +104 -18
  4. package/dist/adapters/gemini.js +3 -3
  5. package/dist/adapters/openai.js +2 -2
  6. package/dist/adapters/openai.js.map +1 -1
  7. package/dist/auth/gemini.js +1 -1
  8. package/dist/cli/commands/create.d.ts.map +1 -1
  9. package/dist/cli/commands/create.js +11 -5
  10. package/dist/cli/commands/create.js.map +1 -1
  11. package/dist/cli/commands/resume.d.ts.map +1 -1
  12. package/dist/cli/commands/resume.js +9 -1
  13. package/dist/cli/commands/resume.js.map +1 -1
  14. package/dist/cli/interactive.d.ts.map +1 -1
  15. package/dist/cli/interactive.js +29 -3
  16. package/dist/cli/interactive.js.map +1 -1
  17. package/dist/config/defaults.d.ts.map +1 -1
  18. package/dist/config/defaults.js +7 -2
  19. package/dist/config/defaults.js.map +1 -1
  20. package/dist/config/index.d.ts +1 -7
  21. package/dist/config/index.d.ts.map +1 -1
  22. package/dist/config/popeye-md.d.ts +32 -0
  23. package/dist/config/popeye-md.d.ts.map +1 -0
  24. package/dist/config/popeye-md.js +111 -0
  25. package/dist/config/popeye-md.js.map +1 -0
  26. package/dist/config/schema.d.ts +3 -21
  27. package/dist/config/schema.d.ts.map +1 -1
  28. package/dist/config/schema.js +21 -8
  29. package/dist/config/schema.js.map +1 -1
  30. package/dist/pipeline/artifact-manager.d.ts +47 -0
  31. package/dist/pipeline/artifact-manager.d.ts.map +1 -0
  32. package/dist/pipeline/artifact-manager.js +251 -0
  33. package/dist/pipeline/artifact-manager.js.map +1 -0
  34. package/dist/pipeline/artifact-validators.d.ts +29 -0
  35. package/dist/pipeline/artifact-validators.d.ts.map +1 -0
  36. package/dist/pipeline/artifact-validators.js +173 -0
  37. package/dist/pipeline/artifact-validators.js.map +1 -0
  38. package/dist/pipeline/bridges/review-bridge.d.ts +70 -0
  39. package/dist/pipeline/bridges/review-bridge.d.ts.map +1 -0
  40. package/dist/pipeline/bridges/review-bridge.js +266 -0
  41. package/dist/pipeline/bridges/review-bridge.js.map +1 -0
  42. package/dist/pipeline/change-request.d.ts +47 -0
  43. package/dist/pipeline/change-request.d.ts.map +1 -0
  44. package/dist/pipeline/change-request.js +91 -0
  45. package/dist/pipeline/change-request.js.map +1 -0
  46. package/dist/pipeline/check-runner.d.ts +47 -0
  47. package/dist/pipeline/check-runner.d.ts.map +1 -0
  48. package/dist/pipeline/check-runner.js +417 -0
  49. package/dist/pipeline/check-runner.js.map +1 -0
  50. package/dist/pipeline/command-resolver.d.ts +9 -0
  51. package/dist/pipeline/command-resolver.d.ts.map +1 -0
  52. package/dist/pipeline/command-resolver.js +140 -0
  53. package/dist/pipeline/command-resolver.js.map +1 -0
  54. package/dist/pipeline/consensus/consensus-runner.d.ts +44 -0
  55. package/dist/pipeline/consensus/consensus-runner.d.ts.map +1 -0
  56. package/dist/pipeline/consensus/consensus-runner.js +212 -0
  57. package/dist/pipeline/consensus/consensus-runner.js.map +1 -0
  58. package/dist/pipeline/constitution.d.ts +45 -0
  59. package/dist/pipeline/constitution.d.ts.map +1 -0
  60. package/dist/pipeline/constitution.js +82 -0
  61. package/dist/pipeline/constitution.js.map +1 -0
  62. package/dist/pipeline/gate-engine.d.ts +55 -0
  63. package/dist/pipeline/gate-engine.d.ts.map +1 -0
  64. package/dist/pipeline/gate-engine.js +270 -0
  65. package/dist/pipeline/gate-engine.js.map +1 -0
  66. package/dist/pipeline/index.d.ts +26 -0
  67. package/dist/pipeline/index.d.ts.map +1 -0
  68. package/dist/pipeline/index.js +35 -0
  69. package/dist/pipeline/index.js.map +1 -0
  70. package/dist/pipeline/migration.d.ts +15 -0
  71. package/dist/pipeline/migration.d.ts.map +1 -0
  72. package/dist/pipeline/migration.js +76 -0
  73. package/dist/pipeline/migration.js.map +1 -0
  74. package/dist/pipeline/orchestrator.d.ts +30 -0
  75. package/dist/pipeline/orchestrator.d.ts.map +1 -0
  76. package/dist/pipeline/orchestrator.js +242 -0
  77. package/dist/pipeline/orchestrator.js.map +1 -0
  78. package/dist/pipeline/packets/audit-report-builder.d.ts +11 -0
  79. package/dist/pipeline/packets/audit-report-builder.d.ts.map +1 -0
  80. package/dist/pipeline/packets/audit-report-builder.js +32 -0
  81. package/dist/pipeline/packets/audit-report-builder.js.map +1 -0
  82. package/dist/pipeline/packets/consensus-packet-builder.d.ts +35 -0
  83. package/dist/pipeline/packets/consensus-packet-builder.d.ts.map +1 -0
  84. package/dist/pipeline/packets/consensus-packet-builder.js +80 -0
  85. package/dist/pipeline/packets/consensus-packet-builder.js.map +1 -0
  86. package/dist/pipeline/packets/index.d.ts +12 -0
  87. package/dist/pipeline/packets/index.d.ts.map +1 -0
  88. package/dist/pipeline/packets/index.js +8 -0
  89. package/dist/pipeline/packets/index.js.map +1 -0
  90. package/dist/pipeline/packets/plan-packet-builder.d.ts +21 -0
  91. package/dist/pipeline/packets/plan-packet-builder.d.ts.map +1 -0
  92. package/dist/pipeline/packets/plan-packet-builder.js +27 -0
  93. package/dist/pipeline/packets/plan-packet-builder.js.map +1 -0
  94. package/dist/pipeline/packets/rca-packet-builder.d.ts +19 -0
  95. package/dist/pipeline/packets/rca-packet-builder.d.ts.map +1 -0
  96. package/dist/pipeline/packets/rca-packet-builder.js +22 -0
  97. package/dist/pipeline/packets/rca-packet-builder.js.map +1 -0
  98. package/dist/pipeline/phases/architecture.d.ts +7 -0
  99. package/dist/pipeline/phases/architecture.d.ts.map +1 -0
  100. package/dist/pipeline/phases/architecture.js +60 -0
  101. package/dist/pipeline/phases/architecture.js.map +1 -0
  102. package/dist/pipeline/phases/audit.d.ts +8 -0
  103. package/dist/pipeline/phases/audit.d.ts.map +1 -0
  104. package/dist/pipeline/phases/audit.js +144 -0
  105. package/dist/pipeline/phases/audit.js.map +1 -0
  106. package/dist/pipeline/phases/consensus-architecture.d.ts +7 -0
  107. package/dist/pipeline/phases/consensus-architecture.d.ts.map +1 -0
  108. package/dist/pipeline/phases/consensus-architecture.js +84 -0
  109. package/dist/pipeline/phases/consensus-architecture.js.map +1 -0
  110. package/dist/pipeline/phases/consensus-master-plan.d.ts +7 -0
  111. package/dist/pipeline/phases/consensus-master-plan.d.ts.map +1 -0
  112. package/dist/pipeline/phases/consensus-master-plan.js +81 -0
  113. package/dist/pipeline/phases/consensus-master-plan.js.map +1 -0
  114. package/dist/pipeline/phases/consensus-role-plans.d.ts +7 -0
  115. package/dist/pipeline/phases/consensus-role-plans.d.ts.map +1 -0
  116. package/dist/pipeline/phases/consensus-role-plans.js +85 -0
  117. package/dist/pipeline/phases/consensus-role-plans.js.map +1 -0
  118. package/dist/pipeline/phases/done.d.ts +7 -0
  119. package/dist/pipeline/phases/done.d.ts.map +1 -0
  120. package/dist/pipeline/phases/done.js +45 -0
  121. package/dist/pipeline/phases/done.js.map +1 -0
  122. package/dist/pipeline/phases/implementation.d.ts +8 -0
  123. package/dist/pipeline/phases/implementation.d.ts.map +1 -0
  124. package/dist/pipeline/phases/implementation.js +45 -0
  125. package/dist/pipeline/phases/implementation.js.map +1 -0
  126. package/dist/pipeline/phases/index.d.ts +20 -0
  127. package/dist/pipeline/phases/index.d.ts.map +1 -0
  128. package/dist/pipeline/phases/index.js +19 -0
  129. package/dist/pipeline/phases/index.js.map +1 -0
  130. package/dist/pipeline/phases/intake.d.ts +8 -0
  131. package/dist/pipeline/phases/intake.d.ts.map +1 -0
  132. package/dist/pipeline/phases/intake.js +49 -0
  133. package/dist/pipeline/phases/intake.js.map +1 -0
  134. package/dist/pipeline/phases/phase-context.d.ts +30 -0
  135. package/dist/pipeline/phases/phase-context.d.ts.map +1 -0
  136. package/dist/pipeline/phases/phase-context.js +33 -0
  137. package/dist/pipeline/phases/phase-context.js.map +1 -0
  138. package/dist/pipeline/phases/production-gate.d.ts +8 -0
  139. package/dist/pipeline/phases/production-gate.d.ts.map +1 -0
  140. package/dist/pipeline/phases/production-gate.js +84 -0
  141. package/dist/pipeline/phases/production-gate.js.map +1 -0
  142. package/dist/pipeline/phases/qa-validation.d.ts +7 -0
  143. package/dist/pipeline/phases/qa-validation.d.ts.map +1 -0
  144. package/dist/pipeline/phases/qa-validation.js +50 -0
  145. package/dist/pipeline/phases/qa-validation.js.map +1 -0
  146. package/dist/pipeline/phases/recovery-loop.d.ts +7 -0
  147. package/dist/pipeline/phases/recovery-loop.d.ts.map +1 -0
  148. package/dist/pipeline/phases/recovery-loop.js +93 -0
  149. package/dist/pipeline/phases/recovery-loop.js.map +1 -0
  150. package/dist/pipeline/phases/review.d.ts +8 -0
  151. package/dist/pipeline/phases/review.d.ts.map +1 -0
  152. package/dist/pipeline/phases/review.js +127 -0
  153. package/dist/pipeline/phases/review.js.map +1 -0
  154. package/dist/pipeline/phases/role-planning.d.ts +7 -0
  155. package/dist/pipeline/phases/role-planning.d.ts.map +1 -0
  156. package/dist/pipeline/phases/role-planning.js +75 -0
  157. package/dist/pipeline/phases/role-planning.js.map +1 -0
  158. package/dist/pipeline/phases/stuck.d.ts +7 -0
  159. package/dist/pipeline/phases/stuck.d.ts.map +1 -0
  160. package/dist/pipeline/phases/stuck.js +51 -0
  161. package/dist/pipeline/phases/stuck.js.map +1 -0
  162. package/dist/pipeline/repo-snapshot.d.ts +24 -0
  163. package/dist/pipeline/repo-snapshot.d.ts.map +1 -0
  164. package/dist/pipeline/repo-snapshot.js +343 -0
  165. package/dist/pipeline/repo-snapshot.js.map +1 -0
  166. package/dist/pipeline/role-execution-adapter.d.ts +59 -0
  167. package/dist/pipeline/role-execution-adapter.d.ts.map +1 -0
  168. package/dist/pipeline/role-execution-adapter.js +159 -0
  169. package/dist/pipeline/role-execution-adapter.js.map +1 -0
  170. package/dist/pipeline/skill-loader.d.ts +34 -0
  171. package/dist/pipeline/skill-loader.d.ts.map +1 -0
  172. package/dist/pipeline/skill-loader.js +156 -0
  173. package/dist/pipeline/skill-loader.js.map +1 -0
  174. package/dist/pipeline/skills/defaults.d.ts +16 -0
  175. package/dist/pipeline/skills/defaults.d.ts.map +1 -0
  176. package/dist/pipeline/skills/defaults.js +189 -0
  177. package/dist/pipeline/skills/defaults.js.map +1 -0
  178. package/dist/pipeline/type-defs/artifacts.d.ts +207 -0
  179. package/dist/pipeline/type-defs/artifacts.d.ts.map +1 -0
  180. package/dist/pipeline/type-defs/artifacts.js +67 -0
  181. package/dist/pipeline/type-defs/artifacts.js.map +1 -0
  182. package/dist/pipeline/type-defs/audit.d.ts +259 -0
  183. package/dist/pipeline/type-defs/audit.d.ts.map +1 -0
  184. package/dist/pipeline/type-defs/audit.js +54 -0
  185. package/dist/pipeline/type-defs/audit.js.map +1 -0
  186. package/dist/pipeline/type-defs/checks.d.ts +82 -0
  187. package/dist/pipeline/type-defs/checks.d.ts.map +1 -0
  188. package/dist/pipeline/type-defs/checks.js +38 -0
  189. package/dist/pipeline/type-defs/checks.js.map +1 -0
  190. package/dist/pipeline/type-defs/enums.d.ts +43 -0
  191. package/dist/pipeline/type-defs/enums.d.ts.map +1 -0
  192. package/dist/pipeline/type-defs/enums.js +55 -0
  193. package/dist/pipeline/type-defs/enums.js.map +1 -0
  194. package/dist/pipeline/type-defs/index.d.ts +12 -0
  195. package/dist/pipeline/type-defs/index.d.ts.map +1 -0
  196. package/dist/pipeline/type-defs/index.js +12 -0
  197. package/dist/pipeline/type-defs/index.js.map +1 -0
  198. package/dist/pipeline/type-defs/packets.d.ts +821 -0
  199. package/dist/pipeline/type-defs/packets.d.ts.map +1 -0
  200. package/dist/pipeline/type-defs/packets.js +109 -0
  201. package/dist/pipeline/type-defs/packets.js.map +1 -0
  202. package/dist/pipeline/type-defs/snapshot.d.ts +52 -0
  203. package/dist/pipeline/type-defs/snapshot.d.ts.map +1 -0
  204. package/dist/pipeline/type-defs/snapshot.js +35 -0
  205. package/dist/pipeline/type-defs/snapshot.js.map +1 -0
  206. package/dist/pipeline/type-defs/state.d.ts +455 -0
  207. package/dist/pipeline/type-defs/state.d.ts.map +1 -0
  208. package/dist/pipeline/type-defs/state.js +90 -0
  209. package/dist/pipeline/type-defs/state.js.map +1 -0
  210. package/dist/pipeline/types.d.ts +16 -0
  211. package/dist/pipeline/types.d.ts.map +1 -0
  212. package/dist/pipeline/types.js +16 -0
  213. package/dist/pipeline/types.js.map +1 -0
  214. package/dist/types/audit.d.ts +6 -6
  215. package/dist/types/consensus.d.ts +5 -1
  216. package/dist/types/consensus.d.ts.map +1 -1
  217. package/dist/types/consensus.js +15 -4
  218. package/dist/types/consensus.js.map +1 -1
  219. package/dist/types/index.d.ts +1 -1
  220. package/dist/types/index.d.ts.map +1 -1
  221. package/dist/types/index.js +1 -1
  222. package/dist/types/index.js.map +1 -1
  223. package/dist/types/project.d.ts +1 -1
  224. package/dist/types/project.d.ts.map +1 -1
  225. package/dist/types/project.js +39 -10
  226. package/dist/types/project.js.map +1 -1
  227. package/dist/types/workflow.d.ts +1 -7
  228. package/dist/types/workflow.d.ts.map +1 -1
  229. package/dist/types/workflow.js +1 -1
  230. package/dist/types/workflow.js.map +1 -1
  231. package/dist/upgrade/handlers.js +5 -5
  232. package/dist/upgrade/handlers.js.map +1 -1
  233. package/dist/workflow/index.d.ts.map +1 -1
  234. package/dist/workflow/index.js +52 -0
  235. package/dist/workflow/index.js.map +1 -1
  236. package/dist/workflow/website-strategy.js +1 -1
  237. package/dist/workflow/website-strategy.js.map +1 -1
  238. package/package.json +1 -1
  239. package/skills/PHASE_GATE_ENGINE_SPEC.md +113 -20
  240. package/skills/POPEYE_FULL_AUTONOMY_PIPELINE.md +66 -13
  241. package/src/adapters/gemini.ts +3 -3
  242. package/src/adapters/openai.ts +2 -2
  243. package/src/auth/gemini.ts +1 -1
  244. package/src/cli/commands/create.ts +12 -6
  245. package/src/cli/commands/resume.ts +9 -1
  246. package/src/cli/interactive.ts +32 -3
  247. package/src/config/defaults.ts +7 -2
  248. package/src/config/popeye-md.ts +139 -0
  249. package/src/config/schema.ts +21 -8
  250. package/src/pipeline/artifact-manager.ts +339 -0
  251. package/src/pipeline/artifact-validators.ts +224 -0
  252. package/src/pipeline/bridges/review-bridge.ts +371 -0
  253. package/src/pipeline/change-request.ts +119 -0
  254. package/src/pipeline/check-runner.ts +504 -0
  255. package/src/pipeline/command-resolver.ts +168 -0
  256. package/src/pipeline/consensus/consensus-runner.ts +317 -0
  257. package/src/pipeline/constitution.ts +109 -0
  258. package/src/pipeline/gate-engine.ts +347 -0
  259. package/src/pipeline/index.ts +82 -0
  260. package/src/pipeline/migration.ts +91 -0
  261. package/src/pipeline/orchestrator.ts +322 -0
  262. package/src/pipeline/packets/audit-report-builder.ts +47 -0
  263. package/src/pipeline/packets/consensus-packet-builder.ts +112 -0
  264. package/src/pipeline/packets/index.ts +15 -0
  265. package/src/pipeline/packets/plan-packet-builder.ts +52 -0
  266. package/src/pipeline/packets/rca-packet-builder.ts +38 -0
  267. package/src/pipeline/phases/architecture.ts +73 -0
  268. package/src/pipeline/phases/audit.ts +193 -0
  269. package/src/pipeline/phases/consensus-architecture.ts +104 -0
  270. package/src/pipeline/phases/consensus-master-plan.ts +100 -0
  271. package/src/pipeline/phases/consensus-role-plans.ts +105 -0
  272. package/src/pipeline/phases/done.ts +68 -0
  273. package/src/pipeline/phases/implementation.ts +52 -0
  274. package/src/pipeline/phases/index.ts +21 -0
  275. package/src/pipeline/phases/intake.ts +68 -0
  276. package/src/pipeline/phases/phase-context.ts +86 -0
  277. package/src/pipeline/phases/production-gate.ts +113 -0
  278. package/src/pipeline/phases/qa-validation.ts +63 -0
  279. package/src/pipeline/phases/recovery-loop.ts +120 -0
  280. package/src/pipeline/phases/review.ts +149 -0
  281. package/src/pipeline/phases/role-planning.ts +92 -0
  282. package/src/pipeline/phases/stuck.ts +62 -0
  283. package/src/pipeline/repo-snapshot.ts +395 -0
  284. package/src/pipeline/role-execution-adapter.ts +238 -0
  285. package/src/pipeline/skill-loader.ts +192 -0
  286. package/src/pipeline/skills/defaults.ts +215 -0
  287. package/src/pipeline/type-defs/artifacts.ts +82 -0
  288. package/src/pipeline/type-defs/audit.ts +67 -0
  289. package/src/pipeline/type-defs/checks.ts +47 -0
  290. package/src/pipeline/type-defs/enums.ts +62 -0
  291. package/src/pipeline/type-defs/index.ts +12 -0
  292. package/src/pipeline/type-defs/packets.ts +131 -0
  293. package/src/pipeline/type-defs/snapshot.ts +55 -0
  294. package/src/pipeline/type-defs/state.ts +167 -0
  295. package/src/pipeline/types.ts +16 -0
  296. package/src/types/consensus.ts +16 -4
  297. package/src/types/index.ts +1 -0
  298. package/src/types/project.ts +39 -10
  299. package/src/types/workflow.ts +1 -1
  300. package/src/upgrade/handlers.ts +5 -5
  301. package/src/workflow/index.ts +52 -0
  302. package/src/workflow/website-strategy.ts +1 -1
  303. package/tests/cli/model-command.test.ts +19 -9
  304. package/tests/config/config.test.ts +3 -3
  305. package/tests/config/popeye-md.test.ts +168 -0
  306. package/tests/pipeline/artifact-manager.test.ts +183 -0
  307. package/tests/pipeline/artifact-validators.test.ts +207 -0
  308. package/tests/pipeline/bridges/review-bridge.test.ts +243 -0
  309. package/tests/pipeline/change-request.test.ts +180 -0
  310. package/tests/pipeline/check-runner.test.ts +157 -0
  311. package/tests/pipeline/command-resolver.test.ts +159 -0
  312. package/tests/pipeline/consensus-runner.test.ts +206 -0
  313. package/tests/pipeline/consensus-scoring.test.ts +163 -0
  314. package/tests/pipeline/constitution.test.ts +122 -0
  315. package/tests/pipeline/gate-engine.test.ts +195 -0
  316. package/tests/pipeline/migration.test.ts +133 -0
  317. package/tests/pipeline/orchestrator.test.ts +614 -0
  318. package/tests/pipeline/packets/builders.test.ts +347 -0
  319. package/tests/pipeline/repo-snapshot.test.ts +189 -0
  320. package/tests/pipeline/role-execution-adapter.test.ts +299 -0
  321. package/tests/pipeline/session-guidance.test.ts +205 -0
  322. package/tests/pipeline/skill-loader.test.ts +186 -0
  323. package/tests/pipeline/start-env-checks.test.ts +123 -0
  324. package/tests/pipeline/types.test.ts +156 -0
  325. package/tests/types/consensus.test.ts +1 -1
  326. package/tests/workflow/pipeline-bootstrap.test.ts +162 -0
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Review Bridge — connects /review (rich audit-mode scanner) to the pipeline
3
+ * artifact + CR system when a project is pipeline-managed.
4
+ *
5
+ * When pipeline state exists, /review produces pipeline-native audit_report
6
+ * artifacts and Change Requests instead of injecting recovery milestones
7
+ * into state.json. This keeps the pipeline as the single source of truth.
8
+ */
9
+
10
+ import { randomUUID } from 'node:crypto';
11
+ import type { ProjectState } from '../../types/workflow.js';
12
+ import type {
13
+ PipelineState,
14
+ PipelinePhase,
15
+ ArtifactEntry,
16
+ ArtifactRef,
17
+ } from '../types.js';
18
+ import type { AuditFinding as WorkflowAuditFinding, AuditCategory as WorkflowCategory, AuditSeverity as WorkflowSeverity } from '../../types/audit.js';
19
+ import type { AuditFinding as PipelineAuditFinding, AuditSeverity as PipelineSeverity } from '../type-defs/audit.js';
20
+ import type { ChangeRequest } from '../types.js';
21
+ import { createArtifactManager } from '../artifact-manager.js';
22
+ import { buildChangeRequest, formatChangeRequest, routeChangeRequest } from '../change-request.js';
23
+ import { generateRepoSnapshot, createSnapshotArtifact } from '../repo-snapshot.js';
24
+ import { scanProject } from '../../workflow/audit-scanner.js';
25
+ import { analyzeProject, calculateAuditScores } from '../../workflow/audit-analyzer.js';
26
+ import { buildSummaryReport, buildAuditReport } from '../../workflow/audit-reporter.js';
27
+ import { loadProject, updateState } from '../../state/index.js';
28
+
29
+ // ─── Types ───────────────────────────────────────────────
30
+
31
+ export interface ReviewBridgeOptions {
32
+ projectDir: string;
33
+ depth?: number;
34
+ strict?: boolean;
35
+ onProgress?: (stage: string, message: string) => void;
36
+ }
37
+
38
+ export interface ReviewBridgeResult {
39
+ success: boolean;
40
+ findingsCount: number;
41
+ changeRequestCount: number;
42
+ overallScore: number;
43
+ recommendation: string;
44
+ artifactsCreated: number;
45
+ error?: string;
46
+ }
47
+
48
+ // ─── Pipeline Detection ──────────────────────────────────
49
+
50
+ /**
51
+ * Check if a project is pipeline-managed.
52
+ * A project is pipeline-managed if its state has a pipeline object
53
+ * with a pipelinePhase field.
54
+ *
55
+ * @param state - The project state to check
56
+ * @returns True if pipeline-managed
57
+ */
58
+ export function isPipelineManaged(state: ProjectState): boolean {
59
+ const pipeline = (state as unknown as { pipeline?: PipelineState }).pipeline;
60
+ return !!pipeline?.pipelinePhase;
61
+ }
62
+
63
+ /**
64
+ * Extract pipeline state from project state.
65
+ *
66
+ * @param state - The project state
67
+ * @returns Pipeline state or undefined
68
+ */
69
+ export function extractPipelineState(state: ProjectState): PipelineState | undefined {
70
+ return (state as unknown as { pipeline?: PipelineState }).pipeline;
71
+ }
72
+
73
+ // ─── Severity Mapping ────────────────────────────────────
74
+
75
+ /** Map workflow audit severity to pipeline severity */
76
+ const SEVERITY_MAP: Record<WorkflowSeverity, PipelineSeverity> = {
77
+ critical: 'P0',
78
+ major: 'P1',
79
+ minor: 'P2',
80
+ info: 'P3',
81
+ };
82
+
83
+ export function mapSeverity(severity: WorkflowSeverity): PipelineSeverity {
84
+ return SEVERITY_MAP[severity];
85
+ }
86
+
87
+ // ─── Category Mapping ────────────────────────────────────
88
+
89
+ /** Map workflow audit categories to pipeline audit categories */
90
+ type PipelineCategory = 'integration' | 'config' | 'tests' | 'schema' | 'security' | 'deployment';
91
+
92
+ const CATEGORY_MAP: Record<WorkflowCategory, PipelineCategory> = {
93
+ 'feature-completeness': 'integration',
94
+ 'integration-wiring': 'integration',
95
+ 'test-coverage': 'tests',
96
+ 'config-deployment': 'config',
97
+ 'dependency-sanity': 'deployment',
98
+ 'consistency': 'schema',
99
+ 'security': 'security',
100
+ 'documentation': 'deployment',
101
+ };
102
+
103
+ export function mapCategory(category: WorkflowCategory): PipelineCategory {
104
+ return CATEGORY_MAP[category];
105
+ }
106
+
107
+ // ─── CR Routing ──────────────────────────────────────────
108
+
109
+ /** Determine CR change_type from pipeline audit category */
110
+ const CATEGORY_TO_CHANGE_TYPE: Record<PipelineCategory, ChangeRequest['change_type']> = {
111
+ integration: 'architecture',
112
+ schema: 'architecture',
113
+ security: 'requirement',
114
+ tests: 'config',
115
+ config: 'config',
116
+ deployment: 'config',
117
+ };
118
+
119
+ export function categoryToChangeType(category: PipelineCategory): ChangeRequest['change_type'] {
120
+ return CATEGORY_TO_CHANGE_TYPE[category];
121
+ }
122
+
123
+ // ─── Finding Conversion ──────────────────────────────────
124
+
125
+ /**
126
+ * Convert a workflow AuditFinding to a pipeline AuditFinding.
127
+ *
128
+ * @param finding - Workflow finding
129
+ * @param snapshotRef - Pipeline artifact ref for the repo snapshot
130
+ * @returns Pipeline-native audit finding
131
+ */
132
+ export function convertFinding(
133
+ finding: WorkflowAuditFinding,
134
+ snapshotRef: ArtifactRef,
135
+ ): PipelineAuditFinding {
136
+ const severity = mapSeverity(finding.severity);
137
+ return {
138
+ id: finding.id,
139
+ severity,
140
+ category: mapCategory(finding.category),
141
+ description: `${finding.title}: ${finding.description}`,
142
+ evidence: [snapshotRef],
143
+ file_path: finding.evidence[0]?.file,
144
+ line_number: finding.evidence[0]?.line,
145
+ suggested_owner: 'AUDITOR',
146
+ blocking: severity === 'P0' || severity === 'P1',
147
+ };
148
+ }
149
+
150
+ // ─── Bridge Orchestrator ─────────────────────────────────
151
+
152
+ /**
153
+ * Run /review through the pipeline bridge.
154
+ * Uses the rich audit-mode scanner but writes results as pipeline artifacts
155
+ * and creates Change Requests for blocking findings.
156
+ *
157
+ * Does NOT inject recovery milestones — the pipeline RECOVERY_LOOP handles fixes.
158
+ *
159
+ * @param options - Bridge options
160
+ * @returns Bridge result with counts and score
161
+ */
162
+ export async function runReviewBridge(options: ReviewBridgeOptions): Promise<ReviewBridgeResult> {
163
+ const { projectDir, onProgress } = options;
164
+ const depth = options.depth ?? 2;
165
+ const strict = options.strict ?? false;
166
+
167
+ try {
168
+ // 1. Load state and extract pipeline
169
+ const state = await loadProject(projectDir);
170
+ const pipeline = extractPipelineState(state);
171
+ if (!pipeline) {
172
+ return { success: false, findingsCount: 0, changeRequestCount: 0, overallScore: 0, recommendation: 'error', artifactsCreated: 0, error: 'No pipeline state found' };
173
+ }
174
+
175
+ const artifactManager = createArtifactManager(projectDir);
176
+ artifactManager.ensureDocsStructure();
177
+ const artifacts: ArtifactEntry[] = [];
178
+
179
+ // 2. Generate fresh repo snapshot (pipeline anchor)
180
+ onProgress?.('bridge', 'Generating repo snapshot...');
181
+ const snapshot = await generateRepoSnapshot(projectDir);
182
+ const snapshotEntry = createSnapshotArtifact(snapshot, artifactManager, 'AUDIT');
183
+ artifacts.push(snapshotEntry);
184
+ pipeline.latestRepoSnapshot = artifactManager.toArtifactRef(snapshotEntry);
185
+ const snapshotRef = artifactManager.toArtifactRef(snapshotEntry);
186
+
187
+ // 3. Run rich audit-mode scanner (Stage 1: Scan)
188
+ onProgress?.('bridge', 'Running project scan...');
189
+ const scan = await scanProject(
190
+ projectDir,
191
+ state.language,
192
+ (msg) => onProgress?.('bridge-scan', msg),
193
+ );
194
+ const summary = buildSummaryReport(scan, state);
195
+
196
+ onProgress?.(
197
+ 'bridge',
198
+ `Scan complete: ${scan.totalSourceFiles} source files, ${scan.totalLinesOfCode} LOC`,
199
+ );
200
+
201
+ // 4. Run AI analysis (Stage 2: Analyze)
202
+ onProgress?.('bridge', 'Running AI analysis...');
203
+ const { findings: workflowFindings, searchMetadata } = await analyzeProject(scan, state, {
204
+ depth,
205
+ strict,
206
+ projectDir,
207
+ });
208
+ const scores = calculateAuditScores(workflowFindings, scan);
209
+ const auditReport = buildAuditReport(summary, workflowFindings, scores, searchMetadata, { strict }, randomUUID());
210
+
211
+ onProgress?.(
212
+ 'bridge',
213
+ `Analysis complete: score ${scores.overallScore}%, ${workflowFindings.length} findings`,
214
+ );
215
+
216
+ // 5. Convert findings to pipeline format
217
+ const pipelineFindings = workflowFindings.map((f) => convertFinding(f, snapshotRef));
218
+
219
+ // 6. Build pipeline audit report and store as artifact
220
+ const pipelineAuditReport = {
221
+ audit_id: `audit-${randomUUID().split('-')[0]}`,
222
+ timestamp: new Date().toISOString(),
223
+ repo_snapshot: snapshotRef,
224
+ overall_status: (auditReport.recommendation === 'pass' ? 'PASS' : 'FAIL') as 'PASS' | 'FAIL',
225
+ findings: pipelineFindings,
226
+ system_risk_score: 100 - scores.overallScore,
227
+ recovery_required: auditReport.recommendation === 'major-rework',
228
+ };
229
+
230
+ const auditJsonEntry = artifactManager.createAndStoreJson(
231
+ 'audit_report',
232
+ pipelineAuditReport,
233
+ 'AUDIT',
234
+ );
235
+ artifacts.push(auditJsonEntry);
236
+
237
+ // Store raw text report too
238
+ const textReport = formatAuditSummary(pipelineFindings, scores.overallScore, auditReport.recommendation);
239
+ const auditTextEntry = artifactManager.createAndStoreText(
240
+ 'audit_report',
241
+ textReport,
242
+ 'AUDIT',
243
+ );
244
+ artifacts.push(auditTextEntry);
245
+
246
+ // 7. Create Change Requests for blocking findings
247
+ const changeRequests: ChangeRequest[] = [];
248
+ const blockingFindings = pipelineFindings.filter((f) => f.blocking);
249
+
250
+ if (blockingFindings.length > 0) {
251
+ // Group by category for targeted CRs
252
+ const byCategory = new Map<string, typeof pipelineFindings>();
253
+ for (const f of blockingFindings) {
254
+ const group = byCategory.get(f.category) ?? [];
255
+ group.push(f);
256
+ byCategory.set(f.category, group);
257
+ }
258
+
259
+ for (const [category, findings] of byCategory) {
260
+ const changeType = categoryToChangeType(category as PipelineCategory);
261
+ const cr = buildChangeRequest({
262
+ originPhase: 'AUDIT',
263
+ requestedBy: 'AUDITOR',
264
+ changeType,
265
+ description: `${findings.length} blocking ${category} finding(s): ${findings.map((f) => f.description.slice(0, 80)).join('; ')}`,
266
+ justification: 'Blocking audit findings from /review require pipeline resolution',
267
+ affectedArtifacts: [snapshotRef],
268
+ affectedPhases: getAffectedPhases(category as PipelineCategory),
269
+ riskLevel: findings.some((f) => f.severity === 'P0') ? 'high' : 'medium',
270
+ });
271
+ changeRequests.push(cr);
272
+
273
+ // Store CR as artifact
274
+ const crEntry = artifactManager.createAndStoreText(
275
+ 'change_request',
276
+ formatChangeRequest(cr),
277
+ 'AUDIT',
278
+ );
279
+ artifacts.push(crEntry);
280
+
281
+ // Register in pipeline state for orchestrator routing
282
+ if (!pipeline.pendingChangeRequests) {
283
+ pipeline.pendingChangeRequests = [];
284
+ }
285
+ pipeline.pendingChangeRequests.push({
286
+ cr_id: cr.cr_id,
287
+ change_type: cr.change_type,
288
+ target_phase: routeChangeRequest(cr),
289
+ status: 'proposed',
290
+ });
291
+ }
292
+ }
293
+
294
+ // 8. Persist pipeline state
295
+ pipeline.artifacts.push(...artifacts);
296
+
297
+ // Update INDEX.md
298
+ artifactManager.updateIndex(pipeline.artifacts);
299
+
300
+ // Save updated state (pipeline object is a reference on state)
301
+ await updateState(projectDir, {
302
+ auditReportPath: auditJsonEntry.path,
303
+ auditLastRunAt: new Date().toISOString(),
304
+ auditRunId: pipelineAuditReport.audit_id,
305
+ } as Partial<ProjectState>);
306
+
307
+ onProgress?.(
308
+ 'bridge',
309
+ `Bridge complete: ${artifacts.length} artifacts, ${changeRequests.length} CRs created`,
310
+ );
311
+
312
+ return {
313
+ success: true,
314
+ findingsCount: pipelineFindings.length,
315
+ changeRequestCount: changeRequests.length,
316
+ overallScore: scores.overallScore,
317
+ recommendation: auditReport.recommendation,
318
+ artifactsCreated: artifacts.length,
319
+ };
320
+ } catch (err) {
321
+ const error = err instanceof Error ? err.message : 'Unknown error';
322
+ return { success: false, findingsCount: 0, changeRequestCount: 0, overallScore: 0, recommendation: 'error', artifactsCreated: 0, error };
323
+ }
324
+ }
325
+
326
+ // ─── Helpers ─────────────────────────────────────────────
327
+
328
+ /** Get affected phases for a finding category */
329
+ function getAffectedPhases(category: PipelineCategory): PipelinePhase[] {
330
+ switch (category) {
331
+ case 'integration':
332
+ case 'schema':
333
+ return ['CONSENSUS_ARCHITECTURE', 'IMPLEMENTATION'];
334
+ case 'security':
335
+ return ['CONSENSUS_MASTER_PLAN', 'IMPLEMENTATION'];
336
+ case 'tests':
337
+ return ['QA_VALIDATION'];
338
+ case 'config':
339
+ case 'deployment':
340
+ return ['IMPLEMENTATION', 'PRODUCTION_GATE'];
341
+ }
342
+ }
343
+
344
+ /** Format a text summary of pipeline audit findings */
345
+ function formatAuditSummary(
346
+ findings: PipelineAuditFinding[],
347
+ score: number,
348
+ recommendation: string,
349
+ ): string {
350
+ const lines = [
351
+ '# Pipeline Audit Report (via /review bridge)',
352
+ '',
353
+ `**Score:** ${score}%`,
354
+ `**Recommendation:** ${recommendation}`,
355
+ `**Findings:** ${findings.length}`,
356
+ `**Blocking:** ${findings.filter((f) => f.blocking).length}`,
357
+ '',
358
+ '## Findings',
359
+ '',
360
+ ];
361
+
362
+ for (const f of findings) {
363
+ lines.push(`### [${f.severity}] ${f.description.slice(0, 120)}`);
364
+ lines.push(`- Category: ${f.category}`);
365
+ lines.push(`- Blocking: ${f.blocking ? 'Yes' : 'No'}`);
366
+ if (f.file_path) lines.push(`- File: ${f.file_path}${f.line_number ? `:${f.line_number}` : ''}`);
367
+ lines.push('');
368
+ }
369
+
370
+ return lines.join('\n');
371
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Change Request mechanism — structured change tracking for mid-pipeline modifications.
3
+ * CRs are created when drift is detected (REVIEW) or architectural issues found (AUDIT).
4
+ * Each CR routes to the appropriate consensus phase for approval.
5
+ */
6
+
7
+ import { randomUUID } from 'node:crypto';
8
+
9
+ import type {
10
+ PipelinePhase,
11
+ PipelineRole,
12
+ ArtifactRef,
13
+ ChangeRequest,
14
+ } from './types.js';
15
+
16
+ // ─── CR Builder ──────────────────────────────────────────
17
+
18
+ export interface BuildChangeRequestArgs {
19
+ originPhase: PipelinePhase;
20
+ requestedBy: PipelineRole;
21
+ changeType: ChangeRequest['change_type'];
22
+ description: string;
23
+ justification: string;
24
+ affectedArtifacts: ArtifactRef[];
25
+ affectedPhases: PipelinePhase[];
26
+ riskLevel: 'low' | 'medium' | 'high';
27
+ }
28
+
29
+ /**
30
+ * Build a change request with generated ID and timestamp.
31
+ *
32
+ * Args:
33
+ * args: Change request parameters.
34
+ *
35
+ * Returns:
36
+ * A fully formed ChangeRequest in 'proposed' status.
37
+ */
38
+ export function buildChangeRequest(args: BuildChangeRequestArgs): ChangeRequest {
39
+ return {
40
+ cr_id: `CR-${randomUUID().split('-')[0].toUpperCase()}`,
41
+ timestamp: new Date().toISOString(),
42
+ origin_phase: args.originPhase,
43
+ requested_by: args.requestedBy,
44
+ change_type: args.changeType,
45
+ description: args.description,
46
+ justification: args.justification,
47
+ impact_analysis: {
48
+ affected_artifacts: args.affectedArtifacts,
49
+ affected_phases: args.affectedPhases,
50
+ risk_level: args.riskLevel,
51
+ },
52
+ status: 'proposed',
53
+ };
54
+ }
55
+
56
+ // ─── CR Routing ──────────────────────────────────────────
57
+
58
+ /** Maps change types to the consensus phase that must approve them */
59
+ const CHANGE_TYPE_ROUTING: Record<ChangeRequest['change_type'], PipelinePhase> = {
60
+ scope: 'CONSENSUS_MASTER_PLAN',
61
+ architecture: 'CONSENSUS_ARCHITECTURE',
62
+ dependency: 'CONSENSUS_ROLE_PLANS',
63
+ config: 'QA_VALIDATION',
64
+ requirement: 'CONSENSUS_MASTER_PLAN',
65
+ };
66
+
67
+ /**
68
+ * Determine which consensus phase should review a change request.
69
+ *
70
+ * Args:
71
+ * cr: The change request to route.
72
+ *
73
+ * Returns:
74
+ * The pipeline phase that should handle the CR approval.
75
+ */
76
+ export function routeChangeRequest(cr: ChangeRequest): PipelinePhase {
77
+ return CHANGE_TYPE_ROUTING[cr.change_type];
78
+ }
79
+
80
+ // ─── CR Formatting ───────────────────────────────────────
81
+
82
+ /**
83
+ * Format a change request as markdown for inclusion in artifacts.
84
+ *
85
+ * Args:
86
+ * cr: The change request to format.
87
+ *
88
+ * Returns:
89
+ * Markdown-formatted string.
90
+ */
91
+ export function formatChangeRequest(cr: ChangeRequest): string {
92
+ const lines = [
93
+ `# Change Request ${cr.cr_id}`,
94
+ '',
95
+ `**Status:** ${cr.status}`,
96
+ `**Type:** ${cr.change_type}`,
97
+ `**Origin Phase:** ${cr.origin_phase}`,
98
+ `**Requested By:** ${cr.requested_by}`,
99
+ `**Risk Level:** ${cr.impact_analysis.risk_level}`,
100
+ `**Timestamp:** ${cr.timestamp}`,
101
+ '',
102
+ '## Description',
103
+ cr.description,
104
+ '',
105
+ '## Justification',
106
+ cr.justification,
107
+ '',
108
+ '## Impact Analysis',
109
+ `- Affected phases: ${cr.impact_analysis.affected_phases.join(', ')}`,
110
+ `- Affected artifacts: ${cr.impact_analysis.affected_artifacts.length}`,
111
+ `- Risk level: ${cr.impact_analysis.risk_level}`,
112
+ ];
113
+
114
+ if (cr.approval_artifact) {
115
+ lines.push('', `## Approval: ${cr.approval_artifact.artifact_id}`);
116
+ }
117
+
118
+ return lines.join('\n');
119
+ }